varHcn=Object.create;varIQ=Object.defineProperty;varWcn=Object.getOwnPropertyDescriptor;varJcn=Object.getOwnPropertyNames;varKcn=Object.getPrototypeOf,Gcn=Object.prototype.hasOwnProperty;varlCt=t=>{throwTypeError(t)};varXcn=(t,e,r)=>eint?IQ(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;varv=(t,e)=>()=>(t&&(e=t(t=0)),e);varS=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),En=(t,e)=>{for(varrine)IQ(t,r,{get:e[r],enumerable:!0})},cCt=(t,e,r,n)=>{if(e&&typeofe=="object"||typeofe=="function")for(letoofJcn(e))!Gcn.call(t,o)&&o!==r&&IQ(t,o,{get:()=>e[o],enumerable:!(n=Wcn(e,o))||n.enumerable});returnt};var$=(t,e,r)=>(r=t!=null?Hcn(Kcn(t)):{},cCt(e||!t||!t.__esModule?IQ(r,"default",{value:t,enumerable:!0}):r,t)),Bpe=t=>cCt(IQ({},"__esModule",{value:!0}),t);varx=(t,e,r)=>Xcn(t,typeofe!="symbol"?e+"":e,r),Zcn=(t,e,r)=>e.has(t)||lCt("Cannot "+r);varcBe=(t,e,r)=>e.has(t)?lCt("Cannot add the same private member more than once"):einstanceofWeakSet?e.add(t):e.set(t,r);vardCt=(t,e,r)=>(Zcn(t,e,"access private method"),r);functiondBe(){if(!zpe&&(zpe=typeofcrypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!zpe))thrownewError("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");returnzpe(Ycn)}varzpe,Ycn,fCt=v(()=>{Ycn=newUint8Array(16)});functionpCt(t,e=0){returnSg[t[e+0]]+Sg[t[e+1]]+Sg[t[e+2]]+Sg[t[e+3]]+"-"+Sg[t[e+4]]+Sg[t[e+5]]+"-"+Sg[t[e+6]]+Sg[t[e+7]]+"-"+Sg[t[e+8]]+Sg[t[e+9]]+"-"+Sg[t[e+10]]+Sg[t[e+11]]+Sg[t[e+12]]+Sg[t[e+13]]+Sg[t[e+14]]+Sg[t[e+15]]}varSg,mCt=v(()=>{Sg=[];for(lett=0;t<256;++t)Sg.push((t+256).toString(16).slice(1))});varQcn,fBe,hCt=v(()=>{Qcn=typeofcrypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),fBe={randomUUID:Qcn}});functionedn(t,e,r){if(fBe.randomUUID&&!e&&!t)returnfBe.randomUUID();t=t||{};letn=t.random||(t.rng||dBe)();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}returnpCt(n)}varod,gCt=v(()=>{hCt();fCt();mCt();od=edn});varqN=v(()=>{gCt()});vartdn,$t,Jo=v(()=>{tdn=Object.defineProperty,$t=(t,e)=>{for(varrine)tdn(t,r,{get:e[r],enumerable:!0})}});functionAQ(t,e=Mz){t=t.trim();letr=t.indexOf("```");if(r===-1)returne(t);letn=t.substring(r+3);n.startsWith(`json
`)&&(n=n.substring(1));leto=n.indexOf("```"),i=n;returno!==-1&&(i=n.substring(0,o)),e(i.trim())}functionrdn(t){try{returnJSON.parse(t)}catch{}lete=t.trim();if(e.length===0)thrownewError("Unexpected end of JSON input");letr=0;functionn(){for(;r<e.length&&/\s/.test(e[r]);)r+=1}functiono(){if(e[r]!=='"')thrownewError(`Expected '"' at position ${r}, got '${e[r]}'`);r+=1;letc="",d=!1;for(;r<e.length;){letf=e[r];if(d){if(f==="n")c+=`
`;elseif(f==="t")c+=" ";elseif(f==="r")c+="\r";elseif(f==="\\")c+="\\";elseif(f==='"')c+='"';elseif(f==="b")c+="\b";elseif(f==="f")c+="\f";elseif(f==="/")c+="/";elseif(f==="u"){letp=e.substring(r+1,r+5);if(/^[0-9A-Fa-f]{0,4}$/.test(p))p.length===4?c+=String.fromCharCode(Number.parseInt(p,16)):c+=`u${p}`,r+=p.length;elsethrownewError(`Invalid unicode escape sequence '\\u${p}' at position ${r}`)}elsethrownewError(`Invalid escape sequence '\\${f}' at position ${r}`);d=!1}elseif(f==="\\")d=!0;else{if(f==='"')returnr+=1,c;c+=f}r+=1}returnd&&(c+="\\"),c}functioni(){letc=r,d="";if(e[r]==="-"&&(d+="-",r+=1),r<e.length&&e[r]==="0"&&(d+="0",r+=1,e[r]>="0"&&e[r]<="9"))thrownewError(`Invalid number at position ${c}`);if(r<e.length&&e[r]>="1"&&e[r]<="9")for(;r<e.length&&e[r]>="0"&&e[r]<="9";)d+=e[r],r+=1;if(r<e.length&&e[r]===".")for(d+=".",r+=1;r<e.length&&e[r]>="0"&&e[r]<="9";)d+=e[r],r+=1;if(r<e.length&&(e[r]==="e"||e[r]==="E"))for(d+=e[r],r+=1,r<e.length&&(e[r]==="+"||e[r]==="-")&&(d+=e[r],r+=1);r<e.length&&e[r]>="0"&&e[r]<="9";)d+=e[r],r+=1;if(d==="-")return-0;letf=Number.parseFloat(d);if(Number.isNaN(f))throwr=c,newError(`Invalid number '${d}' at position ${c}`);returnf}functiona(){if(n(),r>=e.length)thrownewError(`Unexpected end of input at position ${r}`);letc=e[r];if(c==="{")returnu();if(c==="[")returns();if(c==='"')returno();if("null".startsWith(e.substring(r,r+4)))returnr+=Math.min(4,e.length-r),null;if("true".startsWith(e.substring(r,r+4)))returnr+=Math.min(4,e.length-r),!0;if("false".startsWith(e.substring(r,r+5)))returnr+=Math.min(5,e.length-r),!1;if(c==="-"||c>="0"&&c<="9")returni();thrownewError(`Unexpected character '${c}' at position ${r}`)}functions(){if(e[r]!=="[")thrownewError(`Expected '[' at position ${r}, got '${e[r]}'`);letc=[];if(r+=1,n(),r>=e.length)returnc;if(e[r]==="]")returnr+=1,c;for(;r<e.length;){if(n(),r>=e.length||(c.push(a()),n(),r>=e.length))returnc;if(e[r]==="]")returnr+=1,c;if(e[r]===","){r+=1;continue}thrownewError(`Expected ',' or ']' at position ${r}, got '${e[r]}'`)}returnc}functionu(){if(e[r]!=="{")thrownewError(`Expected '{' at position ${r}, got '${e[r]}'`);letc={};if(r+=1,n(),r>=e.length)returnc;if(e[r]==="}")returnr+=1,c;for(;r<e.length;){if(n(),r>=e.length)returnc;letd=o();if(n(),r>=e.length)returnc;if(e[r]!==":")thrownewError(`Expected ':' at position ${r}, got '${e[r]}'`);if(r+=1,n(),r>=e.length||(c[d]=a(),n(),r>=e.length))returnc;if(e[r]==="}")returnr+=1,c;if(e[r]===","){r+=1;continue}thrownewError(`Expected ',' or '}' at position ${r}, got '${e[r]}'`)}returnc}letl=a();if(n(),r<e.length)thrownewError(`Unexpected character '${e[r]}' at position ${r}`);returnl}functionMz(t){try{returntypeoft>"u"?null:rdn(t)}catch{returnnull}}varNQ=v(()=>{});functionFL(t,e){returnt.lc_error_code=e,t.message=`${t.message}
`,t}varDQ=v(()=>{});varbCt=S((ZCi,yCt)=>{"use strict";yCt.exports=function(t,e){if(typeoft!="string")thrownewTypeError("Expected a string");returne=typeofe>"u"?"_":e,t.replace(/([a-z\d])([A-Z])/g,"$1"+e+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+e+"$2").toLowerCase()}});varTCt=S((YCi,pBe)=>{"use strict";varndn=/[\p{Lu}]/u,odn=/[\p{Ll}]/u,_Ct=/^[\p{Lu}](?![\p{Lu}])/gu,SCt=/([\p{Alpha}\p{N}_]|$)/u,CCt=/[_.\- ]+/,idn=newRegExp("^"+CCt.source),vCt=newRegExp(CCt.source+SCt.source,"gu"),wCt=newRegExp("\\d+"+SCt.source,"gu"),adn=(t,e,r)=>{letn=!1,o=!1,i=!1;for(leta=0;a<t.length;a++){lets=t[a];n&&ndn.test(s)?(t=t.slice(0,a)+"-"+t.slice(a),n=!1,i=o,o=!0,a++):o&&i&&odn.test(s)?(t=t.slice(0,a-1)+"-"+t.slice(a-1),i=o,o=!1,n=!0):(n=e(s)===s&&r(s)!==s,i=o,o=r(s)===s&&e(s)!==s)}returnt},sdn=(t,e)=>(_Ct.lastIndex=0,t.replace(_Ct,r=>e(r))),udn=(t,e)=>(vCt.lastIndex=0,wCt.lastIndex=0,t.replace(vCt,(r,n)=>e(n)).replace(wCt,r=>e(r))),xCt=(t,e)=>{if(!(typeoft=="string"||Array.isArray(t)))thrownewTypeError("Expected the input to be `string | string[]`");if(e={pascalCase:!1,preserveConsecutiveUppercase:!1,...e},Array.isArray(t)?t=t.map(i=>i.trim()).filter(i=>i.length).join("-"):t=t.trim(),t.length===0)return"";letr=e.locale===!1?i=>i.toLowerCase():i=>i.toLocaleLowerCase(e.locale),n=e.locale===!1?i=>i.toUpperCase():i=>i.toLocaleUpperCase(e.locale);returnt.length===1?e.pascalCase?n(t):r(t):(t!==r(t)&&(t=adn(t,r,n)),t=t.replace(idn,""),e.preserveConsecutiveUppercase?t=sdn(t,r):t=r(t),e.pascalCase&&(t=n(t.charAt(0))+t.slice(1)),udn(t,n))};pBe.exports=xCt;pBe.exports.default=xCt});functionECt(t,e){returne?.[t]||(0,OCt.default)(t)}functionPCt(t,e,r){letn={};for(letoint)Object.hasOwn(t,o)&&(n[e(o,r)]=t[o]);returnn}varOCt,ldn,MCt=v(()=>{OCt=$(bCt(),1),ldn=$(TCt(),1)});functioncdn(t){return"lc"int||Object.keys(t).length===1&&RCtint}functionddn(t){return{[RCt]:t}}functionfdn(t){returnt!==null&&typeoft=="object"&&"lc_serializable"int&&typeoft.toJSON=="function"}functionpdn(t){lete;returnt!==null&&typeoft=="object"?"lc_id"int&&Array.isArray(t.lc_id)?e=t.lc_id:e=[t.constructor?.name??"Object"]:e=[typeoft],{lc:1,type:"not_implemented",id:e}}functionVpe(t,e=newWeakSet){if(t!==null&&typeoft=="object"&&!Array.isArray(t)){if(e.has(t))returnpdn(t);if(fdn(t))returnt;e.add(t);letr=t;if(cdn(r))returne.delete(t),ddn(r);letn={};for(let[o,i]ofObject.entries(r))n[o]=Vpe(i,e);returne.delete(t),n}returnArray.isArray(t)?t.map(r=>Vpe(r,e)):t}varRCt,ICt=v(()=>{RCt="__lc_escaped__"});functionACt(t){returnArray.isArray(t)?[...t]:{...t}}functionhdn(t,e){letr=ACt(t);for(let[n,o]ofObject.entries(e)){let[i,...a]=n.split(".").reverse(),s=r;for(letuofa.reverse()){if(s[u]===void0)break;s[u]=ACt(s[u]),s=s[u]}s[i]!==void0&&(s[i]={lc:1,type:"secret",id:[o]})}returnr}functionHpe(t){lete=Object.getPrototypeOf(t);returntypeoft.lc_name=="function"&&(typeofe.lc_name!="function"||t.lc_name()!==e.lc_name())?t.lc_name():t.name}varmdn,Cg,kL=v(()=>{Jo();MCt();ICt();mdn={};$t(mdn,{Serializable:()=>Cg,get_lc_unique_name:()=>Hpe});Cg=classNCt{constructor(e,...r){x(this,"lc_serializable",!1);x(this,"lc_kwargs");this.lc_serializable_keys!==void0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([n])=>this.lc_serializable_keys?.includes(n))):this.lc_kwargs=e??{}}staticlc_name(){returnthis.name}getlc_id(){return[...this.lc_namespace,Hpe(this.constructor)]}getlc_secrets(){}getlc_attributes(){}getlc_aliases(){}getlc_serializable_keys(){}toJSON(){if(!this.lc_serializable)returnthis.toJSONNotImplemented();if(this.lc_kwargsinstanceofNCt||typeofthis.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))returnthis.toJSONNotImplemented();lete={},r={},n=Object.keys(this.lc_kwargs).reduce((u,l)=>(u[l]=linthis?this[l]:this.lc_kwargs[l],u),{});for(letu=Object.getPrototypeOf(this);u;u=Object.getPrototypeOf(u))Object.assign(e,Reflect.get(u,"lc_aliases",this)),Object.assign(r,Reflect.get(u,"lc_secrets",this)),Object.assign(n,Reflect.get(u,"lc_attributes",this));Object.keys(r).forEach(u=>{letl=this,c=n,[d,...f]
Received:${JSON.stringify(t,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function wS(t){if(typeof t=="string")return new qs(t);if(xg(t))return t;if(Array.isArray(t)){let[e,r]=t;return CBe({type:e,content:r})}else if(eme(t)){let{role:e,...r}=t;return CBe({...r,type:e})}else return CBe(t)}function fl(t,e="Human",r="AI"){let n=[];for(let o of t){let i;if(o.type==="human")i=e;else if(o.type==="ai")i=r;else if(o.type==="system")i="System";else if(o.type==="tool")i="Tool";else if(o.type==="generic")i=o.role;else throw new Error(`Gotunsupportedmessagetype:${o.type}`);let a=o.name?`${o.name},`:"",s=o.text,u=`${i}:${a}${s}`;if(o.type==="ai"){let l=o;l.tool_calls&&l.tool_calls.length>0?u+=JSON.stringify(l.tool_calls):l.additional_kwargs&&"function_call"in l.additional_kwargs&&(u+=JSON.stringify(l.additional_kwargs.function_call))}n.push(u)}return n.join(`
`)}function Ndn(t){if(t.data!==void 0)return t;{let e=t;return{type:e.type,data:{content:e.text,role:e.role,name:void 0,tool_call_id:void 0}}}}function VQ(t){let e=Ndn(t);switch(e.type){case"human":return new qs(e.data);case"ai":return new Pn(e.data);case"system":return new Od(e.data);case"function":if(e.data.name===void 0)throw new Error("Name must be defined for function messages");return new Iz(e.data);case"tool":if(e.data.tool_call_id===void 0)throw new Error("Tool call ID must be defined for tool messages");return new Mh(e.data);case"generic":if(e.data.role===void 0)throw new Error("Role must be defined for chat messages");return new Td(e.data);default:throw new Error(`Gotunexpectedtype:${e.type}`)}}function Rxt(t){return t.map(VQ)}function Ixt(t){return t.map(e=>e.toDict())}function Nz(t){let e=t._getType();if(e==="human")return new rw({...t});if(e==="ai"){let r={...t};return"tool_calls"in r&&(r={...r,tool_call_chunks:r.tool_calls?.map(n=>({...n,type:"tool_call_chunk",index:void 0,args:JSON.stringify(n.args)}))}),new Er({...r})}else{if(e==="system")return new Rb({...t});if(e==="function")return new tw({...t});if(Td.isInstance(t))return new ew({...t});throw new Error("Unknown message type.")}}function ame(t){let e=t.reduce((o,i)=>{let a=o.findIndex(([s])=>"id"in i&&i.id&&"index"in i&&i.index!==void 0?i.id===s.id&&i.index===s.index:"id"in i&&i.id?i.id===s.id:"index"in i&&i.index!==void 0?i.index===s.index:!1);return a!==-1?o[a].push(i):o.push([i]),o},[]),r=[],n=[];for(let o of e){let i=null,a=o[0]?.name??"",s=o.map(c=>c.args||"").join("").trim(),u=s.length?s:"{}",l=o[0]?.id;try{if(i=Mz(u),!l||i===null||typeof i!="object"||Array.isArray(i))throw new Error("Malformed tool call chunk args.");r.push({name:a,args:i,id:l,type:"tool_call"})}catch{n.push({name:a,args:u,id:l,error:"Malformed args.",type:"invalid_tool_call"})}}return{tool_call_chunks:t,tool_calls:r,invalid_tool_calls:n}}var sme,UC=v(()=>{Oy();G6();DQ();Wpe();NQ();UQ();tme();zL();rme();BQ();vS();sme=t=>t()});function TBe(){return xBe===void 0&&(xBe={library:"langchain-js",runtime:lme()}),xBe}function Xr(t){try{return typeof process<"u"?process.env?.[t]:ume()?Deno?.env.get(t):void 0}catch{return}}var Ddn,Axt,Nxt,Dxt,ume,jxt,lme,xBe,au=v(()=>{Jo();Ddn={};$t(Ddn,{getEnv:()=>lme,getEnvironmentVariable:()=>Xr,getRuntimeEnvironment:()=>TBe,isBrowser:()=>Axt,isDeno:()=>ume,isJsDom:()=>Dxt,isNode:()=>jxt,isWebWorker:()=>Nxt});Axt=()=>typeof window<"u"&&typeof window.document<"u",Nxt=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Dxt=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),ume=()=>typeof Deno<"u",jxt=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!ume(),lme=()=>{let t;return Axt()?t="browser":jxt()?t="node":Nxt()?t="webworker":Dxt()?t="jsdom":ume()?t="deno":t="other",t}});var $xt,Lxt=v(()=>{$xt=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});function jdn(t){return typeof t=="string"&&$xt.test(t)}var Z6,Fxt=v(()=>{Lxt();Z6=jdn});function dme(t,e=0){return(Tg[t[e+0]]+Tg[t[e+1]]+Tg[t[e+2]]+Tg[t[e+3]]+"-"+Tg[t[e+4]]+Tg[t[e+5]]+"-"+Tg[t[e+6]]+Tg[t[e+7]]+"-"+Tg[t[e+8]]+Tg[t[e+9]]+"-"+Tg[t[e+10]]+Tg[t[e+11]]+Tg[t[e+12]]+Tg[t[e+13]]+Tg[t[e+14]]+Tg[t[e+15]]).toLowerCase()}var Tg,cme,OBe=v(()=>{Tg=[];for(cme=0;cme<256;++cme)Tg.push((cme+256).toString(16).slice(1))});function HQ(){if(!fme&&(fme=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!fme))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return fme($dn)}var fme,$dn,EBe=v(()=>{$dn=new Uint8Array(16)});var Ldn,PBe,kxt=v(()=>{Ldn=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),PBe={randomUUID:Ldn}});function Fdn(t,e,r){if(PBe.randomUUID&&!e&&!t)return PBe.randomUUID();t=t||{};var n=t.random||(t.rng||HQ)();if(n[6]=n[6]
`),r}async_ensureServerInfo(){returnthis._getServerInfoPromise===void0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void0)try{this._serverInfo=awaitthis._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"}${e.message}`)}returnthis._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void0&&(this._getServerInfoPromise=void0),e))}async_getSettings(){returnthis.settings||(this.settings=this._get("/settings")),awaitthis.settings}asyncflush(){lete=awaitthis._getBatchSizeLimitBytes(),r=awaitthis._getBatchSizeLimit();awaitthis.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r})}_cloneCurrentOTELContext(){lete=Ime(),r=nOt();if(this.langSmithToOTELTranslator!==void0){letn=e.getActiveSpan();if(n)returne.setSpan(r.active(),n)}}asynccreateRun(e,r){if(!this._filterForSampling([e]).length)return;letn={...this.headers,"Content-Type":"application/json"},o=e.project_name;deletee.project_name;leti=awaitthis.prepareRunCreateOrUpdateInputs({session_name:o,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&i.trace_id!==void0&&i.dotted_order!==void0){letu=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:i,otelContext:u,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}leta=gPt(i,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);r?.apiKey!==void0&&(n["x-api-key"]=r.apiKey),r?.workspaceId!==void0&&(n["x-tenant-id"]=r.workspaceId);lets=E_(a,`Creating run with id: ${a.id}`);awaitthis.caller.call(async()=>{letu=awaitthis._fetch(`${r?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});returnawaitAr(u,"create run",!0),u})}asyncbatchIngestRuns({runCreates:e,runUpdates:r},n){if(e===void0&&r===void0)return;leto=awaitPromise.all(e?.map(u=>this.prepareRunCreateOrUpdateInputs(u))??[]),i=awaitPromise.all(r?.map(u=>this.prepareRunCreateOrUpdateInputs(u))??[]);if(o.length>0&&i.length>0){letu=o.reduce((c,d)=>(d.id&&(c[d.id]=d),c),{}),l=[];for(letcofi)c.id!==void0&&u[c.id]?u[c.id]={...u[c.id],...c}:l.push(c);o=Object.values(u),i=l}leta={post:o,patch:i};if(!a.post.length&&!a.patch.length)return;lets={post:[],patch:[]};for(letuof["post","patch"]){letl=u,c=a[l].reverse(),d=c.pop();for(;d!==void0;)s[l].push(d),d=c.pop()}if(s.post.length>0||s.patch.length>0){letu=s.post.map(l=>l.id).concat(s.patch.map(l=>l.id)).join(",");awaitthis._postBatchIngestRuns(E_(s,`Ingesting runs with ids: ${u}`),n)}}async_postBatchIngestRuns(e,r){letn={...this.headers,"Content-Type":"application/json",Accept:"application/json"};r?.apiKey!==void0&&(n["x-api-key"]=r.apiKey),awaitthis.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{leto=awaitthis._fetch(`${r?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});returnawaitAr(o,"batch create run",!0),o})}asyncmultipartIngestRuns({runCreates:e,runUpdates:r},n){if(e===void0&&r===void0)return;leto={},i=[];for(letdofe??[]){letf=awaitthis.prepareRunCreateOrUpdateInputs(d);f.id!==void0&&f.attachments!==void0&&(o[f.id]=f.attachments),deletef.attachments,i.push(f)}leta=[];for(letdofr??[])a.push(awaitthis.prepareRunCreateOrUpdateInputs(d));if(i.find(d=>d.trace_id===void0||d.dotted_order===void0)!==void0)thrownewError('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(a.find(d=>d.trace_id===void0||d.dotted_order===void0)!==void0)thrownewError('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(i.length>0&&a.length>0){letd=i.reduce((p,m)=>(m.id&&(p[m.id]=m),p),{}),f=[];for(letpofa)p.id!==void0&&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;letl=[],c=[];for(let[d,f]of[["post",i],["patch",
`])),await new Blob(n).arrayBuffer()}async _createMultipartStream(e,r){let n=new TextEncoder;return new ReadableStream({async start(i){let a=async s=>{typeof s=="string"?i.enqueue(n.encode(s)):i.enqueue(s)};for(let s of e){await a(`--${r}\r
Context:${r}`)}}async updateRun(e,r,n){Ao(e),r.inputs&&(r.inputs=await this.processInputs(r.inputs)),r.outputs&&(r.outputs=await this.processOutputs(r.outputs));let o={...r,id:e};if(!this._filterForSampling([o],!0).length)return;if(this.autoBatchTracing&&o.trace_id!==void 0&&o.dotted_order!==void 0){let s=this._cloneCurrentOTELContext();if(r.end_time!==void 0&&o.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:o,otelContext:s,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:o,otelContext:s,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}let i={...this.headers,"Content-Type":"application/json"};n?.apiKey!==void 0&&(i["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(i["x-tenant-id"]=n.workspaceId);let a=E_(r,`Serializingpayloadtoupdaterunwithid:${e}`);await this.caller.call(async()=>{let s=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:i,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await Ar(s,"update run",!0),s})}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){Ao(e);let n=await this._get(`/runs/${e}`);return r&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:r,projectOpts:n}){if(r!==void 0){let o;r.session_id?o=r.session_id:n?.projectName?o=(await this.readProject({projectName:n?.projectName})).id:n?.projectId?o=n?.projectId:o=(await this.readProject({projectName:ad("PROJECT")||"default"})).id;let i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${o}/r/${r.id}?poll=true`}else if(e!==void 0){let o=await this.readRun(e);if(!o.app_path)throw new Error(`Run${e}hasnoapp_path`);return`${this.getHostUrl()}${o.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){let r=await ogn(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(let i of r){if(i.parent_run_id===null||i.parent_run_id===void 0)throw new Error(`Childrun${i.id}hasnoparent`);i.dotted_order?.startsWith(e.dotted_order??"")&&i.id!==e.id&&(i.parent_run_id in n||(n[i.parent_run_id]=[]),n[i.parent_run_id].push(i),o[i.id]=i)}e.child_runs=n[e.id]||[];for(let i in n)i!==e.id&&(o[i].child_runs=n[i]);return e}async*listRuns(e){let{projectId:r,projectName:n,parentRunId:o,traceId:i,referenceExampleId:a,startTime:s,executionOrder:u,isRoot:l,runType:c,error:d,id:f,query:p,filter:m,traceFilter:h,treeFilter:y,limit:g,select:b,order:_}=e,w=[];if(r&&(w=Array.isArray(r)?r:[r]),n){let P=Array.isArray(n)?n:[n],R=await Promise.all(P.map(I=>this.readProject({projectName:I}).then(N=>N.id)));w.push(...R)}let T=["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"],O={session:w.length?w:null,run_type:c,reference_example:a,query:p,filter:m,trace_filter:h,tree_filter:y,execution_order:u,parent_run:o,start_time:s?s.toISOString():null,error:d,id:f,limit:g,trace:i,select:b||T,is_root:l,order:_};O.select.includes("child_run_ids")&&$z("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let E=0;for await(let P of this._getCursorPaginatedList("/runs/query",O))if(g){if(E>=g)break;if(P.length+E>g){yield*P.slice(0,g-E);break}E+=P.length,yield*P}else yield*P}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||(await this.readProject({projectName:n})).id,group_by:o,filter:i,start_time:a?a.toISOString():null,end_time:s?s.toISOString():null,limit:Number(u)||100},f=Number(l)||0,p="/runs/group",m=`${this.apiUrl}${p}`;for(;;){let h={...d,offset:f},y
`):"Unspecified error"}`):newError(`Failed to list shared examples: ${i.status}${i.statusText}`);returna.map(s=>({...s,_hostUrl:this.getHostUrl()}))}asynccreateProject({projectName:e,description:r=null,metadata:n=null,upsert:o=!1,projectExtra:i=null,referenceDatasetId:a=null}){lets=o?"?upsert=true":"",u=`${this.apiUrl}/sessions${s}`,l=i||{};n&&(l.metadata=n);letc={name:e,extra:l,description:r};a!==null&&(c.reference_dataset_id=a);letd=JSON.stringify(c);returnawait(awaitthis.caller.call(async()=>{letm=awaitthis._fetch(u,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:d});returnawaitAr(m,"create project"),m})).json()}asyncupdateProject(e,{name:r=null,description:n=null,metadata:o=null,projectExtra:i=null,endTime:a=null}){lets=`${this.apiUrl}/sessions/${e}`,u=i;o&&(u={...u||{},metadata:o});letl=JSON.stringify({name:r,extra:u,description:n,end_time:a?newDate(a).toISOString():null});returnawait(awaitthis.caller.call(async()=>{letf=awaitthis._fetch(s,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});returnawaitAr(f,"update project"),f})).json()}asynchasProject({projectId:e,projectName:r}){letn="/sessions",o=newURLSearchParams;if(e!==void0&&r!==void0)thrownewError("Must provide either projectName or projectId, not both");if(e!==void0)Ao(e),n+=`/${e}`;elseif(r!==void0)o.append("name",r);elsethrownewError("Must provide projectName or projectId");leti=awaitthis.caller.call(async()=>{leta=awaitthis._fetch(`${this.apiUrl}${n}?${o}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});returnawaitAr(a,"has project"),a});try{leta=awaiti.json();returni.ok?Array.isArray(a)?a.length>0:!0:!1}catch{return!1}}asyncreadProject({projectId:e,projectName:r,includeStats:n}){leto="/sessions",i=newURLSearchParams;if(e!==void0&&r!==void0)thrownewError("Must provide either projectName or projectId, not both");if(e!==void0)Ao(e),o+=`/${e}`;elseif(r!==void0)i.append("name",r);elsethrownewError("Must provide projectName or projectId");n!==void0&&i.append("include_stats",n.toString());leta=awaitthis._get(o,i),s;if(Array.isArray(a)){if(a.length===0)thrownewError(`Project[id=${e}, name=${r}] not found`);s=a[0]}elses=a;returns}asyncgetProjectUrl({projectId:e,projectName:r}){if(e===void0&&r===void0)thrownewError("Must provide either projectName or projectId");letn=awaitthis.readProject({projectId:e,projectName:r}),o=awaitthis._getTenantId();return`${this.getHostUrl()}/o/${o}/projects/p/${n.id}`}asyncgetDatasetUrl({datasetId:e,datasetName:r}){if(e===void0&&r===void0)thrownewError("Must provide either datasetName or datasetId");letn=awaitthis.readDataset({datasetId:e,datasetName:r}),o=awaitthis._getTenantId();return`${this.getHostUrl()}/o/${o}/datasets/${n.id}`}async_getTenantId(){if(this._tenantId!==null)returnthis._tenantId;lete=newURLSearchParams({limit:"1"});forawait(letrofthis._getPaginated("/sessions",e))returnthis._tenantId=r[0].tenant_id,r[0].tenant_id;thrownewError("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:r,nameContains:n,referenceDatasetId:o,referenceDatasetName:i,includeStats:a,datasetVersion:s,referenceFree:u,metadata:l}={}){letc=newURLSearchParams;if(e!==void0)for(letdofe)c.append("id",d);if(r!==void0&&c.append("name",r),n!==void0&&c.append("name_contains",n),o!==void0)c.append("reference_dataset",o);elseif(i!==void0){letd=awaitthis.readDataset({datasetName:i});c.append("reference_dataset",d.id)}a!==void0&&c.append("include_stats",a.toString()),s!==void0&&c.append("dataset_version",s),u!==void0&&c.append("reference_free",u.toString()),l!==void0&&c.append("metadata",JSON.stringify(l));forawait(letdofthis._getPaginated("/sessions",c))yield*d}asyncdeleteProject({projectId:e,projectName:r}){letn;if(e===void0&&r===void0)thrownewError("Must provide projectNa
`).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("MustprovideeitherdatasetNameordatasetId");let i=r??(await this.readDataset({datasetName:n})).id;Ao(i);let a=JSON.stringify(o);return await(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await Ar(u,"updatedataset"),u})).json()}async updateDatasetTag(e){let{datasetId:r,datasetName:n,asOf:o,tag:i}=e;if(!r&&!n)throw new Error("MustprovideeitherdatasetNameordatasetId");let a=r??(await this.readDataset({datasetName:n})).id;Ao(a);let s=JSON.stringify({as_of:typeof o=="string"?o:o.toISOString(),tag:i});await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${a}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await Ar(u,"updatedatasettags",!0),u})}async deleteDataset({datasetId:e,datasetName:r}){let n="/datasets",o=e;if(e!==void 0&&r!==void 0)throw new Error("MustprovideeitherdatasetNameordatasetId,notboth");if(r!==void 0&&(o=(await this.readDataset({datasetName:r})).id),o!==void 0)Ao(o),n+=`/${o}`;else throw new Error("MustprovidedatasetNameordatasetId");await this.caller.call(async()=>{let i=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Ar(i,`delete ${n}`,!0),i})}async indexDataset({datasetId:e,datasetName:r,tag:n}){let o=e;if(!o&&!r)throw new Error("MustprovideeitherdatasetNameordatasetId");if(o&&r)throw new Error("MustprovideeitherdatasetNameordatasetId,notboth");o||(o=(await this.readDataset({datasetName:r})).id),Ao(o);let a=JSON.stringify({tag:n});await(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${o}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await Ar(u,"indexdataset"),u})).json()}async similarExamples(e,r,n,{filter:o}={}){let i={limit:n,inputs:e};o!==void 0&&(i.filter=o),Ao(r);let a=JSON.stringify(i);return(await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${r}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:a});return await Ar(l,"fetchsimilarexamples"),l})).json()).examples}async createExample(e,r,n){if(_Pt(e)&&(r!==void 0||n!==void 0))throw new Error("CannotprovideoutputsoroptionswhenusingExampleCreateobject");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("MustprovideeitherdatasetNameordatasetId");if(o!==void 0&&i!==void 0)throw new Error("MustprovideeitherdatasetNameordatasetId,notboth");o===void 0&&(o=(await this.readDataset({datasetName:i})).id);let a=(r?n?.createdAt:e.created_at)||new Date,s;_Pt(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]??jz())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let b=e,_=b[0].dataset_id,w=b[0].dat
https://smith.langchain.com/prompts`);let[o,i,a]=VN(e);if(!await this._currentTenantIsOwner(o))throw await this._ownerConflictError("createaprompt",o);let s={repo_handle:i,...r?.description&&{description:r.description},...r?.readme&&{readme:r.readme},...r?.tags&&{tags:r.tags},is_public:!!r?.isPublic},u=JSON.stringify(s),l=await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await Ar(d,"createprompt"),d}),{repo:c}=await l.json();return c}async createCommit(e,r,n){if(!await this.promptExists(e))throw new Error("Promptdoesnotexist,youmustcreateitfirst.");let[o,i,a]=VN(e),s=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${o}/${i}`):n?.parentCommitHash,u={manifest:JSON.parse(JSON.stringify(r)),parent_commit:s},l=JSON.stringify(u),d=await(await this.caller.call(async()=>{let f=await this._fetch(`${this.apiUrl}/commits/${o}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await Ar(f,"createcommit"),f})).json();return this._getPromptUrl(`${o}/${i}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(e,r=[]){return this._updateExamplesMultipart(e,r)}async _updateExamplesMultipart(e,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("YourLangSmithdeploymentdoesnotallowusingthemultipartexamplesendpoint,pleaseupgradeyourdeploymenttothelatestversion.");let n=new FormData;for(let a of r){let s=a.id,u={...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split}},l=E_(u,`Serializing body for example with id: ${s}`),c=new Blob([l],{type:"application/json"});if(n.append(s,c),a.inputs){let d=E_(a.inputs,`Serializing inputs for example with id: ${s}`),f=new Blob([d],{type:"application/json"});n.append(`${s}.inputs`,f)}if(a.outputs){let d=E_(a.outputs,`Serializing outputs whle updating example with id: ${s}`),f=new Blob([d],{type:"application/json"});n.append(`${s}.outputs`,f)}if(a.attachments)for(let[d,f]of Object.entries(a.attachments)){let p,m;Array.isArray(f)?[p,m]=f:(p=f.mimeType,m=f.data);let h=new Blob([m],{type:`${p}; length=${m.byteLength}`});n.append(`${s}.attachment.${d}`,h)}if(a.attachments_operations){let d=E_(a.attachments_operations,`Serializing attachments while updating example with id: ${s}`),f=new Blob([d],{type:"application/json"});n.append(`${s}.attachments_operations`,f)}}let o=e??r[0]?.dataset_id;return(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${o}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await Ar(a,"updateexamples"),a})).json()}async uploadExamplesMultipart(e,r=[]){return this._uploadExamplesMultipart(e,r)}async _uploadExamplesMultipart(e,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("YourLangSmithdeploymentdoesnotallowusingthemultipartexamplesendpoint,pleaseupgradeyourdeploymenttothelatestversion.");let n=new FormData;for(let i of r){let a=(i.id??jz()).toString(),s={created_at:i.created_at,...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split},...i.source_run_id&&{source_run_id:i.source_run_id},...i.use_source_run_io&&{use_source_run_io:i.use_source_run_io},...i.use_source_run_attachments&&{use_source_run_attachments:i.use_source_run_attachments}},u=E_(s,`Serializing body for uploaded example with id: ${a}`),l=new Blob([u],{type:"application/json"});if(n.append(a,l),i.inputs){let c=E_(i.inputs,`Serializing inputs for uploaded example with id: ${a}`),d=new Blob([c],{type:"application/json"});n.append(`${a}.inputs`,d)}if(i.outputs){let c=E_(i.outputs,`Serializing outputs for uploaded example with id: ${a}`),d=new Blob([c],{type:"application/json"});n.append(`${a}.outputs`,d)}if(i.attachme
Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function she(t){return typeof t=="function"&&"langsmith:traceable"in t}var r4e,t4e,Sgn,n4e,Cgn,NMi,LPt=v(()=>{r4e=class{getStore(){}run(e,r){return r()}},t4e=Symbol.for("ls:tracing_async_local_storage"),Sgn=new r4e,n4e=class{getInstance(){return globalThis[t4e]??Sgn}initializeGlobalInstance(e){globalThis[t4e]===void 0&&(globalThis[t4e]=e)}},Cgn=new n4e;NMi=Symbol.for("langsmith:traceable:root")});var o4e=v(()=>{LPt()});function Tgn(t){let e;for(let r of t)for(let n of r)Pn.isInstance(n.message)&&n.message.usage_metadata!==void 0&&(e=X6(e,n.message.usage_metadata));return e}var xgn,lee,kPt=v(()=>{Jo();ime();vS();Uz();e4e();o4e();nhe();ihe();xgn={};$t(xgn,{LangChainTracer:()=>lee});lee=class FPt extends HC{constructor(r={}){super(r);x(this,"name","langchain_tracer");x(this,"projectName");x(this,"exampleId");x(this,"client");x(this,"replicas");x(this,"usesRunTreeMap",!0);let{exampleId:n,projectName:o,client:i,replicas:a}=r;this.projectName=o??ZQ(),this.replicas=a,this.exampleId=n,this.client=i??ahe();let s=FPt.getTraceableRunTree();s&&this.updateFromRunTree(s)}async persistRun(r){}async onRunCreate(r){r.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(r.id)?.postRun()}async onRunUpdate(r){let n=this.getRunTreeWithTracingConfig(r.id);r.extra?.lc_defers_inputs?await n?.postRun():await n?.patchRun()}onLLMEnd(r){let n=r.outputs;if(n?.generations){let o=Tgn(n.generations);if(o!==void 0){r.extra=r.extra??{};let i=r.extra.metadata??{};i.usage_metadata=o,r.extra.metadata=i}}}getRun(r){return this.runTreeMap.get(r)}updateFromRunTree(r){this.runTreeMap.set(r.id,r);let n=r,o=new Set;for(;n.parent_run&&!(o.has(n.id)||(o.add(n.id),!n.parent_run));)n=n.parent_run;o.clear();let i=[n];for(;i.length>0;){let a=i.shift();!a||o.has(a.id)||(o.add(a.id),this.runTreeMap.set(a.id,a),a.child_runs&&i.push(...a.child_runs))}this.client=r.client??this.client,this.replicas=r.replicas??this.replicas,this.projectName=r.project_name??this.projectName,this.exampleId=r.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(r){let n=this.runTreeMap.get(r);if(n)return new VC({...n,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return $Pt(!0)}catch{return}}}});var UPt=S((JMi,lhe)=>{"usestrict";var Ogn=pze(),uhe=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},qPt=(t,e,r)=>new Promise((n,o)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected`milliseconds`tobeapositivenumber");if(e===1/0){n(t);return}let i=setTimeout(()=>{if(typeof r=="function"){try{n(r())}catch(u){o(u)}return}let a=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,s=r instanceof Error?r:new uhe(a);typeof t.cancel=="function"&&t.cancel(),o(s)},e);Ogn(t.then(n,o),()=>{clearTimeout(i)})});lhe.exports=qPt;lhe.exports.default=qPt;lhe.exports.TimeoutError=uhe});var BPt=S(i4e=>{"usestrict";Object.defineProperty(i4e,"__esModule",{value:!0});function Egn(t,e,r){let n=0,o=t.length;for(;o>0;){let i=o/2|0,a=n+i;r(t[a],e)<=0?(n=++a,o-=i+1):o=i}return n}i4e.default=Egn});var zPt=S(s4e=>{"usestrict";Object.defineProperty(s4e,"__esModule",{value:!0});var Pgn=BPt(),a4e=class{constructor(){this._queue=[]}enqueue(e,r){r=Object.assign({priority:0},r);let n={priority:r.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=r.priority){this._queue.push(n);return}let o=Pgn.default(this._queue,n,(i,a)=>a.priority-i.priority);this._queue.splice(o,0,n)}dequeue(){let e=this._queue.shift();return e?.run}filter(e){return this._queue.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this._queue.length}};s4e.default=a4e});var c4e=S(l4e=>{"usestrict";Object.defineProperty(l4e,"__esModule",{value:!0});var Mgn=fze(),VPt=UPt(),Rgn=zPt(),che=()=>{},Ign=new VPt.TimeoutError,u4e=class extends Mgn{constructor(e){var r,n,o,i;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._r
`)}var Bgn,_he,vhe=v(()=>{Bgn=Object.prototype.hasOwnProperty;_he=class extends Error{constructor(t,e,r,n,o){super(rMt(t,{name:e,index:r,operation:n,tree:o})),this.name=e,this.index=r,this.operation=n,this.tree=o,Object.setPrototypeOf(this,new.target.prototype),this.message=rMt(t,{name:e,index:r,operation:n,tree:o})}}});function y4e(t){return Object.getOwnPropertyNames(Object.prototype).includes(t)}function whe(t,e){if(e=="")return t;var r={op:"_get",path:e};return Wz(t,r),r.value}function Wz(t,e,r=!1,n=!0,o=!0,i=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):She(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=whe(t,e.from),e.op==="move"&&(a.removed=t),a;if(e.op==="test"){if(a.test=fee(t,e.value),a.test===!1)throw new jc("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 jc("Operation`op`propertyisnotoneofoperationsdefinedinRFC-6902","OPERATION_OP_INVALID",i,e,t);return a}}else{n||(t=Fb(t));let s=(e.path||"").split("/"),u=t,l=1,c=s.length,d,f,p;for(typeof r=="function"?p=r:p=She;;){if(f=s[l],f&&f.indexOf("~")!=-1&&(f=bhe(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&&!yhe(f))throw new jc("Expectedanunsignedbase-10integervalue,makingthenewreferencedvaluethearrayelementwiththezero-basedindex","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,t);yhe(f)&&(f=~~f)}if(l>=c){if(r&&e.op==="add"&&f>u.length)throw new jc("ThespecifiedindexMUSTNOTbegreaterthanthenumberofelementsinthearray","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);let m=Vgn[e.op].call(e,u,f,t);if(m.test===!1)throw new jc("Testoperationfailed","TEST_OPERATION_FAILED",i,e,t);return m}}else if(l>=c){let m=aJ[e.op].call(e,u,f,t);if(m.test===!1)throw new jc("Testoperationfailed","TEST_OPERATION_FAILED",i,e,t);return m}if(u=u[f],r&&l<c&&(!u||typeof u!="object"))throw new jc("Cannotperformoperationatthedesiredpath","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function GL(t,e,r,n=!0,o=!0){if(r&&!Array.isArray(e))throw new jc("Patchsequencemustbeanarray","SEQUENCE_NOT_AN_ARRAY");n||(t=Fb(t));let i=new Array(e.length);for(let a=0,s=e.length;a<s;a++)i[a]=Wz(t,e[a],r,!0,o,a),t=i[a].newDocument;return i.newDocument=t,i}function Hgn(t,e,r){let n=Wz(t,e);if(n.test===!1)throw new jc("Testoperationfailed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function She(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new jc("Operationisnotanobject","OPERATION_NOT_AN_OBJECT",e,t,r);if(aJ[t.op]){if(typeof t.path!="string")throw new jc("Operation`path`propertyisnotastring","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new jc('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 jc("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)throw new jc("Operation`value`propertyisnotpresent(applicablein`add`,`replace`and`test`operations)","OPERATION_VALUE_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&mhe(t.value))throw new jc("Operation`value`propertyisnotpresent(applicablein`add`,`replace`and`test`operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,r);if(r){if(t.op=="add"){var o=t.path.
`)}var _Mt,Tee,dJ,k4e=v(()=>{uJ();zn();_Mt=(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(){return JSON.stringify(e,P4e,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Tee=xe("$ZodError",_Mt),dJ=xe("$ZodError",_Mt,{Parent:Error})});var Rhe,aO,Ihe,Xz,Ahe,q4e,Nhe,U4e,Dhe=v(()=>{uJ();k4e();zn();Rhe=t=>(e,r,n,o)=>{let i=n?Object.assign(n,{async:!1}):{async:!1},a=e._zod.run({value:r,issues:[]},i);if(a instanceof Promise)throw new iO;if(a.issues.length){let s=new(o?.Err??t)(a.issues.map(u=>ow(u,i,Pd())));throw Mhe(s,o?.callee),s}return a.value},aO=Rhe(dJ),Ihe=t=>async(e,r,n,o)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},a=e._zod.run({value:r,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){let s=new(o?.Err??t)(a.issues.map(u=>ow(u,i,Pd())));throw Mhe(s,o?.callee),s}return a.value},Xz=Ihe(dJ),Ahe=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new iO;return i.issues.length?{success:!1,error:new(t??Tee)(i.issues.map(a=>ow(a,o,Pd())))}:{success:!0,data:i.value}},q4e=Ahe(dJ),Nhe=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new t(i.issues.map(a=>ow(a,o,Pd())))}:{success:!0,data:i.value}},U4e=Nhe(dJ)});var Yz={};En(Yz,{_emoji:()=>wMt,base64:()=>r2e,base64url:()=>jhe,bigint:()=>l2e,boolean:()=>f2e,browserEmail:()=>Iyn,cidrv4:()=>e2e,cidrv6:()=>t2e,cuid:()=>B4e,cuid2:()=>z4e,date:()=>i2e,datetime:()=>s2e,domain:()=>Ayn,duration:()=>K4e,e164:()=>o2e,email:()=>X4e,emoji:()=>Z4e,extendedDuration:()=>xyn,guid:()=>G4e,hostname:()=>n2e,html5Email:()=>Pyn,integer:()=>c2e,ipv4:()=>Y4e,ipv6:()=>Q4e,ksuid:()=>W4e,lowercase:()=>h2e,nanoid:()=>J4e,null:()=>p2e,number:()=>d2e,rfc5322Email:()=>Myn,string:()=>u2e,time:()=>a2e,ulid:()=>V4e,undefined:()=>m2e,unicodeEmail:()=>Ryn,uppercase:()=>g2e,uuid:()=>Zz,uuid4:()=>Tyn,uuid6:()=>Oyn,uuid7:()=>Eyn,xid:()=>H4e});function Z4e(){return new RegExp(wMt,"u")}function CMt(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function a2e(t){return new RegExp(`^${CMt(t)}$`)}function s2e(t){let e=CMt({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${SMt}T(?:${n})$`)}var B4e,z4e,V4e,H4e,W4e,J4e,K4e,xyn,G4e,Zz,Tyn,Oyn,Eyn,X4e,Pyn,Myn,Ryn,Iyn,wMt,Y4e,Q4e,e2e,t2e,r2e,jhe,n2e,Ayn,o2e,SMt,i2e,u2e,l2e,c2e,d2e,f2e,p2e,m2e,h2e,g2e,$he=v(()=>{B4e=/^[cC][^\s-]{8,}$/,z4e=/^[0-9a-z]+$/,V4e=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,H4e=/^[0-9a-vA-V]{20}$/,W4e=/^[A-Za-z0-9]{27}$/,J4e=/^[a-zA-Z0-9_-]{21}$/,K4e=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,xyn=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,G4e=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Zz=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,Tyn=Zz(4),Oyn=Zz(6),Eyn=Zz(7),X4e=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Pyn=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Myn=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0
`).filter(a=>a),o=Math.min(...n.map(a=>a.length-a.trimStart().length)),i=n.map(a=>a.slice(o)).map(a=>"".repeat(this.indent*2)+a);for(let a of i)this.content.push(a)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new e(...r,o.join(`
})));`),f.write(`newResult[${Kz(b)}] = ${_}.value`)}f.write("payload.value=newResult;"),f.write("returnpayload;");let g=f.compile();return(b,_)=>g(d,b,_)},o,i=lJ,a=!yee.jitless,u=a&&I4e.value,l=e.catchall,c;t._zod.parse=(d,f)=>{c??(c=r.value);let p=d.value;if(!i(p))return d.issues.push({expected:"object",code:"invalid_type",input:p,inst:t}),d;let m=[];if(a&&u&&f?.async===!1&&f.jitless!==!0)o||(o=n(e.shape)),d=o(d,f);else{d.value={};let _=c.shape;for(let w of c.keys){let T=_[w],O=T._zod.run({value:p[w],issues:[]},f),E=T._zod.optin==="optional"&&T._zod.optout==="optional";O instanceof Promise?m.push(O.then(P=>E?PMt(P,d,w,p):qhe(P,d,w))):E?PMt(O,d,w,p):qhe(O,d,w)}}if(!l)return m.length?Promise.all(m).then(()=>d):d;let h=[],y=c.keySet,g=l._zod,b=g.def.type;for(let _ of Object.keys(p)){if(y.has(_))continue;if(b==="never"){h.push(_);continue}let w=g.run({value:p[_],issues:[]},f);w instanceof Promise?m.push(w.then(T=>qhe(T,d,_))):qhe(w,d,_)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:p,inst:t}),m.length?Promise.all(m).then(()=>d):d}});Vhe=xe("$ZodUnion",(t,e)=>{uo.init(t,e),Us(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Us(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Us(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Us(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>wee(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,i=[];for(let a of e.options){let s=a._zod.run({value:r.value,issues:[]},n);if(s instanceof Promise)i.push(s),o=!0;else{if(s.issues.length===0)return s;i.push(s)}}return o?Promise.all(i).then(a=>MMt(a,r,t,n)):MMt(i,r,t,n)}}),_Ve=xe("$ZodDiscriminatedUnion",(t,e)=>{Vhe.init(t,e);let r=t._zod.parse;Us(t._zod,"propValues",()=>{let o={};for(let i of e.options){let a=i._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let[s,u]of Object.entries(a)){o[s]||(o[s]=new Set);for(let l of u)o[s].add(l)}}return o});let n=vee(()=>{let o=e.options,i=new Map;for(let a of o){let s=a._zod.propValues[e.discriminator];if(!s||s.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(a)}"`);for(let u of s){if(i.has(u))throw new Error(`Duplicate discriminator value "${String(u)}"`);i.set(u,a)}}return i});t._zod.parse=(o,i)=>{let a=o.value;if(!lJ(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:t}),o;let s=n.value.get(a?.[e.discriminator]);return s?s._zod.run(o,i):e.unionFallback?r(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"Nomatchingdiscriminator",input:a,path:[e.discriminator],inst:t}),o)}}),vVe=xe("$ZodIntersection",(t,e)=>{uo.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,i=e.left._zod.run({value:o,issues:[]},n),a=e.right._zod.run({value:o,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([u,l])=>RMt(r,u,l)):RMt(r,i,a)}});e4=xe("$ZodTuple",(t,e)=>{uo.init(t,e);let r=e.items,n=r.length-[...r].reverse().findIndex(o=>o._zod.optin!=="optional");t._zod.parse=(o,i)=>{let a=o.value;if(!Array.isArray(a))return o.issues.push({input:a,inst:t,expected:"tuple",code:"invalid_type"}),o;o.value=[];let s=[];if(!e.rest){let l=a.length>r.length,c=a.length<n-1;if(l||c)return o.issues.push({input:a,inst:t,origin:"array",...l?{code:"too_big",maximum:r.length}:{code:"too_small",minimum:r.length}}),o}let u=-1;for(let l of r){if(u++,u>=a.length&&u>=n)continue;let c=l._zod.run({value:a[u],issues:[]},i);c instanceof Promise?s.push(c.then(d=>Uhe(d,o,u))):Uhe(c,o,u)}if(e.rest){let l=a.slice(r.length);for(let c of l){u++;let d=e.rest._zod.run({value:c,issues:[]},i);d instanceof Promise?s.push(d.then(f=>Uhe(f,o,u))):Uhe(d,o,u)}}return s.length?Promise.all(s).then(()=>o):o}});wVe=xe("$ZodRecord",(t,e)=>{uo.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!cJ(o))return r.issues.p
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let c of this.seen.entries()){let d=c[1];if(e===c[0]){a(c);continue}if(n.external){let p=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}}let s=(c,d)=>{let f=this.seen.get(c),p=f.def??f.schema,m={...p};if(f.ref===null)return;let h=f.ref;if(f.ref=null,h){s(h,d);let y=this.seen.get(h).schema;y.$ref&&d.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(y)):(Object.assign(p,y),Object.assign(p,m))}f.isParent||this.override({zodSchema:c,jsonSchema:p,path:f.path??[]})};for(let c of[...this.seen.entries()].reverse())s(c[0],{target:this.target});let u={};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){let c=n.external.registry.get(e)?.id;if(!c)throw new Error("Schema is missing an `id` property");u.$id=n.external.uri(c)}Object.assign(u,o.def);let l=n.external?.defs??{};for(let c of this.seen.entries()){let d=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{return JSON.parse(JSON.stringify(u))}catch{throw new Error("Error converting schema to JSON.")}}}});var pIt={};var mIt=v(()=>{});var YN={};En(YN,{$ZodAny:()=>hVe,$ZodArray:()=>Iee,$ZodAsyncError:()=>iO,$ZodBase64:()=>iVe,$ZodBase64URL:()=>aVe,$ZodBigInt:()=>zhe,$ZodBigIntFormat:()=>dVe,$ZodBoolean:()=>Mee,$ZodCIDRv4:()=>rVe,$ZodCIDRv6:()=>nVe,$ZodCUID:()=>H2e,$ZodCUID2:()=>W2e,$ZodCatch:()=>AVe,$ZodCheck:()=>gc,$ZodCheckBigIntFormat:()=>_2e,$ZodCheckEndsWith:()=>I2e,$ZodCheckGreaterThan:()=>Fhe,$ZodCheckIncludes:()=>M2e,$ZodCheckLengthEquals:()=>T2e,$ZodCheckLessThan:()=>Lhe,$ZodCheckLowerCase:()=>E2e,$ZodCheckMaxLength:()=>C2e,$ZodCheckMaxSize:()=>v2e,$ZodCheckMimeType:()=>N2e,$ZodCheckMinLength:()=>x2e,$ZodCheckMinSize:()=>w2e,$ZodCheckMultipleOf:()=>y2e,$ZodCheckNumberFormat:()=>b2e,$ZodCheckOverwrite:()=>D2e,$ZodCheckProperty:()=>A2e,$ZodCheckRegex:()=>O2e,$ZodCheckSizeEquals:()=>S2e,$ZodCheckStartsWith:()=>R2e,$ZodCheckStringFormat:()=>fJ,$ZodCheckUpperCase:()=>P2e,$ZodCustom:()=>FVe,$ZodCustomStringFormat:()=>lVe,$ZodDate:()=>yVe,$ZodDefault:()=>PVe,$ZodDiscriminatedUnion:()=>_Ve,$ZodE164:()=>sVe,$ZodEmail:()=>U2e,$ZodEmoji:()=>z2e,$ZodEnum:()=>xVe,$ZodError:()=>Tee,$ZodFile:()=>OVe,$ZodFunction:()=>mge,$ZodGUID:()=>k2e,$ZodIPv4:()=>eVe,$ZodIPv6:()=>tVe,$ZodISODate:()=>Z2e,$ZodISODateTime:()=>X2e,$ZodISODuration:()=>Q2e,$ZodISOTime:()=>Y2e,$ZodIntersection:()=>vVe,$ZodJWT:()=>uVe,$ZodKSUID:()=>G2e,$ZodLazy:()=>LVe,$ZodLiteral:()=>TVe,$ZodMap:()=>SVe,$ZodNaN:()=>NVe,$ZodNanoID:()=>V2e,$ZodNever:()=>Ree,$ZodNonOptional:()=>RVe,$ZodNull:()=>mVe,$ZodNullable:()=>EVe,$ZodNumber:()=>Bhe,$ZodNumberFormat:()=>cVe,$ZodObject:()=>bVe,$ZodOptional:()=>pJ,$ZodPipe:()=>Nee,$ZodPrefault:()=>MVe,$ZodPromise:()=>$Ve,$ZodReadonly:()=>DVe,$ZodRealError:()=>dJ,$ZodRecord:()=>wVe,$ZodRegistry:()=>mJ,$ZodSet:()=>CVe,$ZodString:()=>Qz,$ZodStringFormat:()=>Ru,$ZodSuccess:()=>IVe,$ZodSymbol:()=>fVe,$ZodTemplateLiteral:()=>jVe,$ZodTransform:()=>Aee,$ZodTuple:()=>e4,$ZodType:()=>uo,$ZodULID:()=>J2e,$ZodURL:()=>B2e,$ZodUUID:()=>q2e,$ZodUndefined:()=>pVe,$ZodUnion:()=>Vhe,$ZodUnknown:()=>ZL,$ZodVoid:()=>gVe,$ZodXID:()=>K2e,$brand:()=>T4e,$constructor:()=>xe,$input:()=>BVe,$output:()=>UVe,Doc:()=>Pee,JSONSchema:()=>pIt,JSONSchemaGenerator:()=>Zee,NEVER:()=>x4e,TimePrecision:()=>WVe,_any:()=>pHe,_array:()=>Xee,_base64:()=>cge,_base64url:()=>dge,_bigint:()=>aHe,_boolean:()=>oHe,_catch:()=>$bn,_cidrv4:()=>uge,_cidrv6:()=>lge,_coercedBigint:()=>sHe,_coercedBoolean:()=>iHe,_coercedDate:()=>gHe,_coercedNumber:()=>YVe,_coercedString:()=>HVe,_cuid:()=>tge,_cuid2:()=>rge,_custom:()=>THe,_date:()=>hHe,_default:()=>Nbn,_discriminatedUnion:()=>Sbn,_e164:()=>fge,_email:()=>Jhe,_emoji:()=>Qhe,_endsWith:()=>Vee,_enum:()
`}}let c={};for(let m of e){let h=m.source.split(":"),y=m.target.split(":"),g=h.filter((b,_)=>b===y[_]).join(":");c[g]||(c[g]=[]),c[g].push(m)}let d=new Set;function f(m){return[...m].sort((h,y)=>h.split(":").length-y.split(":").length)}function p(m,h){let y=m.length===1&&m[0].source===m[0].target;if(h&&!y){let b=h.split(":").pop();if(d.has(h))throw new Error(`Foundduplicatesubgraph'${b}'at'${h} -- this likely means that you'rereusingasubgraphnodewiththesamename.Pleaseadjustyourgraphtohavesubgraphnodeswithuniquenames.`);d.add(h),l+=`subgraph${b}
`}let g=f(Object.keys(c).filter(b=>b.startsWith(`${h}:`)&&b!==h&&b.split(":").length===h.split(":").length+1));for(let b of g)p(c[b],b);for(let b of m){let{source:_,target:w,data:T,conditional:O}=b,E="";if(T!==void 0){let P=T,R=P.split(" ");R.length>u&&(P=Array.from({length:Math.ceil(R.length/u)},(I,N)=>R.slice(N*u,(N+1)*u).join(" ")).join(" <br> ")),E=O?`-. ${P} .->`:`-- ${P} -->`}else E=O?" -.-> ":" --> ";l+=`${jHe(_)}${E}${jHe(w)};
`)}p(c[""]??[],"");for(let m in c)!m.includes(":")&&m!==""&&p(c[m],m);return a&&(l+=Hbn(i??{})),l}async function OIt(t,e){let r=e?.backgroundColor??"white",n=e?.imageType??"png",o=bMt(t);r!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));let i=`https://mermaid.ink/img/${o}?bgColor=${r}&type=${n}`,a=await fetch(i);if(!a.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${a.status}`,`Status text: ${a.statusText}`].join(`
`));return await a.blob()}var Vbn,EIt=v(()=>{Phe();Vbn=["*","_","`"]});var MIt,PIt,RIt,vge=v(()=>{MIt=Symbol("LetzodToJsonSchemadecideonwhichparsertouse"),PIt={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},RIt=t=>typeof t=="string"?{...PIt,name:t}:{...PIt,...t}});var IIt,$He=v(()=>{vge();IIt=t=>{let e=RIt(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});var wge,Sge=v(()=>{wge=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")}});function Ul(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?wge(e,t.currentPath):e.join("/")}}var RS=v(()=>{Sge()});function LHe(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function Hi(t,e,r,n,o){t[e]=r,LHe(t,e,n,o)}var oF=v(()=>{});var Ai,FHe,cr,sO,Qee=v(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let i={};for(let a of o)i[a]=a;return i},t.getValidEnumValues=o=>{let i=t.objectKeys(o).filter(s=>typeof o[o[s]]!="number"),a={};for(let s of i)a[s]=o[s];return t.objectValues(a)},t.objectValues=o=>t.objectKeys(o).map(function(i){return o[i]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let i=[];for(let a in o)Object.prototype.hasOwnProperty.call(o,a)&&i.push(a);return i},t.find=(o,i)=>{for(let a of o)if(i(a))return a},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,i="|"){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=n,t.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(Ai||(Ai={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(FHe||(FHe={}));cr=Ai.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),sO=t=>{switch(typeof t){case"undefined":return cr.undefined;case"string":return cr.string;case"number":return Number.isNaN(t)?cr.nan:cr.number;case"boolean":return cr.boolean;case"function":return cr.function;case"bigint":return cr.bigint;case"symbol":return cr.symbol;case"object":return Array.isArray(t)?cr.array:t===null?cr.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?cr.promise:typeof Map<"u"&&t instanceof Map?cr.map:typeof Set<"u"&&t instanceof Set?cr.set:typeof Date<"u"&&t instanceof Date?cr.date:cr.object;default:return cr.unknown}}});var it,Wbn,I_,Cge=v(()=>{Qee();it=Ai.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Wbn=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),I_=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issue
]`;continue}o+=n[u],n[u]==="\\"?i=!0:a&&n[u]==="]"?a=!1:!a&&n[u]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Couldnotconvertregexpatternat${e.currentPath.join("/")}toaflag-independentform!Fallingbacktotheflag-ignorantsource`),t.source}return o}var e3e,JC,ovn,Nge=v(()=>{oF();JC={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(e3e===void 0&&(e3e=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),e3e),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};ovn=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Dge(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===Ae.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:kn(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Ul(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:kn(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===Ae.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Age(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===Ae.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===Ae.ZodBranded&&t.keyType._def.type._def.typeName===Ae.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Rge(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var jge=v(()=>{RS();Ige();Nge();Md();cO()});function rAt(t,e){if(e.mapStrategy==="record")return Dge(t,e);let r=kn(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ul(e),n=kn(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ul(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var r3e=v(()=>{RS();jge();Md()});function nAt(t){let e=t.values,n=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":
- `)}`,newError(Ue)}letht=`${s}/$ref`,$e=Ku(t,ze,r,n,o,i,a,ht,u);if($e.valid||je.push({instanceLocation:a,keyword:"$ref",keywordLocation:ht,error:"A subschema had errors."},...$e.errors),r==="4"||r==="7")return{valid:je.length===0,errors:je}}if(Array.isArray(m)){letct=m.length,ze=!1;for(letht=0;ht<ct;ht++)if(c===m[ht]||m[ht]==="integer"&&c==="number"&&t%1===0&&t===t){ze=!0;break}ze||je.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m.join('", "')}".`})}elsem==="integer"?(c!=="number"||t%1||t!==t)&&je.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m}".`}):m!==void0&&c!==m&&je.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m}".`});if(h!==void0&&(c==="object"||c==="array"?dO(t,h)||je.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):t!==h&&je.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),y!==void0&&(c==="object"||c==="array"?y.some(ct=>dO(t,ct))||je.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`}):y.some(ct=>t===ct)||je.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`})),b!==void0){letct=`${s}/not`;Ku(t,b,r,n,o,i,a,ct).valid&&je.push({instanceLocation:a,keyword:"not",keywordLocation:ct,error:'Instance matched "not" schema.'})}letGr=[];if(_!==void0){letct=`${s}/anyOf`,ze=je.length,ht=!1;for(let$e=0;$e<_.length;$e++){letUe=_[$e],Ve=Object.create(u),Kt=Ku(t,Ue,r,n,o,p===!0?i:null,a,`${ct}/${$e}`,Ve);je.push(...Kt.errors),ht=ht||Kt.valid,Kt.valid&&Gr.push(Ve)}ht?je.length=ze:je.splice(ze,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:ct,error:"Instance does not match any subschemas."})}if(w!==void0){letct=`${s}/allOf`,ze=je.length,ht=!0;for(let$e=0;$e<w.length;$e++){letUe=w[$e],Ve=Object.create(u),Kt=Ku(t,Ue,r,n,o,p===!0?i:null,a,`${ct}/${$e}`,Ve);je.push(...Kt.errors),ht=ht&&Kt.valid,Kt.valid&&Gr.push(Ve)}ht?je.length=ze:je.splice(ze,0,{instanceLocation:a,keyword:"allOf",keywordLocation:ct,error:"Instance does not match every subschema."})}if(T!==void0){letct=`${s}/oneOf`,ze=je.length,ht=T.filter(($e,Ue)=>{letVe=Object.create(u),Kt=Ku(t,$e,r,n,o,p===!0?i:null,a,`${ct}/${Ue}`,Ve);returnje.push(...Kt.errors),Kt.valid&&Gr.push(Ve),Kt.valid}).length;ht===1?je.length=ze:je.splice(ze,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:ct,error:`Instance does not match exactly one subschema (${ht} matches).`})}if((c==="object"||c==="array")&&Object.assign(u,...Gr),O!==void0){letct=`${s}/if`;if(Ku(t,O,r,n,o,i,a,ct,u).valid){if(E!==void0){letht=Ku(t,E,r,n,o,i,a,`${s}/then`,u);ht.valid||je.push({instanceLocation:a,keyword:"if",keywordLocation:ct,error:'Instance does not match "then" schema.'},...ht.errors)}}elseif(P!==void0){letht=Ku(t,P,r,n,o,i,a,`${s}/else`,u);ht.valid||je.push({instanceLocation:a,keyword:"if",keywordLocation:ct,error:'Instance does not match "else" schema.'},...ht.errors)}}if(c==="object"){if(g!==void0)for(let$eofg)$eint||je.push({instanceLocation:a,keyword:"required",keywordLocation:`${s}/required`,error:`Instance does not have required property "${$e}".`});letct=Object.keys(t);if(k!==void0&&ct.length<k&&je.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${k} properties.`}),X!==void0&&ct.length>X&&je.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${X} properties.`}),B!==void0){let$e=`${s}/propertyNames`;for(letUeint){letVe=`${a}/${iw(Ue)}`,Kt=Ku(Ue,B,r,n,o,i,Ve,$e);Kt.valid||je.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:$e,error:`Property name "${Ue}" does not
`)),n.close()}});return$b.fromReadableStream(r)}varNAt=v(()=>{nO()});functionx3e(t){returntypeoft=="object"&&t!==null&&typeoft[Symbol.iterator]=="function"&&typeoft.next=="function"}functionBge(t){returntypeoft=="object"&&t!==null&&typeoft[Symbol.asyncIterator]=="function"}function*T3e(t,e){for(;;){let{value:r,done:n}=Rh.runWithConfig(jb(t),e.next.bind(e),!0);if(n)break;yieldr}}asyncfunction*zge(t,e){letr=e[Symbol.asyncIterator]();for(;;){let{value:n,done:o}=awaitRh.runWithConfig(jb(t),r.next.bind(e),!0);if(o)break;yieldn}}varDAt,jAt=v(()=>{zz();Vz();rO();DAt=t=>t!=null&&typeoft=="object"&&"next"int&&typeoft.next=="function"});functionRd(t,e){returnt&&!Array.isArray(t)&&!(tinstanceofDate)&&typeoft=="object"?t:{[e]:t}}functionKvn(t){if(she(t))thrownewError("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}functionaw(t){if(typeoft=="function")returnnewD_({func:t});if(Go.isRunnable(t))returnt;if(!Array.isArray(t)&&typeoft=="object"){lete={};for(let[r,n]ofObject.entries(t))e[r]=aw(n);returnnewlF({steps:e})}elsethrownewError(`Expected a Runnable, function or object.
Instead got an unsupported type.`)}functionGvn(t,e){letr=e.name??t.getName(),n=e.description??nF(e.schema);return_J(e.schema)?newVge({name:r,description:n,schema:wt.object({input:wt.string()}).transform(o=>o.input),bound:t}):newVge({name:r,description:n,schema:e.schema,bound:t})}varGo,DS,LAt,Hge,Bl,lF,Jvn,D_,BAt,O3e,ate,E3e,Vge,Pg=v(()=>{kL();Wpe();zz();Vz();rO();iJ();nO();sMt();fMt();S4e();Jz();gMt();Phe();QN();IAt();NAt();jAt();cO();JQ();o4e();Go=classextendsCg{constructor(){super(...arguments);x(this,"lc_runnable",!0);x(this,"name")}getName(e){letr=this.name??this.constructor.lc_name()??this.constructor.name;returne?`${r}${e}`:r}withRetry(e){returnnewHge({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){returnnewDS({bound:this,config:e,kwargs:{}})}withFallbacks(e){letr=Array.isArray(e)?e:e.fallbacks;returnnewO3e({runnable:this,fallbacks:r})}_getOptionsList(e,r=0){if(Array.isArray(e)&&e.length!==r)thrownewError(`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))returne.map(ai);if(r>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");letn=Object.fromEntries(Object.entries(e).filter(([o])=>o!=="runId"));returnArray.from({length:r},(o,i)=>ai(i===0?e:n))}returnArray.from({length:r},()=>ai(e))}asyncbatch(e,r,n){leto=this._getOptionsList(r??{},e.length),i=o[0]?.maxConcurrency??n?.maxConcurrency,a=newES({maxConcurrency:i,onFailedAttempt:u=>{throwu}}),s=e.map((u,l)=>a.call(async()=>{try{returnawaitthis.invoke(u,o[l])}catch(c){if(n?.returnExceptions)returnc;throwc}}));returnPromise.all(s)}async*_streamIterator(e,r){yieldthis.invoke(e,r)}asyncstream(e,r){letn=ai(r),o=newKL({generator:this._streamIterator(e,n),config:n});returnawaito.setup,$b.fromAsyncGenerator(o)}_separateRunnableConfigFromCallOptions(e){letr;e===void0?r=ai(e):r=ai({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});letn={...e};returndeleten.callbacks,deleten.tags,deleten.metadata,deleten.runName,deleten.configurable,deleten.recursionLimit,deleten.maxConcurrency,deleten.runId,deleten.timeout,deleten.signal,[r,n]}async_callWithConfig(e,r,n){leto=ai(n),a=await(awaitRy(o))?.handleChainStart(this.toJSON(),Rd(r,"input"),o.runId,o?.runType,void0,void0,o?.runName??this.getName());deleteo.runId;lets;try{letu=e.call(this,r,o,a);s=awaitTS(u,n?.signal)}catch(u){throwawaita?.handleChainError(u),u}returnawaita?.handleChainEnd(Rd(s,"output")),s}async_batchWithConfig(e,r,n,o){leti=this._getOptionsList(n??{},r.length),a=awaitPromise.all(i.map(Ry)),s=awaitPromise.all(a.map(async(l,c)=>{letd=awaitl?.handleChainStart(this.toJSON(),Rd(r[c],"input"),i[c].runId,i[c].runType,void0,void0,i[c].runName??this.getName());returndeletei[c].runId,d})),u;try{letl=e.call(this,r,i,s,o);u=awaitTS(l,i?.[0]?.signal)}catch(l){throwawaitPromise.all(s.map(c=>c?.handleChainError(l))),l}returnawaitPromise.all(s.map(l=>l?.handleChainEnd(Rd(u,"output")))),u}_concatOutputChunks(e,r){returnLb(e,r)}async*_transformStreamWithConfig(e,r,n){leto,i=!0,a,s=!0,u=ai(n),l=awaitRy(u),c=this;asyncfunction*d(){forawait(letpofe){if(i)if(o===void0)o=p;elsetry{o=c._concatOutputChunks(o,p)}catch{o=void0,i=!1}yieldp}}letf;try{letp=awaitg4e(r.bind(this),d(),async()=>l?.handleChainStart(this.toJSON(),{input:""},u.runId,u.runType,void0,void0,u.runName??this.getName(),void0,{lc_defers_inputs:!0}),n?.signal,u);deleteu.runId,f=p.setup;letm=f?.handlers.find(cMt),h=p.output;m!==void0&&f!==void0&&(h=m.tapOutputIterable(f.runId,h));lety=f?.handlers.find(w4e);y!==void0&&f!==void0&&(h=y.tapOutputIterable(f.runId,h));forawait(letgofh)if(yieldg,s)if(a===void0)a=g;elsetry{a=this._concatOutputChunks(a,g)}catch{a=void0,s=!1}}catch(p){throwawaitf?.handleChainError(p,void0,void0,
${a.content}`),e.push(Zvn(s))}}return e}function QAt(t,e){if(Array.isArray(t)){let r=t;if(!e)throw new Error("Options parameter is required when providing messages.");return GAt(r,e)}else{let r=t;return D_.from(n=>GAt(n,r)).withConfig({runName:"trim_messages"})}}async function GAt(t,e){let{maxTokens:r,tokenCounter:n,strategy:o="last",allowPartial:i=!1,endOn:a,startOn:s,includeSystem:u=!1,textSplitter:l}=e;if(s&&o==="first")throw new Error("`startOn` should only be specified if `strategy` is 'last'.");if(u&&o==="first")throw new Error("`includeSystem` should only be specified if `strategy` is 'last'.");let c;"getNumTokens"in n?c=async f=>(await Promise.all(f.map(m=>n.getNumTokens(m.content)))).reduce((m,h)=>m+h,0):c=async f=>n(f);let d=M3e;if(l&&("splitText"in l?d=l.splitText:d=async f=>l(f)),o==="first")return eNt(t,{maxTokens:r,tokenCounter:c,textSplitter:d,partialStrategy:i?"first":void 0,endOn:a});if(o==="last")return Xvn(t,{maxTokens:r,tokenCounter:c,textSplitter:d,allowPartial:i,includeSystem:u,startOn:s,endOn:a});throw new Error(`Unrecognizedstrategy:'${o}'.Mustbeoneof'first'or'last'.`)}async function eNt(t,e){let{maxTokens:r,tokenCounter:n,textSplitter:o,partialStrategy:i,endOn:a}=e,s=[...t],u=0;for(let l=0;l<s.length;l+=1){let c=l>0?s.slice(0,-l):s;if(await n(c)<=r){u=s.length-l;break}}if(u<s.length&&i){let l=!1;if(Array.isArray(s[u].content)){let c=s[u];if(typeof c.content=="string")throw new Error("Expected content to be an array.");let d=c.content.length,f=i==="last"?[...c.content].reverse():c.content;for(let p=1;p<=d;p+=1){let m=i==="first"?f.slice(0,p):f.slice(-p),h=Object.fromEntries(Object.entries(c).filter(([b])=>b!=="type"&&!b.startsWith("lc_"))),y=P3e(c.getType(),{...h,content:m}),g=[...s.slice(0,u),y];if(await n(g)<=r)s=g,u+=1,l=!0;else break}l&&i==="last"&&(c.content=[...f].reverse())}if(!l){let c=s[u],d;if(Array.isArray(c.content)&&c.content.some(f=>typeof f=="string"||f.type==="text")?d=c.content.find(p=>p.type==="text"&&p.text)?.text:typeof c.content=="string"&&(d=c.content),d){let f=await o(d),p=f.length;i==="last"&&f.reverse();for(let m=0;m<p-1;m+=1)if(f.pop(),c.content=f.join(""),await n([...s.slice(0,u),c])<=r){i==="last"&&(c.content=[...f].reverse().join("")),s=[...s.slice(0,u),c],u+=1;break}}}}if(a){let l=Array.isArray(a)?a:[a];for(;u>0&&!Jge(s[u-1],l);)u-=1}return s.slice(0,u)}async function Xvn(t,e){let{allowPartial:r=!1,includeSystem:n=!1,endOn:o,startOn:i,...a}=e,s=t.map(c=>{let d=Object.fromEntries(Object.entries(c).filter(([f])=>f!=="type"&&!f.startsWith("lc_")));return P3e(c.getType(),d,K6(c))});if(o){let c=Array.isArray(o)?o:[o];for(;s.length>0&&!Jge(s[s.length-1],c);)s=s.slice(0,-1)}let u=n&&s[0]?.getType()==="system",l=u?s.slice(0,1).concat(s.slice(1).reverse()):s.reverse();return l=await eNt(l,{...a,partialStrategy:r?"last":void 0,endOn:i}),u?[l[0],...l.slice(1).reverse()]:l.reverse()}function P3e(t,e,r){let n,o;switch(t){case"human":r?n=new rw(e):o=new qs(e);break;case"ai":if(r){let i={...e};"tool_calls"in i&&(i={...i,tool_call_chunks:i.tool_calls?.map(a=>({...a,type:"tool_call_chunk",index:void 0,args:JSON.stringify(a.args)}))}),n=new Er(i)}else o=new Pn(e);break;case"system":r?n=new Rb(e):o=new Od(e);break;case"developer":r?n=new Rb({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}}):o=new Od({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in e)r?n=new _S(e):o=new Mh(e);else throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");break;case"function":if(r)n=new tw(e);else{if(!e.name)throw new Error("FunctionMessage must have a 'name' field");o=new Iz(e)}break;case"generic":if("role"in e)r?n=new ew(e):o=new Td(e);else throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.");break;default:throw new Error(`Unrecognizedmessagetype${t}`)}if(r&&n)return n;if(o)return o;throw new Error(`Unrecognizedmessagetype${t}`)}function Zvn(t){let e=t.getType(),r,n=Object.fromEntries(Object.entries(t
`),e[e.length-1]])}varJge,XAt,tNt=v(()=>{Oy();G6();UQ();tme();zL();rme();BQ();UC();vS();Pg();Jge=(t,e)=>{letr=[...newSet(e?.map(o=>{if(typeofo=="string")returno;leti=newo({});if(!("getType"ini)||typeofi.getType!="function")thrownewError("Invalid type provided.");returni.getType()}))],n=t.getType();returnr.some(o=>o===n)};XAt={human:{message:qs,messageChunk:rw},ai:{message:Pn,messageChunk:Er},system:{message:Od,messageChunk:Rb},developer:{message:Od,messageChunk:Rb},tool:{message:Mh,messageChunk:_S},function:{message:Iz,messageChunk:tw},generic:{message:Td,messageChunk:ew},remove:{message:Az,messageChunk:Az}}});varrNt,nNt=v(()=>{rNt=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"]});varoNt,iNt=v(()=>{oNt=["image","video","audio","text-plain","file"]});varaNt,sNt=v(()=>{nNt();iNt();aNt=["text","reasoning",...rNt,...oNt]});varYvn,ta=v(()=>{Jo();LQ();bBe();Oy();ime();G6();UQ();tme();zL();rme();BQ();UC();vS();tNt();sNt();Yvn={};$t(Yvn,{AIMessage:()=>Pn,AIMessageChunk:()=>Er,BaseMessage:()=>id,BaseMessageChunk:()=>Mb,ChatMessage:()=>Td,ChatMessageChunk:()=>ew,FunctionMessage:()=>Iz,FunctionMessageChunk:()=>tw,HumanMessage:()=>qs,HumanMessageChunk:()=>rw,KNOWN_BLOCK_TYPES:()=>aNt,RemoveMessage:()=>Az,SystemMessage:()=>Od,SystemMessageChunk:()=>Rb,ToolMessage:()=>Mh,ToolMessageChunk:()=>_S,_isMessageFieldWithRole:()=>eme,_mergeDicts:()=>Fl,_mergeLists:()=>Rz,_mergeObj:()=>Qpe,_mergeStatus:()=>Ype,coerceMessageLikeToMessage:()=>wS,collapseToolCallChunks:()=>ame,convertToChunk:()=>Nz,convertToOpenAIImageBlock:()=>Kpe,convertToProviderContentBlock:()=>GT,defaultTextSplitter:()=>M3e,defaultToolCallParser:()=>kQ,filterMessages:()=>ZAt,getBufferString:()=>fl,iife:()=>sme,isAIMessage:()=>kl,isAIMessageChunk:()=>zQ,isBase64ContentBlock:()=>J6,isBaseMessage:()=>xg,isBaseMessageChunk:()=>K6,isChatMessage:()=>QCt,isChatMessageChunk:()=>ext,isDataContentBlock:()=>Ph,isDirectToolOutput:()=>FQ,isFunctionMessage:()=>txt,isFunctionMessageChunk:()=>rxt,isHumanMessage:()=>nxt,isHumanMessageChunk:()=>oxt,isIDContentBlock:()=>Jpe,isMessage:()=>Zpe,isOpenAIToolCallArray:()=>XCt,isPlainTextContentBlock:()=>LCt,isSystemMessage:()=>ixt,isSystemMessageChunk:()=>axt,isToolMessage:()=>qQ,isToolMessageChunk:()=>vBe,isURLContentBlock:()=>W6,mapChatMessagesToStoredMessages:()=>Ixt,mapStoredMessageToChatMessage:()=>VQ,mapStoredMessagesToChatMessages:()=>Rxt,mergeContent:()=>Ty,mergeMessageRuns:()=>YAt,mergeResponseMetadata:()=>ome,mergeUsageMetadata:()=>X6,parseBase64DataUrl:()=>Cy,parseMimeType:()=>$Q,trimMessages:()=>QAt})});varuNt,lNt=v(()=>{Oy();zL();vS();Pg();ta();Wge();uNt=classextendsDS{constructor(e){letr=D_.from((a,s)=>this._enterHistory(a,s??{})).withConfig({runName:"loadHistory"}),n=e.historyMessagesKey??e.inputMessagesKey;n&&(r=Au.assign({[n]:r}).withConfig({runName:"insertHistory"}));leto=r.pipe(e.runnable.withListeners({onEnd:(a,s)=>this._exitHistory(a,s??{})})).withConfig({runName:"RunnableWithMessageHistory"}),i=e.config??{};super({...e,config:i,bound:o});x(this,"runnable");x(this,"inputMessagesKey");x(this,"outputMessagesKey");x(this,"historyMessagesKey");x(this,"getMessageHistory");this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){letr;if(typeofe=="object"&&!Array.isArray(e)&&!xg(e)){letn;this.inputMessagesKey?n=this.inputMessagesKey:Object.keys(e).length===1?n=Object.keys(e)[0]:n="input",Array.isArray(e[n])&&Array.isArray(e[n][0])?r=e[n][0]:r=e[n]}elser=e;if(typeofr=="string")return[newqs(r)];if(Array.isArray(r))returnr;if(xg(r))return[r];thrownewError(`Expected a string, BaseMessage, or array of BaseMessages.
Got ${JSON.stringify(r,null,2)}`)}_getOutputMessages(e){letr;if(!Array.isArray(e)&&!xg(e)&&typeofe!="string"){letn;this.outputMessagesKey!==void0?n=this.outputMessagesKey:Object.keys(e).length===1?n=Object.keys(e)[0]:n="output",e.generations!==void0?r=e.generations[0][0].message:r=e[n]}elser=e;if(typeofr=="string")return[newPn(r)];if(Array.isArray(r))returnr;if(xg(r))return[r];thrownewError(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(r,null,2)}`)}async_enterHistory(e,r){leto=await(r?.configurable?.messageHistory).getMessages();returnthis.historyMessagesKey===void0?o.concat(this._getInputMessages(e)):o}async_exitHistory(e,r){letn=r.configurable?.messageHistory,o;Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?o=e.inputs[0]:o=e.inputs;leti=this._getInputMessages(o);if(this.historyMessagesKey===void0){letu=awaitn.getMessages();i=i.slice(u.length)}leta=e.outputs;if(!a)thrownewError(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);lets=this._getOutputMessages(a);awaitn.addMessages([...i,...s])}async_mergeConfig(...e){letr=awaitsuper._mergeConfig(...e);if(!r.configurable||!r.configurable.sessionId){leto={[this.inputMessagesKey??"input"]:"foo"},i={configurable:{sessionId:"123"}};thrownewError(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()
eg. chain.invoke(${JSON.stringify(o)}, ${JSON.stringify(i)})`)}let{sessionId:n}=r.configurable;returnr.configurable.messageHistory=awaitthis.getMessageHistory(n),r}}});varQvn,sw=v(()=>{Jo();rO();iJ();Pg();Wge();VAt();WAt();lNt();Qvn={};$t(Qvn,{RouterRunnable:()=>zAt,Runnable:()=>Go,RunnableAssign:()=>ate,RunnableBinding:()=>DS,RunnableBranch:()=>HAt,RunnableEach:()=>LAt,RunnableLambda:()=>D_,RunnableMap:()=>lF,RunnableParallel:()=>BAt,RunnablePassthrough:()=>Au,RunnablePick:()=>E3e,RunnableRetry:()=>Hge,RunnableSequence:()=>Bl,RunnableToolLike:()=>Vge,RunnableWithFallbacks:()=>O3e,RunnableWithMessageHistory:()=>uNt,_coerceToRunnable:()=>aw,ensureConfig:()=>ai,getCallbackManagerForConfig:()=>Ry,mergeConfigs:()=>Hz,patchConfig:()=>Xs,pickRunnableConfigKeys:()=>jb,raceWithSignal:()=>TS})});varv4,o1,Ih,MJ=v(()=>{DQ();Pg();sw();v4=classextendsGo{parseResultWithPrompt(t,e,r){returnthis.parseResult(t,r)}_baseMessageToString(t){returntypeoft.content=="string"?t.content:this._baseMessageContentToString(t.content)}_baseMessageContentToString(t){returnJSON.stringify(t)}asyncinvoke(t,e){returntypeoft=="string"?this._callWithConfig(async(r,n)=>this.parseResult([{text:r}],n?.callbacks),t,{...e,runType:"parser"}):this._callWithConfig(async(r,n)=>this.parseResult([{message:r,text:this._baseMessageToString(r)}],n?.callbacks),t,{...e,runType:"parser"})}},o1=classextendsv4{parseResult(t,e){returnthis.parse(t[0].text,e)}asyncparseWithPrompt(t,e,r){returnthis.parse(t,r)}_type(){thrownewError("_type not implemented")}},Ih=classextendsError{constructor(e,r,n,o=!1){super(e);x(this,"llmOutput");x(this,"observation");x(this,"sendToLLM");if(this.llmOutput=r,this.observation=n,this.sendToLLM=o,o&&(n===void0||r===void0))thrownewError("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");FL(this,"OUTPUT_PARSING_FAILURE")}}});vari1,cF,dF=v(()=>{Oy();UC();Ed();MJ();qge();i1=classextendso1{async*_transform(t){forawait(leteoft)typeofe=="string"?yieldthis.parseResult([{text:e}]):yieldthis.parseResult([{message:e,text:this._baseMessageToString(e)}])}async*transform(t,e){yield*this._transformStreamWithConfig(t,this._transform.bind(this),{...e,runType:"parser"})}},cF=classextendsi1{constructor(e){super(e);x(this,"diff",!1);this.diff=e?.diff??this.diff}async*_transform(e){letr,n;forawait(letoofe){if(typeofo!="string"&&typeofo.content!="string")thrownewError("Cannot handle non-string output.");leti;if(K6(o)){if(typeofo.content!="string")thrownewError("Cannot handle non-string message output.");i=newsi({message:o,text:o.content})}elseif(xg(o)){if(typeofo.content!="string")thrownewError("Cannot handle non-string message output.");i=newsi({message:Nz(o),text:o.content})}elsei=newOS({text:o});n===void0?n=i:n=n.concat(i);leta=awaitthis.parsePartialResult([n]);a!=null&&!dO(a,r)&&(this.diff?yieldthis._diff(r,a):yielda,r=a)}}getFormatInstructions(){return""}}});varcNt,dNt=v(()=>{dF();cNt=classextendsi1{constructor(){super(...arguments);x(this,"lc_namespace",["langchain_core","output_parsers","bytes"]);x(this,"lc_serializable",!0);x(this,"textEncoder",newTextEncoder)}staticlc_name(){return"BytesOutputParser"}parse(e){returnPromise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return""}}});varRJ,fNt,pNt,mNt,hNt,gNt=v(()=>{MJ();dF();RJ=classextendsi1{constructor(){super(...arguments);x(this,"re")}async*_transform(e){letr="";forawait(letnofe)if(typeofn=="string"?r+=n:r+=n.content,this.re){leto=[...r.matchAll(this.re)];if(o.length>1){leti=0;for(letaofo.slice(0,-1))yield[a[1]],i+=(a.index??0)+a[0].length;r=r.slice(i)}}else{leto=awaitthis.parse(r);if(o.length>1){for(letiofo.slice(0,-1))yield[i];r=o[o.length-1]}}for(letnofawaitthis.parse(r))yield[n]}},fNt=classextendsRJ{constructor(){super(...arguments);x(this,"lc_namespace",["langchain_core","output_parsers","list"]);x(this,"lc_serializable",!0)}staticlc_name(){return"CommaSeparatedListOutputParser"}asyncparse(e){try{returne.trim().split(",").map(r=>r.trim())}catch{thrownewIh(`Could not pa
3. baz`}asyncparse(e){return[...e.matchAll(this.re)??[]].map(r=>r[1])}},hNt=classextendsRJ{constructor(){super(...arguments);x(this,"lc_namespace",["langchain_core","output_parsers","list"]);x(this,"lc_serializable",!0);x(this,"re",/^\s*[-*]\s([^\n]+)$/gm)}staticlc_name(){return"NumberedListOutputParser"}getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
3. baz`}asyncparse(e){return[...e.matchAll(this.re)??[]].map(r=>r[1])}}});varKge,yNt=v(()=>{dF();Kge=classextendsi1{constructor(){super(...arguments);x(this,"lc_namespace",["langchain_core","output_parsers","string"]);x(this,"lc_serializable",!0)}staticlc_name(){return"StrOutputParser"}parse(e){returnPromise.resolve(e)}getFormatInstructions(){return""}_textContentToString(e){returne.text}_imageUrlContentToString(e){thrownewError('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentToString(e){switch(e.type){case"text":case"text_delta":if("text"ine)returnthis._textContentToString(e);break;case"image_url":if("image_url"ine)returnthis._imageUrlContentToString(e);break;default:thrownewError(`Cannot coerce "${e.type}" message part into a string.`)}thrownewError(`Invalid content type: ${e.type}`)}_baseMessageContentToString(e){returne.reduce((r,n)=>r+this._messageContentToString(n),"")}}});varuw,R3e,bNt,_Nt=v(()=>{QN();Ny();MJ();cO();uw=classextendso1{constructor(e){super(e);x(this,"lc_namespace",["langchain","output_parsers","structured"]);this.schema=e}staticlc_name(){return"StructuredOutputParser"}toJSON(){returnthis.toJSONNotImplemented()}staticfromZodSchema(e){returnnewthis(e)}staticfromNamesAndDescriptions(e){letr=wt.object(Object.fromEntries(Object.entries(e).map(([n,o])=>[n,wt.string().describe(o)])));returnnewthis(r)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
"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:
`}asyncparse(e){try{letr=e.trim(),o=(r.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||r.match(/```json\s*([\s\S]*?)```/)?.[1]||r).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(i,a)=>`"${a.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");returnawaitrF(this.schema,JSON.parse(o))}catch(r){thrownewIh(`Failed to parse. Text: "${e}". Error: ${r}`,e)}}},R3e=classextendsuw{staticlc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(t){lete=t?.interpolationDepth??1;if(e<1)thrownewError("f string interpolation depth must be at least 1");return`Return a markdown code snippet with a JSON object formatted to look like:
`?(A.line++,A.column=0):A.column++);A.textNode+=j.substring(re,U-1)}H==="<"&&!(A.sawRoot&&A.closedRoot&&!A.strict)?(A.state=P.OPEN_WAKA,A.startTagPosition=A.position):(!_(H)&&(!A.sawRoot||A.closedRoot)&&B(A,"Text data outside of root node."),H==="&"?A.state=P.TEXT_ENTITY:A.textNode+=H);continue;case P.SCRIPT:H==="<"?A.state=P.SCRIPT_ENDING:A.script+=H;continue;case P.SCRIPT_ENDING:H==="/"?A.state=P.CLOSE_TAG:(A.script+="<"+H,A.state=P.SCRIPT);continue;case P.OPEN_WAKA:if(H==="!")A.state=P.SGML_DECL,A.sgmlDecl="";else if(!_(H))if(O(h,H))A.state=P.OPEN_TAG,A.tagName=H;else if(H==="/")A.state=P.CLOSE_TAG,A.tagName="";else if(H==="?")A.state=P.PROC_INST,A.procInstName=A.procInstBody="";else{if(B(A,"Unencoded <"),A.startTagPosition+1<A.position){var Z=A.position-A.startTagPosition;H=new Array(Z).join(" ")+H}A.textNode+="<"+H,A.state=P.TEXT}continue;case P.SGML_DECL:(A.sgmlDecl+H).toUpperCase()===c?(N(A,"onopencdata"),A.state=P.CDATA,A.sgmlDecl="",A.cdata=""):A.sgmlDecl+H==="--"?(A.state=P.COMMENT,A.comment="",A.sgmlDecl=""):(A.sgmlDecl+H).toUpperCase()===d?(A.state=P.DOCTYPE,(A.doctype||A.sawRoot)&&B(A,"Inappropriately located doctype declaration"),A.doctype="",A.sgmlDecl=""):H===">"?(N(A,"onsgmldeclaration",A.sgmlDecl),A.sgmlDecl="",A.state=P.TEXT):(w(H)&&(A.state=P.SGML_DECL_QUOTED),A.sgmlDecl+=H);continue;case P.SGML_DECL_QUOTED:H===A.q&&(A.state=P.SGML_DECL,A.q=""),A.sgmlDecl+=H;continue;case P.DOCTYPE:H===">"?(A.state=P.TEXT,N(A,"ondoctype",A.doctype),A.doctype=!0):(A.doctype+=H,H==="["?A.state=P.DOCTYPE_DTD:w(H)&&(A.state=P.DOCTYPE_QUOTED,A.q=H));continue;case P.DOCTYPE_QUOTED:A.doctype+=H,H===A.q&&(A.q="",A.state=P.DOCTYPE);continue;case P.DOCTYPE_DTD:A.doctype+=H,H==="]"?A.state=P.DOCTYPE:w(H)&&(A.state=P.DOCTYPE_DTD_QUOTED,A.q=H);continue;case P.DOCTYPE_DTD_QUOTED:A.doctype+=H,H===A.q&&(A.state=P.DOCTYPE_DTD,A.q="");continue;case P.COMMENT:H==="-"?A.state=P.COMMENT_ENDING:A.comment+=H;continue;case P.COMMENT_ENDING:H==="-"?(A.state=P.COMMENT_ENDED,A.comment=V(A.opt,A.comment),A.comment&&N(A,"oncomment",A.comment),A.comment=""):(A.comment+="-"+H,A.state=P.COMMENT);continue;case P.COMMENT_ENDED:H!==">"?(B(A,"Malformed comment"),A.comment+="--"+H,A.state=P.COMMENT):A.state=P.TEXT;continue;case P.CDATA:H==="]"?A.state=P.CDATA_ENDING:A.cdata+=H;continue;case P.CDATA_ENDING:H==="]"?A.state=P.CDATA_ENDING_2:(A.cdata+="]"+H,A.state=P.CDATA);continue;case P.CDATA_ENDING_2:H===">"?(A.cdata&&N(A,"oncdata",A.cdata),N(A,"onclosecdata"),A.cdata="",A.state=P.TEXT):H==="]"?A.cdata+="]":(A.cdata+="]]"+H,A.state=P.CDATA);continue;case P.PROC_INST:H==="?"?A.state=P.PROC_INST_ENDING:_(H)?A.state=P.PROC_INST_BODY:A.procInstName+=H;continue;case P.PROC_INST_BODY:if(!A.procInstBody&&_(H))continue;H==="?"?A.state=P.PROC_INST_ENDING:A.procInstBody+=H;continue;case P.PROC_INST_ENDING:H===">"?(N(A,"onprocessinginstruction",{name:A.procInstName,body:A.procInstBody}),A.procInstName=A.procInstBody="",A.state=P.TEXT):(A.procInstBody+="?"+H,A.state=P.PROC_INST_BODY);continue;case P.OPEN_TAG:O(y,H)?A.tagName+=H:(Q(A),H===">"?oe(A):H==="/"?A.state=P.OPEN_TAG_SLASH:(_(H)||B(A,"Invalid character in tag name"),A.state=P.ATTRIB));continue;case P.OPEN_TAG_SLASH:H===">"?(oe(A,!0),ue(A)):(B(A,"Forward-slash in opening tag not followed by >"),A.state=P.ATTRIB);continue;case P.ATTRIB:if(_(H))continue;H===">"?oe(A):H==="/"?A.state=P.OPEN_TAG_SLASH:O(h,H)?(A.attribName=H,A.attribValue="",A.state=P.ATTRIB_NAME):B(A,"Invalid attribute name");continue;case P.ATTRIB_NAME:H==="="?A.state=P.ATTRIB_VALUE:H===">"?(B(A,"Attribute without value"),A.attribValue=A.attribName,K(A),oe(A)):_(H)?A.state=P.ATTRIB_NAME_SAW_WHITE:O(y,H)?A.attribName+=H:B(A,"Invalid attribute name");continue;case P.ATTRIB_NAME_SAW_WHITE:if(H==="=")A.state=P.ATTRIB_VALUE;else{if(_(H))continue;B(A,"Attribute without value"),A.tag.attributes[A.attribName]="",A.attribValue="",N(A,"onattribute",{name:A.attribName,value:""}),A.attribName="",H===">"?oe(A):O(h,H)?(A.attribName=H,A.state=P.ATTRIB_NAME):(B(A,"Invalid attribute name"),A.state=P.ATTRIB)}continue;case P.ATTRIB_VALUE:if(_(H))continue;w(H)?(A.q
`).trim(),CNt=t=>{if(Object.keys(t).length===0)return{};lete={};returnt.children.length>0?(e[t.name]=t.children.map(CNt),e):(e[t.name]=t.text??void0,e)}});varnwn,fO=v(()=>{Jo();NQ();MJ();dF();dNt();gNt();yNt();_Nt();A3e();xNt();nwn={};$t(nwn,{AsymmetricStructuredOutputParser:()=>bNt,BaseCumulativeTransformOutputParser:()=>cF,BaseLLMOutputParser:()=>v4,BaseOutputParser:()=>o1,BaseTransformOutputParser:()=>i1,BytesOutputParser:()=>cNt,CommaSeparatedListOutputParser:()=>fNt,CustomListOutputParser:()=>pNt,JsonMarkdownStructuredOutputParser:()=>R3e,JsonOutputParser:()=>j_,ListOutputParser:()=>RJ,MarkdownListOutputParser:()=>hNt,NumberedListOutputParser:()=>mNt,OutputParserException:()=>Ih,StringOutputParser:()=>Kge,StructuredOutputParser:()=>uw,XMLOutputParser:()=>SNt,XML_FORMAT_INSTRUCTIONS:()=>Gge,parseJsonMarkdown:()=>AQ,parsePartialJson:()=>Mz,parseXMLMarkdown:()=>Xge})});varjS,IJ=v(()=>{Pg();jS=classextendsGo{constructor(e){super(e);x(this,"lc_serializable",!0);x(this,"lc_namespace",["langchain_core","prompts",this._getPromptType()]);x(this,"inputVariables");x(this,"outputParser");x(this,"partialVariables");x(this,"metadata");x(this,"tags");let{inputVariables:r}=e;if(r.includes("stop"))thrownewError("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,e)}getlc_attributes(){return{partialVariables:void0}}asyncmergePartialAndUserVariables(e){letr=this.partialVariables??{},n={};for(let[i,a]ofObject.entries(r))typeofa=="string"?n[i]=a:n[i]=awaita();return{...n,...e}}asyncinvoke(e,r){letn={...this.metadata,...r?.metadata},o=[...this.tags??[],...r?.tags??[]];returnthis._callWithConfig(i=>this.formatPromptValue(i),e,{...r,tags:o,metadata:n,runType:"prompt"})}}});varown,Zge,ste,ute,N3e,lte=v(()=>{Jo();kL();zL();UC();own={};$t(own,{BasePromptValue:()=>Zge,ChatPromptValue:()=>ute,ImagePromptValue:()=>N3e,StringPromptValue:()=>ste});Zge=classextendsCg{},ste=classextendsZge{constructor(e){super({value:e});x(this,"lc_namespace",["langchain_core","prompt_values"]);x(this,"lc_serializable",!0);x(this,"value");this.value=e}staticlc_name(){return"StringPromptValue"}toString(){returnthis.value}toChatMessages(){return[newqs(this.value)]}},ute=classextendsZge{constructor(e){Array.isArray(e)&&(e={messages:e});super(e);x(this,"lc_namespace",["langchain_core","prompt_values"]);x(this,"lc_serializable",!0);x(this,"messages");this.messages=e.messages}staticlc_name(){return"ChatPromptValue"}toString(){returnfl(this.messages)}toChatMessages(){returnthis.messages}},N3e=classextendsZge{constructor(e){"imageUrl"ine||(e={imageUrl:e});super(e);x(this,"lc_namespace",["langchain_core","prompt_values"]);x(this,"lc_serializable",!0);x(this,"imageUrl");x(this,"value");this.imageUrl=e.imageUrl}staticlc_name(){return"ImagePromptValue"}toString(){returnthis.imageUrl.url}toChatMessages(){return[newqs({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}}});vara1,cte=v(()=>{lte();IJ();a1=classextendsjS{asyncformatPromptValue(t){lete=awaitthis.format(t);returnnewste(e)}}});functionj3e(t){returntypeoft=="function"}functionawn(t){returnNJ(t)?"array":typeoft}functionD3e(t){returnt.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}functionTNt(t,e){returnt!=null&&typeoft=="object"&&eint}functionswn(t,e){returnt!=null&&typeoft!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}functionlwn(t,e){returnuwn.call(t,e)}functiondwn(t){return!lwn(cwn,t)}functionpwn(t){returnString(t).replace(/[&<>"'`=\/]/g,function(r){returnfwn[r]})}functionbwn(t,e){if(!t)return[];varr=!1,n=[],o=[],i=[],a=!1,s=!1,u="",l=0;functionc(){if(a&&!s)for(;i.length;)deleteo[i.pop()];elsei=[];a=!1,s=!1}vard,f,p;functionm(P){if(typeofP=="string"&&(P=P.split(hwn,2)),!NJ(P)||P.length!==2)thrownewError("Invalid tags: "+P);d=newRegExp(D3e(P[0])+"\\s*"),f=newRegExp("\\s*"+D3e(P[1])),p=newRegExp("\\s*"+D3e("}"+P[1]))}m(e||$S.tags);for(varh=newfte(t),y,g,b,_,w,T;!h.eos();){if(y=h.pos,b=h.scanUntil(d),b)for(varO=0,E=b.length;O<E;++O)_=b.cha
`&&(c(),u="",l=0,r=!1);if(!h.scan(d))break;if(a=!0,g=h.scan(ywn)||"name",h.scan(mwn),g==="="?(b=h.scanUntil(ONt),h.scan(ONt),h.scanUntil(f)):g==="{"?(b=h.scanUntil(p),h.scan(gwn),h.scanUntil(f),g="&"):b=h.scanUntil(f),!h.scan(f))throw new Error("Unclosed tag at "+h.pos);if(g==">"?w=[g,b,y,h.pos,u,l,r]:w=[g,b,y,h.pos],l++,o.push(w),g==="#"||g==="^")n.push(w);else if(g==="/"){if(T=n.pop(),!T)throw new Error('Unopened section "'+b+'" at '+y);if(T[1]!==b)throw new Error('Unclosed section "'+T[1]+'" at '+y)}else g==="name"||g==="{"||g==="&"?s=!0:g==="="&&m(b)}if(c(),T=n.pop(),T)throw new Error('Unclosed section "'+T[1]+'" at '+h.pos);return vwn(_wn(o))}function _wn(t){for(var e=[],r,n,o=0,i=t.length;o<i;++o)r=t[o],r&&(r[0]==="text"&&n&&n[0]==="text"?(n[1]+=r[1],n[3]=r[3]):(e.push(r),n=r));return e}function vwn(t){for(var e=[],r=e,n=[],o,i,a=0,s=t.length;a<s;++a)switch(o=t[a],o[0]){case"#":case"^":r.push(o),n.push(o),r=o[4]=[];break;case"/":i=n.pop(),i[5]=o[2],r=n.length>0?n[n.length-1][4]:e;break;default:r.push(o)}return e}function fte(t){this.string=t,this.tail=t,this.pos=0}function AJ(t,e){this.view=t,this.cache={".":this.view},this.parent=e}function qb(){this.templateCache={_cache:{},set:function(e,r){this._cache[e]=r},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}var iwn,NJ,uwn,cwn,fwn,mwn,hwn,ONt,gwn,ywn,$S,dte,Yge,ENt=v(()=>{iwn=Object.prototype.toString,NJ=Array.isArray||function(e){return iwn.call(e)==="[object Array]"};uwn=RegExp.prototype.test;cwn=/\S/;fwn={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};mwn=/\s*/,hwn=/\s+/,ONt=/\s*=/,gwn=/\s*\}/,ywn=/#|\^|\/|>|\{|&|=|!/;fte.prototype.eos=function(){return this.tail===""};fte.prototype.scan=function(e){var r=this.tail.match(e);if(!r||r.index!==0)return"";var n=r[0];return this.tail=this.tail.substring(n.length),this.pos+=n.length,n};fte.prototype.scanUntil=function(e){var r=this.tail.search(e),n;switch(r){case-1:n=this.tail,this.tail="";break;case 0:n="";break;default:n=this.tail.substring(0,r),this.tail=this.tail.substring(r)}return this.pos+=n.length,n};AJ.prototype.push=function(e){return new AJ(e,this)};AJ.prototype.lookup=function(e){var r=this.cache,n;if(r.hasOwnProperty(e))n=r[e];else{for(var o=this,i,a,s,u=!1;o;){if(e.indexOf(".")>0)for(i=o.view,a=e.split("."),s=0;i!=null&&s<a.length;)s===a.length-1&&(u=TNt(i,a[s])||swn(i,a[s])),i=i[a[s++]];else i=o.view[e],u=TNt(o.view,e);if(u){n=i;break}o=o.parent}r[e]=n}return j3e(n)&&(n=n.call(this.view)),n};qb.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};qb.prototype.parse=function(e,r){var n=this.templateCache,o=e+":"+(r||$S.tags).join(":"),i=typeof n<"u",a=i?n.get(o):void 0;return a==null&&(a=bwn(e,r),i&&n.set(o,a)),a};qb.prototype.render=function(e,r,n,o){var i=this.getConfigTags(o),a=this.parse(e,i),s=r instanceof AJ?r:new AJ(r,void 0);return this.renderTokens(a,s,n,e,o)};qb.prototype.renderTokens=function(e,r,n,o,i){for(var a="",s,u,l,c=0,d=e.length;c<d;++c)l=void 0,s=e[c],u=s[0],u==="#"?l=this.renderSection(s,r,n,o,i):u==="^"?l=this.renderInverted(s,r,n,o,i):u===">"?l=this.renderPartial(s,r,n,i):u==="&"?l=this.unescapedValue(s,r):u==="name"?l=this.escapedValue(s,r,i):u==="text"&&(l=this.rawValue(s)),l!==void 0&&(a+=l);return a};qb.prototype.renderSection=function(e,r,n,o,i){var a=this,s="",u=r.lookup(e[1]);function l(f){return a.render(f,r,n,i)}if(u){if(NJ(u))for(var c=0,d=u.length;c<d;++c)s+=this.renderTokens(e[4],r.push(u[c]),n,o,i);else if(typeof u=="object"||typeof u=="string"||typeof u=="number")s+=this.renderTokens(e[4],r.push(u),n,o,i);else if(j3e(u)){if(typeof o!="string")throw new Error("Cannotusehigher-ordersectionswithouttheoriginaltemplate");u=u.call(r.view,o.slice(e[3],e[5]),l),u!=null&&(s+=u)}else s+=this.renderTokens(e[4],r,n,o,i);return s}};qb.prototype.renderInverted=function(e,r,n,o,i){var a=r.lookup(e[1]);if(!a||NJ(a)&&a.length===0)return this.renderTokens(e[4],r,n,o,i)};qb.prototype.indentPartial=function(e,r,n){for(var o=r.replace(/[^ \t]/g,""),i=e.split(`
`)};qb.prototype.renderPartial=function(e,r,n,o){if(n){var i=this.getConfigTags(o),a=j3e(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)}}};qb.prototype.unescapedValue=function(e,r){var n=r.lookup(e[1]);if(n!=null)return n};qb.prototype.escapedValue=function(e,r,n){var o=this.getConfigEscape(n)||$S.escape,i=r.lookup(e[1]);if(i!=null)return typeof i=="number"&&o===$S.escape?String(i):o(i)};qb.prototype.rawValue=function(e){return e[1]};qb.prototype.getConfigTags=function(e){return NJ(e)?e:e&&typeof e=="object"?e.tags:void 0};qb.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!NJ(e))return e.escape};$S={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){dte.templateCache=t},get templateCache(){return dte.templateCache}},dte=new qb;$S.clearCache=function(){return dte.clearCache()};$S.parse=function(e,r){return dte.parse(e,r)};$S.render=function(e,r,n,o){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+awn(e)+'" was given as the first argument for mustache#render(template, view, partials)');return dte.render(e,r,n,o)};$S.escape=pwn;$S.Scanner=fte;$S.Context=AJ;$S.Writer=qb;Yge=$S});function PNt(){Yge.escape=t=>t}var w4,MNt,DJ,$3e,L3e,pte,F3e,Dy,S4,s1,C4=v(()=>{DQ();ENt();w4=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},MNt=(t,e=[])=>{let r=[];for(let n of t)if(n[0]==="name"){let o=n[1].includes(".")?n[1].split(".")[0]:n[1];r.push({type:"variable",name:o})}else if(["#","&","^",">"].includes(n[0])){if(r.push({type:"variable",name:n[1]}),n[0]==="#"&&n.length>4&&Array.isArray(n[4])){let o=[...e,n[1]],i=MNt(n[4],o);r.push(...i)}}else r.push({type:"literal",text:n[1]});return r},DJ=t=>{PNt();let e=Yge.parse(t);return MNt(e)},$3e=(t,e)=>w4(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},""),L3e=(t,e)=>(PNt(),Yge.render(t,e)),pte={"f-string":$3e,mustache:L3e},F3e={"f-string":w4,mustache:DJ},Dy=(t,e,r)=>{try{return pte[e](t,r)}catch(n){throw FL(n,"INVALID_PROMPT_INPUT")}},S4=(t,e)=>F3e[e](t),s1=(t,e,r)=>{if(!(e in pte)){let n=Object.keys(pte);throw new Error(`Invalid template format. Got \`${e}\`;
should be one of ${n}`)}try{let n=Object.fromEntries(r.map(o=>[o,"foo"]));Array.isArray(t)?t.forEach(o=>{if(o.type==="text"&&"text"in o&&typeof o.text=="string")Dy(o.text,e,n);else if(o.type==="image_url"){if(typeof o.image_url=="string")Dy(o.image_url,e,n);else if(typeof o.image_url=="object"&&o.image_url!==null&&"url"in o.image_url&&typeof o.image_url.url=="string"){let i=o.image_url.url;Dy(i,e,n)}}else throw new Error(`Invalid message template received. ${JSON.stringify(o,null,2)}`)}):Dy(t,e,n)}catch(n){throw new Error(`Invalid prompt schema: ${n.message}`)}}});var mu,Qge=v(()=>{cte();C4();mu=class mte extends a1{constructor(r){super(r);x(this,"template");x(this,"templateFormat","f-string");x(this,"validateTemplate",!0);x(this,"additionalContentFields");if(r.templateFormat==="mustache"&&r.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,r),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustachetemplatescannotbevalidated.");let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),s1(this.template,this.templateFormat,n)}}static lc_name(){return"PromptTemplate"}_getPromptType(){return"prompt"}async format(r){let n=await this.mergePartialAndUserVariables(r);return Dy(this.template,this.templateFormat,n)}static fromExamples(r,n,o,i=`
From:${i}`);s=[l[0]]}else s=[];i={url:i},a=new jJ({template:i,inputVariables:s,templateFormat:r?.templateFormat,additionalContentFields:o})}else if(typeof i=="object"){if("url"in i){let u;r?.templateFormat==="mustache"?u=DJ(i.url):u=w4(i.url),s=u.flatMap(l=>l.type==="variable"?[l.name]:[])}else s=[];a=new jJ({template:i,inputVariables:s,templateFormat:r?.templateFormat,additionalContentFields:o})}else throw new Error("Invalid image template");n.push(a)}else typeof o=="object"&&n.push(new hte({template:o,templateFormat:r?.templateFormat}));return new this({prompt:n,additionalOptions:r})}async format(e){if(this.prompt instanceof a1){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}doesnothaveinputVariablesdefined.`);for(let i of n.inputVariables)o||(o={[i]:e[i]}),o={...o,[i]:e[i]};if(n instanceof a1){let i=await n.format(o),a;"additionalContentFields"in n&&(a=n.additionalContentFields),i!==""&&r.push({...a,type:"text",text:i})}else if(n instanceof jJ){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 hte){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)]}},$_=class extends H3e{static _messageClass(){return qs}static lc_name(){return"HumanMessagePromptTemplate"}},tye=class extends H3e{static _messageClass(){return Pn}static lc_name(){return"AIMessagePromptTemplate"}},LS=class extends H3e{static _messageClass(){return Od}static lc_name(){return"SystemMessagePromptTemplate"}};Ah=class eye extends yte{constructor(r){super(r);x(this,"promptMessages");x(this,"validateTemplate",!0);x(this,"templateFormat","f-string");if(r.templateFormat==="mustache"&&r.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,r),this.validateTemplate){let n=new Set;for(let u of this.promptMessages)if(!(u instanceof id))for(let l of u.inputVariables)n.add(l);let o=this.inputVariables,i=new Set(this.partialVariables?o.concat(Object.keys(this.partialVariables)):o),a=new Set([...i].filter(u=>!n.has(u)));if(a.size>0)throw new Error(`Inputvariables\`${[...a]}\` are not used in any of the prompt messages.`);lets=newSet([...n].filter(u=>!i.has(u)));if(s.size>0)thrownewError(`Input variables \`${[...s]}\` are used in prompt messages but not in the prompt template.`)}}staticlc_name(){return"ChatPromptTemplate"}getlc_aliases(){return{promptMessages:"messages"}}_getPromptType(){return"chat"}async_parseImagePrompts(r,n){if(typeofr.content=="string")returnr;leto=awaitPromise.all(r.content.map(asynci=>{if(i.type!=="image_url")returni;leta="";typeofi.image_url=="string"?a=i.image_url:typeofi.image_url=="object"&&i.image_url!==null&&"url"ini.image_url&&typeofi.image_url.url=="string"&&(a=i.image_url.url);letu=awaitmu.fromTemplate(a,{templateFormat:this.templateFormat}).format(n);returntypeofi.image_url=="object"&&i.image_url!==null&&"url"ini.image_url?i.image_url.url=u:i.image_url=u,i}));returnr.content=o,r}asyncformatMessages(r){letn=awaitthis.mergePartialAndUserVariables(r),o=[];for(letiofthis.promptMessages)if(iinstanceofid)o.push(awaitthis._parseImagePrompts(i,n));else{leta;this.templateFormat==="mustache"?a={...n}:a=i.inputVariables.reduce((u,l)=>{if(!(linn)&&!(Twn(i)&&i.optional))throwFL(newError(`Missing value for input variable \`${l.toString()}\``),"INVALID_PROMPT_INPUT");returnu[l]=n[l],u},{});lets=awaiti.formatMessages(a);o=o.concat(s)}returno}asyncpartial(r){letn=this.inputVariables.filter(a=>!(ainr)),o={...this.partialVariables??{},...r},i={...this,inputVariables:n,partialVariables:o};returnneweye(i)}staticfromTemplate(r,n){leto=mu.fromTemplate(r,n),i=new$_({prompt:o});returnthis.fromMessages([i])}staticfromMessages(r,n){leto=r.reduce((s,u)=>s.concat(uinstanceofeye?u.promptMessages:[xwn(u,n)]),[]),i=r.reduce((s,u)=>u
`);x(this,"prefix","");x(this,"templateFormat","f-string");x(this,"validateTemplate",!0);if(Object.assign(this,r),this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),s1(this.prefix+this.suffix,this.templateFormat,n)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(r){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(r);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(r){let n=this.inputVariables.filter(a=>!(a in r)),o={...this.partialVariables??{},...r},i={...this,inputVariables:n,partialVariables:o};return new W3e(i)}async format(r){let n=await this.mergePartialAndUserVariables(r),o=await this.getExamples(n),i=await Promise.all(o.map(s=>this.examplePrompt.format(s))),a=[this.prefix,...i,this.suffix].join(this.exampleSeparator);return Dy(a,this.templateFormat,n)}serialize(){if(this.exampleSelector||!this.examples)throw new Error("Serializing an example selector is not currently supported");if(this.outputParser!==void 0)throw new Error("Serializing an output parser is not currently supported");return{_type:this._getPromptType(),input_variables:this.inputVariables,example_prompt:this.examplePrompt.serialize(),example_separator:this.exampleSeparator,suffix:this.suffix,prefix:this.prefix,template_format:this.templateFormat,examples:this.examples}}static async deserialize(r){let{example_prompt:n}=r;if(!n)throw new Error("Missing example prompt");let o=await mu.deserialize(n),i;if(Array.isArray(r.examples))i=r.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new W3e({inputVariables:r.input_variables,examplePrompt:o,examples:i,exampleSeparator:r.example_separator,prefix:r.prefix,suffix:r.suffix,templateFormat:r.template_format})}},ANt=class NNt extends yte{constructor(r){super(r);x(this,"lc_serializable",!0);x(this,"examples");x(this,"exampleSelector");x(this,"examplePrompt");x(this,"suffix","");x(this,"exampleSeparator",`
`,this.exampleSelector=r.exampleSelector,this.prefix=r.prefix??"",this.suffix=r.suffix??"",this.templateFormat=r.templateFormat??"f-string",this.validateTemplate=r.validateTemplate??!0,this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),s1(this.prefix+this.suffix,this.templateFormat,n)}}_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}async getExamples(r){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(r);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(r){let n=await this.mergePartialAndUserVariables(r),o=await this.getExamples(n);o=o.map(a=>{let s={};return this.examplePrompt.inputVariables.forEach(u=>{s[u]=a[u]}),s});let i=[];for(let a of o){let s=await this.examplePrompt.formatMessages(a);i.push(...s)}return i}async format(r){let n=await this.mergePartialAndUserVariables(r),o=await this.getExamples(n),a=(await Promise.all(o.map(u=>this.examplePrompt.formatMessages(u)))).flat().map(u=>u.content),s=[this.prefix,...a,this.suffix].join(this.exampleSeparator);return Dy(s,this.templateFormat,n)}async partial(r){let n=this.inputVariables.filter(a=>!(a in r)),o={...this.partialVariables??{},...r},i={...this,inputVariables:n,partialVariables:o};return new NNt(i)}}});var jNt,$Nt=v(()=>{IJ();bte();jNt=class rye extends jS{constructor(r){super({...r,inputVariables:[]});x(this,"pipelinePrompts");x(this,"finalPrompt");this.pipelinePrompts=r.pipelinePrompts,this.finalPrompt=r.finalPrompt,this.inputVariables=this.computeInputValues()}static lc_name(){return"PipelinePromptTemplate"}computeInputValues(){let r=this.pipelinePrompts.map(o=>o.name),n=this.pipelinePrompts.map(o=>o.prompt.inputVariables.filter(i=>!r.includes(i))).flat();return[...new Set(n)]}static extractRequiredInputValues(r,n){return n.reduce((o,i)=>(o[i]=r[i],o),{})}async formatPipelinePrompts(r){let n=await this.mergePartialAndUserVariables(r);for(let{name:o,prompt:i}of this.pipelinePrompts){let a=rye.extractRequiredInputValues(n,i.inputVariables);i instanceof Ah?n[o]=await i.formatMessages(a):n[o]=await i.format(a)}return rye.extractRequiredInputValues(n,this.finalPrompt.inputVariables)}async formatPromptValue(r){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(r))}async format(r){return this.finalPrompt.format(await this.formatPipelinePrompts(r))}async partial(r){let n={...this};return n.inputVariables=this.inputVariables.filter(o=>!(o in r)),n.partialVariables={...this.partialVariables??{},...r},new rye(n)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}}});function LNt(t){return typeof t=="object"&&t!=null&&"withStructuredOutput"in t&&typeof t.withStructuredOutput=="function"}function Own(t){return typeof t=="object"&&t!=null&&"lc_id"in t&&Array.isArray(t.lc_id)&&t.lc_id.join("/")==="langchain_core/runnables/RunnableBinding"}var FNt,qNt=v(()=>{Pg();bte();FNt=class kNt extends Ah{constructor(r){super(r);x(this,"schema");x(this,"method");x(this,"lc_namespace",["langchain_core","prompts","structured"]);this.schema=r.schema,this.method=r.method}get lc_aliases(){return{...super.lc_aliases,schema:"schema_"}}pipe(r){if(LNt(r))return super.pipe(r.withStructuredOutput(this.schema));if(Own(r)&&LNt(r.bound))return super.pipe(new DS({bound:r.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:r.kwargs??{},config:r.config,configFactories:r.configFactories}));throw new Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(r,n,o){return kNt.fromMessages(r,{schema:n,method:o})}}});var E
`)});functionbc(t,e){letr=`atom${++Rwn}`,n={toString(){return(zl.env?zl.env.MODE:void0)!=="production"&&this.debugLabel?r+":"+this.debugLabel:r}};returntypeoft=="function"?n.read=t:(n.init=t,n.read=Iwn,n.write=Awn),e&&(n.write=e),n}functionIwn(t){returnt(this)}functionAwn(t,e,r){returne(this,typeofr=="function"?r(t(this)):r)}varzl,Rwn,UNt,K3e,G3e,iye,Z3e,Nwn,Dwn,Y3e,BNt,oye,HNt,zNt,LJ,X3e,jwn,$wn,VNt,fF,WNt,pF,vte,JNt,Q3e=v(()=>{zl={},Rwn=0;UNt=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,K3e=t=>"init"int,G3e=t=>!!t.write,iye=newWeakMap,Z3e=t=>{vare;returnY3e(t)&&!((e=iye.get(t))!=null&&e[1])},Nwn=(t,e)=>{letr=iye.get(t);if(r)r[1]=!0,r[0].forEach(n=>n(e));elseif((zl.env?zl.env.MODE:void0)!=="production")thrownewError("[Bug] cancelable promise not found")},Dwn=t=>{if(iye.has(t))return;lete=[newSet,!1];iye.set(t,e);letr=()=>{e[1]=!0};t.then(r,r),t.onCancel=n=>{e[0].add(n)}},Y3e=t=>typeoft?.then=="function",BNt=t=>"v"int||"e"int,oye=t=>{if("e"int)throwt.e;if((zl.env?zl.env.MODE:void0)!=="production"&&!("v"int))thrownewError("[Bug] atom state is not initialized");returnt.v},HNt=(t,e,r)=>{r.p.has(t)||(r.p.add(t),e.then(()=>{r.p.delete(t)},()=>{r.p.delete(t)}))},zNt=(t,e,r,n,o)=>{vari;if((zl.env?zl.env.MODE:void0)!=="production"&&n===e)thrownewError("[Bug] atom cannot depend on itself");r.d.set(n,o.n),Z3e(r.v)&&HNt(e,r.v,o),(i=o.m)==null||i.t.add(e),t&&jwn(t,n,e)},LJ=()=>[newMap,newMap,newSet],X3e=(t,e,r)=>{t[0].has(e)||t[0].set(e,newSet),t[1].set(e,r)},jwn=(t,e,r)=>{letn=t[0].get(e);n&&n.add(r)},$wn=(t,e)=>t[0].get(e),VNt=(t,e)=>{t[2].add(e)},fF=t=>{lete,r=!1,n=o=>{try{o()}catch(i){r||(e=i,r=!0)}};for(;t[1].size||t[2].size;){t[0].clear();leto=newSet(t[1].values());t[1].clear();leti=newSet(t[2]);t[2].clear(),o.forEach(a=>{vars;return(s=a.m)==null?void0:s.l.forEach(n)}),i.forEach(n)}if(r)throwe},WNt=(...[t,e,r,n])=>{leto;(zl.env?zl.env.MODE:void0)!=="production"&&(o=newSet);leti=(_,w,T)=>{letO="v"inw,E=w.v,P=Z3e(w.v)?w.v:null;if(Y3e(T)){Dwn(T);for(letRofw.d.keys())HNt(_,T,t(R));w.v=T,deletew.e}elsew.v=T,deletew.e;(!O||!Object.is(E,w.v))&&(++w.n,P&&Nwn(P,T))},a=(_,w,T)=>{varO;letE=t(w);if(BNt(E)&&(E.m&&!T?.has(w)||Array.from(E.d).every(([V,k])=>a(_,V,T).n===k)))returnE;E.d.clear();letP=!0,R=V=>{if(UNt(w,V)){letX=t(V);if(!BNt(X))if(K3e(V))i(V,X,V.init);elsethrownewError("no atom init");returnoye(X)}letk=a(_,V,T);try{returnoye(k)}finally{if(P)zNt(_,w,E,V,k);else{letX=LJ();zNt(X,w,E,V,k),p(X,w,E),fF(X)}}},I,N,z={getsignal(){returnI||(I=newAbortController),I.signal},getsetSelf(){return(zl.env?zl.env.MODE:void0)!=="production"&&!G3e(w)&&console.warn("setSelf function cannot be used with read-only atom"),!N&&G3e(w)&&(N=(...V)=>{if((zl.env?zl.env.MODE:void0)!=="production"&&P&&console.warn("setSelf function cannot be called in sync"),!P)returnf(w,...V)}),N}};try{letV=e(w,R,z);if(i(w,E,V),Y3e(V)){(O=V.onCancel)==null||O.call(V,()=>I?.abort());letk=()=>{if(E.m){letX=LJ();p(X,w,E),fF(X)}};V.then(k,k)}returnE}catch(V){returndeleteE.v,E.e=V,++E.n,E}finally{P=!1}},s=_=>oye(a(void0,_)),u=(_,w,T)=>{varO,E;letP=newMap;for(letRof((O=T.m)==null?void0:O.t)||[])P.set(R,t(R));for(letRofT.p)P.set(R,t(R));return(E=$wn(_,w))==null||E.forEach(R=>{P.set(R,t(R))}),P};functionl(_,w,T){letO=[],E=newSet,P=newSet,R=[[w,T]];for(;R.length>0;){let[I,N]=R[R.length-1];if(P.has(I)){R.pop();continue}if(E.has(I)){O.push([I,N,N.n]),P.add(I),R.pop();continue}E.add(I);for(let[z,V]ofu(_,I,N))I!==z&&!E.has(z)&&R.push([z,V])}return[O,P]}letc=(_,w,T)=>{let[O,E]=l(_,w,T),P=newSet([w]);for(letR=O.length-1;R>=0;--R){let[I,N,z]=O[R],V=!1;for(letkofN.d.keys())if(k!==I&&P.has(k)){V=!0;break}V&&(a(_,I,E),p(_,I,N),z!==N.n&&(X3e(_,I,N),P.add(I))),E.delete(I)}},d=(_,w,...T)=>{letO=!0,E=R=>oye(a(_,R)),P=(R,...I)=>{letN=t(R);try{if(UNt(w,R)){if(!K3e(R))thrownewError("atom not writable");letz=N.n,V=I[0];i(R,N,V),p(_,R,N),z!==N.n&&(X3e(_,R,N),c(_,R,N));return}elsereturnd(_,R,...I)}finally{O||fF(_)}};try{returnr(w,E,P,...T)}finally{O=!1}},f=(_,...w)=>{letT=LJ();try{returnd
`)||o.startsWith("\r")?o.slice(1):o}}returnt}functiongO(t,e=!0){letr=app.metadataCache.getFileCache(t),n=r?.frontmatter?.tags,o=newSet;if(!e){leti=r?.tags?.map(a=>a.tag);i&&i.forEach(a=>o.add(VJ(a)))}returnn&&(Array.isArray(n)?n.forEach(i=>{typeofi=="string"&&o.add(VJ(i))}):typeofn=="string"&&o.add(VJ(n))),Array.from(o)}functionmye(t,e,r){if(e.length===0)return[];e=e.map(i=>VJ(i));letn=r&&r.length>0?r:Ote(t,"/"),o=[];for(letiofn){leta=gO(i);e.some(s=>a.includes(s))&&o.push(i)}returno}asyncfunction$c(t){lete=(0,$y.normalizePath)(t).replace(/^\/+/,"").replace(/\/+$/,"");if(!e)return;letr=e.split("/").filter(Boolean),n="";for(letoofr){n=n?`${n}/${o}`:o;leti=app.vault.getAbstractFileByPath(n);if(i){if(iinstanceof$y.TFile)thrownewError(`Path conflict: "${n}" exists as a file, expected folder.`);continue}awaitapp.vault.adapter.mkdir(n)}}asyncfunctionWJ(t,e){returnt.extension!="md"&&t.extension!="canvas"?null:awaite.cachedRead(t)}functionhye(t){returnt.basename}functionyO(t){returnt?dSn.includes(t.extension):!1}functionzb(t){returnt==="copilot_plus"||t==="project"}functionJJ(t,e){returnt?t.extension==="md"||t.extension==="canvas"?!0:zb(e):!1}functionw1t(t,e){return!t||!e?!1:t.includes(hWe)&&e.includes(hWe)||t==="small"&&e==="cohereai"||t==="cohereai"&&e==="small"?!0:t===e}functiongye(t){lete=[],{history:r}=t;for(letn=0;n<r.length;n+=2){leto=r[n]?.content||"",i=r[n+1]?.content||"";e.push({role:"user",content:o},{role:"assistant",content:i})}returne}functionS1t(t,e){letr=newMap;returnt.forEach(n=>{leto=e.getAbstractFileByPath(n);if(oinstanceof$y.TFile)r.set(o.path,o);else{leta=e.getMarkdownFiles().filter(s=>s.basename===n);a.length>0&&(fSn(n,e)?r.set(a[0].path,a[0]):console.warn(`Found multiple files with title "${n}". Expected a full path for duplicate titles.`))}}),Array.from(r.values())}functionkS(t,e){letr=/\[\[(.*?)\]\]/g,n=t.match(r);if(!n)return[];leto=n.map(i=>i.slice(2,-2));returnS1t(o,e)}functionC1t(t,e){letr=/\{\[\[(.*?)\]\]\}/g,n=t.match(r);if(!n)return[];leto=n.map(i=>i.slice(3,-3));returnS1t(o,e)}functionfSn(t,e){returne.getMarkdownFiles().filter(n=>n.basename===t).length===1}functionx1t(t){returnt=t.trim(),t.startsWith("[[")&&t.endsWith("]]")?`${t.slice(2,-2).trim()}.md`:t}functionT1t(t){lete=newSet;returnt.forEach(r=>{r.metadata?.title&&e.add(r.metadata?.title)}),Array.from(e)}functiongWe(t){if(!t||typeoft!="string")return{isValid:!1,error:"URL is required"};lete=t.trim();if(!e)return{isValid:!1,error:"URL cannot be empty"};letr=yWe(e);returnr?/^[a-zA-Z0-9_-]{11}$/.test(r)?{isValid:!0,videoId:r}:{isValid:!1,error:"Invalid YouTube video ID"}:{isValid:!1,error:"Invalid YouTube URL format"}}functionyWe(t){try{lete=[/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/v\/)([a-zA-Z0-9_-]{11})/,/youtube\.com\/shorts\/([a-zA-Z0-9_-]{11})/];for(letrofe){letn=t.match(r);if(n&&n[1])returnn[1]}returnnull}catch{returnnull}}functionO1t(t){return`https://www.youtube.com/watch?v=${t}`}functionE1t(t){returngWe(t).isValid}functionP1t(t){if(!t||typeoft!="string")return!1;try{lete=newURL(t.trim());return(e.hostname==="x.com"||e.hostname==="www.x.com"||e.hostname==="twitter.com"||e.hostname==="www.twitter.com")&&e.pathname.includes("/status/")}catch{return!1}}functionM1t(t){lete=t.matchAll(newRegExp(pSn,"g"));returnArray.from(e,r=>r[0])}asyncfunctiongl(t,e={}){let{throwOnHttpError:r=!0}=e,n=newHeaders(e.headers),o=Object.fromEntries(n.entries());deleteo["content-length"],F("safeFetch request");leti=e.method?.toUpperCase()||"POST",s=await(0,$y.requestUrl)({url:t,contentType:"application/json",headers:o,method:i,...["POST","PUT","PATCH"].includes(i)&&{body:e.body?.toString()},throw:!1});if(r&&s.status>=400){letu;try{u=typeofs.json=="string"?JSON.parse(s.json):s.json}catch{try{u=typeofs.text=="string"?JSON.parse(s.text):s.text}catch{u=null}}letl=newError(mWe.REQUEST_FAILED(s.status));if(l.json=u,u?.detail?.reason==="Invalid license key"||u?.reason==="Invalid license key")l.message="Invalid license key";elseif
`),e=e.trim(),e}async function KJ(t,e=!1){let r=app.workspace.getMostRecentLeaf();if(!r){new $y.Notice("No active leaf found.");return}if(r.view instanceof $y.MarkdownView||(r=app.workspace.getLeaf(!1),await r.setViewState({type:"markdown",state:r.view.getState()})),!(r.view instanceof $y.MarkdownView)){new $y.Notice("Failed to open a markdown view.");return}let n=r.view.editor,o=n.getCursor("from"),i=n.getCursor("to"),a=f1(t),s=a.split(`
`),u=(b,_)=>{let w=_.length-1;return w===0?{line:b.line,ch:b.ch+(_[0]?.length??0)}:{line:b.line+w,ch:_[_.length-1]?.length??0}},l=()=>{let b=e?o:i;n.replaceRange(a,b,i),n.setSelection(b,u(b,s))},c=()=>{n.focus(),new $y.Notice("Message inserted into the active note.")},d=n.cm;if(!(d?.state?.doc&&typeof d.dispatch=="function")){l(),c();return}let{from:p,to:m}=d.state.selection.main,h=e?p:m,y=d.state.toText(a),g=h+y.length;try{d.dispatch({changes:{from:h,to:m,insert:y},selection:{anchor:h,head:g}})}catch(b){Te("CM6 dispatch failed, falling back to Obsidian API",b),l()}c()}function yye(t,e){let r;return(...n)=>{clearTimeout(r),r=setTimeout(()=>t(...n),e)}}function bye(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let o=0;o<3;o++){if(r[o]>n[o])return!0;if(r[o]<n[o])return!1}return!1}async function I1t(){try{return{version:(await(0,$y.requestUrl)({url:"https://api.github.com/repos/logancyang/obsidian-copilot/releases/latest",method:"GET"})).json.tag_name.replace("v",""),error:null}}catch(t){return{version:null,error:t instanceof Error?t.message:"Failed to check for updates"}}}function Pte(t){if(typeof t=="string")return t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4");let e=t.modelName||t.model||"";return e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4")}function hSn(t){return typeof t=="string"?t.startsWith("gpt-5"):(t.modelName||t.model||"").startsWith("gpt-5")}function GJ(t){let e=typeof t=="string"?t:t.modelName||t.model||"",r=Pte(e),n=hSn(e),o=e.startsWith("claude-3-7-sonnet")||e.startsWith("claude-sonnet-4")||e.startsWith("claude-opus-4");return{isOSeries:r,isGPT5:n,isThinkingEnabled:o}}function Mte(t,e="system"){return Pte(t)?"human":e}function bWe(){let t=["3rd party (openai-format)","ollama","lm-studio","azure openai","github-copilot","copilot-plus","copilot-plus-jina"];return Object.keys(QC).filter(e=>!t.includes(e))}function XJ(t,e){if(t.provider==="amazon-bedrock")return t.apiKey||e.amazonBedrockApiKey?{hasApiKey:!0}:{hasApiKey:!1,errorNotice:"Amazon Bedrock API key is missing. Please add a key in Settings > API Keys or update the model configuration."};if(t.provider==="github-copilot")return!(t.apiKey||e.githubCopilotToken||e.githubCopilotAccessToken)?{hasApiKey:!1,errorNotice:"GitHub Copilot is not authenticated. Please connect it in Settings > Copilot > Basic Tab > Set Keys."}:{hasApiKey:!0};let r=!!bWe().find(o=>o===t.provider),n=!Bb(t.provider,t);return r&&n?{hasApiKey:!1,errorNotice:`PleaseconfigureAPIKeyfor${t.name}insettingsfirst.
Path:Settings>copilotplugin>BasicTab>SetKeys`}:{hasApiKey:!0}}function M4(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>e.text).join(""):String(t||"")}function Rte(t){let r=M4(t).replace(/<think>[\s\S]*?<\/think>/g,"");return r=r.replace(/<think>[\s\S]*$/g,""),r.trim()}function _ye(t){return M4(t).replace(/<errorChunk>[\s\S]*?<\/errorChunk>/g,"").trim()}function A1t(){return crypto.randomUUID()}async function Vb(t){let e=console.warn;try{return console.warn=function(...r){if(!(r[0]?.includes&&(r[0].includes("Failed to calculate number of tokens")||r[0].includes("Unknown model"))))return e.apply(console,r)},await t()}finally{console.warn=e}}async function N1t(t,e,r="Operation"){let{TimeoutError:n}=await Promise.resolve().then(()=>(lw(),g1t)),o=new AbortController,i=setTimeout(()=>{o.abort()},e);try{return await Promise.race([t(o.signal),new Promise((a,s)=>{o.signal.addEventListener("abort",()=>{s(new n(r,e))})})])}finally{clearTimeout(i)}}function Ite(){let t=app.workspace.getActiveViewOfType($y.MarkdownView);return t?t.getState().source===!0:!0}function P4(t){return new TextEncoder().encode(t).length}function Tte(t,e){if(e<=0)return"";let r=new TextEncoder;if(r.encode(t).length<=e)return t;let o=0,i=t.length,a="";for(;o<=i;){let s=Math.floor((o+i)/2),u=t.substring(0,s);r.encode(u).length<=e?(a=u,o=s+1):i=s-1}return a}function D1t(t){let e=t.split("/"),r=e[e.length-1];if(P4(r)<=pWe)return t;let n=r.lastIndexOf("."),o=n>=0?r.substring(n):"",i=n>=0?r.substring(0,n):r,a=P4(o),s=pWe-a;return s<=0?e[e.length-1]=Tte(r,pWe):e[e.length-1]=Tte(i,s)+o,e.join("/")}async function j1t(t,e=!0){let r=null;app.workspace.iterateAllLeaves(n=>{if(n.view.getViewType()==="markdown"||n.view.getViewType()==="pdf"||n.view.getViewType()==="canvas"){let o=n.view.file;o&&o.path===t.path&&(r=n)}}),r&&e?app.workspace.setActiveLeaf(r,{focus:!0}):r||await app.workspace.getLeaf("tab").openFile(t)}var y1t,$y,mWe,Ote,lSn,cSn,v1t,Mg,dSn,pSn,pWe,Bt=v(()=>{sd();mr();Xe();y1t=$(m1t()),$y=require("obsidian");hF();cWe();mWe={INVALID_LICENSE_KEY_USER:"Invalid Copilot Plus license key. Please check your license key in settings.",UNKNOWN_ERROR:"An unknown error occurred",REQUEST_FAILED:t=>`Requestfailed,status${t}`};Ote=(t,e)=>{let r=t.getMarkdownFiles();if(e==="/")return r;let n=e.toLowerCase().replace(/^\/|\/$/g,"");return r.filter(o=>{let a=o.path.toLowerCase().split("/"),s=n.split("/"),u=0;for(let l of s){for(;u<a.length&&a[u]!==l;)u++;if(u>=a.length)return!1}return!0})};lSn=t=>t.last?.modelName||t.last?.model,cSn=t=>t.last?.retriever!==void 0,v1t=t=>lSn(t)||cSn(t),Mg=(t,e="local")=>{let r=(0,y1t.default)(t);return e==="utc"&&r.utc(),{fileName:r.format("YYYYMMDD_HHmmss"),display:r.format("YYYY/MM/DD HH:mm:ss"),epoch:r.valueOf()}};dSn=["md","pdf","canvas"];pSn=/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|shorts\/)|youtu\.be\/)([^\s&]+)/;pWe=255});var ZJ,_We,Ate,sd=v(()=>{fO();FS();sw();J3e();Bt();ZJ=class ZJ{static createNewLLMChain(e){let{llm:r,memory:n,prompt:o,abortController:i}=e,a=r.withConfig({signal:i?.signal}),s=Bl.from([{input:u=>u.input,memory:()=>n.loadMemoryVariables({})},{input:u=>u.input,history:u=>u.memory.history},o,a]);return ZJ.instances.set("llm_chain",s),console.log("New LLM chain created."),s}static getLLMChainFromMap(e){let r=ZJ.instances.get("llm_chain");return r||(r=ZJ.createNewLLMChain(e)),r}static createConversationalRetrievalChain(e,r,n){let{llm:o,retriever:i,systemMessage:a}=e,u=mu.fromTemplate(`Giventhefollowingconversationandafollowupquestion,
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.
8. When showing **Obsidian internal** image links, use ![[link]] format and do not wrap them in \` \`.
9. When showing **web** image links, use  format and do not wrap them in \` \`.
10. When generating a table, format as github markdown tables, however, for table headings, immediately add ' |' after the table heading.
11. Always respond in the language of the user's query.
12. Do NOT mention the additional context provided such as getCurrentTime and getTimeRangeMs if it's irrelevant to the user message.
13. If the user mentions "tags", it most likely means tags in Obsidian note properties.
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.
15. For markdown lists, always use '- ' (hyphen followed by exactly one space) for bullet points, with no leading spaces before the hyphen. Never use '*' (asterisk) for bullets.`,F1t=`Return the new note content or canvas JSON in <writeToFile> tags.
`,Dte="note_context",q_="selected_text",wWe="web_selected_text",jte="variable",R4="variable_note",$te="embedded_pdf",SWe="embedded_note",Lte="dataview_block",CWe="retrieved_document",xWe="web_tab_context",vye="active_web_tab",TWe="youtube_video_context",Fte="{activeWebTab}",wye=6e3,Sye=.4,OWe=448e3,Cye=3e4,Ly=30,EWe=5*60*1e3,dye=16,dw={DEFAULT:"",READING_FILES:"Reading files",SEARCHING_WEB:"Searching the web",READING_FILE_TREE:"Reading file tree",COMPACTING:"Compacting"},m1={SETTINGS:"settings",EXPIRED_MODAL:"expired_modal",CHAT_MODE_SELECT:"chat_mode_select",MODE_SELECT_TOOLTIP:"mode_select_tooltip"},Hb={MAX_TOKENS:6e3,TEMPERATURE:.1,REASONING_EFFORT:"low",VERBOSITY:"medium"},k_=(g=>(g.OPENROUTERAI="openrouterai",g.OPENAI="openai",g.OPENAI_FORMAT="3rd party (openai-format)",g.ANTHROPIC="anthropic",g.GOOGLE="google",g.XAI="xai",g.AMAZON_BEDROCK="amazon-bedrock",g.AZURE_OPENAI="azure openai",g.GROQ="groq",g.OLLAMA="ollama",g.LM_STUDIO="lm-studio",g.COPILOT_PLUS="copilot-plus",g.MISTRAL="mistralai",g.DEEPSEEK="deepseek",g.COHEREAI="cohereai",g.SILICONFLOW="siliconflow",g.GITHUB_COPILOT="github-copilot",g))(k_||{}),gF={reasoning:"This model supports general reasoning tasks.",vision:"This model supports image inputs.",websearch:"This model can access the internet."},hO=[{name:"copilot-plus-flash",provider:"copilot-plus",enabled:!0,isBuiltIn:!0,core:!0,plusExclusive:!0,projectEnabled:!1,capabilities:["vision"]},{name:"google/gemini-3-flash-preview",provider:"openrouterai",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"google/gemini-3.1-pro-preview",provider:"openrouterai",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{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:!1,projectEnabled:!0,capabilities:["vision"]},{name:"openai/gpt-5.2",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"openai/gpt-5-mini",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"grok-4-1-fast",provider:"xai",enabled:!0,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"x-ai/grok-4.1-fast",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-5.2",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-4.1",provider:"openai",enabled:!0,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-4.1-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"claude-opus-4-6",provider:"anthropic",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"claude-sonnet-4-5-20250929",provider:"anthropic",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-3-flash-preview",provider:"google",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-3.1-pro-preview",provider:"google",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-2.5-flash",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gemini-2.5-pro",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"azure-openai",provider:"azure openai",enabled:!0,isBuiltIn:!0},{name:"deepseek-chat",provider:"deepseek",enabled:!0,isBuiltIn:!0},{name:"deepseek-reasoner",provider:"deepseek",enabled:!0,isBuiltIn:!0,capabilities:["reasoning"]},{name:"deepseek-ai/DeepSeek-V3",provider:"siliconflow",enabled:!1,isBuiltIn:!1,baseUrl:"https://api.siliconflow.com/v1"},{name:"deepseek-ai/DeepSeek-R1",provider:"siliconflow",enabled:!1,isBuiltIn:!1,baseUrl:"https://api.siliconflow.com/v1",capabilities:["reasoning"]}],YC=(d=>(d.OPENAI="openai",d.OPENROUTERAI="openrouterai",d.COHEREAI="cohereai",d.GOOGLE="google",d.
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")returnCw(i);if(o==="hex")returnU6t(i);if(o===void0||o==="utf8"||o==="utf-8")returnPve(i);if(typeofTextDecoder=="function")returnnewTextDecoder(o).decode(i);thrownewError("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(e)thrownewError(z6t);if(e=!0,V6t(t))returnn(t);if(uKe(t))returnt;thrownewError(`Cannot transform payload to web stream, got ${t}`)}})},V6t=t=>typeofBlob=="function"&&tinstanceofBlob});varJ6t=v(()=>{});varfKe=v(()=>{h6t();g6t();b6t();_6t();v6t();w6t();W6t();J6t()});var$1,pKe=v(()=>{fKe();$1=async(t=newUint8Array,e)=>{if(tinstanceofUint8Array)returnY5.mutate(t);if(!t)returnY5.mutate(newUint8Array);letr=e.streamCollector(t);returnY5.mutate(awaitr)}});functionmKe(t){returnencodeURIComponent(t).replace(/[!'()*]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}varK6t=v(()=>{});varnk,hKe=v(()=>{nk=t=>typeoft=="function"?t():t});varRve,Ive=v(()=>{Rve=(t,e,r,n,o)=>({name:e,namespace:t,traits:r,input:n,output:o})});varG6t,X6t,gKe,Z6t=v(()=>{mne();G6t=$(r0());Ive();X6t=t=>(e,r)=>asyncn=>{let{response:o}=awaite(n),{operationSchema:i}=(0,G6t.getSmithyContext)(r),[,a,s,u,l,c]=i??[];try{letd=awaitt.protocol.deserializeResponse(Rve(a,s,u,l,c),{...t,...r},o);return{response:o,output:d}}catch(d){if(Object.defineProperty(d,"$response",{value:o,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"ind)){letf="Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";try{d.message+=`
`+f}catch{!r.logger||r.logger?.constructor?.name==="NoOpLogger"?console.warn(f):r.logger?.warn?.(f)}typeofd.$responseBodyText<"u"&&d.$response&&(d.$response.body=d.$responseBodyText);try{if(Z5.isInstance(o)){let{headers:p={}}=o,m=Object.entries(p);d.$metadata={httpStatusCode:o.statusCode,requestId:gKe(/^x-[\w-]+-request-?id$/,m),extendedRequestId:gKe(/^x-[\w-]+-id-2$/,m),cfId:gKe(/^x-[\w-]+-cf-id$/,m)}}}catch{}}throwd}},gKe=(t,e)=>(e.find(([r])=>r.match(t))||[void0,void0])[1]});varY6t,Q6t,eJt=v(()=>{Y6t=$(r0());Ive();Q6t=t=>(e,r)=>asyncn=>{let{operationSchema:o}=(0,Y6t.getSmithyContext)(r),[,i,a,s,u,l]=o??[],c=r.endpointV2?.url&&t.urlParser?async()=>t.urlParser(r.endpointV2.url):t.endpoint,d=awaitt.protocol.serializeRequest(Rve(i,a,s,u,l),n.input,{...t,...r,endpoint:c});returne({...n,request:d})}});functionAve(t){return{applyToStack:e=>{e.add(Q6t(t),QEn),e.add(X6t(t),YEn),t.protocol.setSerdeContext(t)}}}varYEn,QEn,tJt=v(()=>{Z6t();eJt();YEn={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},QEn={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});varn0,m2=v(()=>{n0=class{constructor(){x(this,"name");x(this,"namespace");x(this,"traits")}staticassign(e,r){returnObject.assign(e,r)}static[Symbol.hasInstance](e){letr=this.prototype.isPrototypeOf(e);return!r&&typeofe=="object"&&e!==null?e.symbol===this.symbol:r}getName(){returnthis.namespace+"#"+this.name}}});varNve,rJt,nJt=v(()=>{m2();Nve=classNveextendsn0{constructor(){super(...arguments);x(this,"name");x(this,"traits");x(this,"valueSchema");x(this,"symbol",Nve.symbol)}};x(Nve,"symbol",Symbol.for("@smithy/lis"));rJt=Nve});varDve,oJt,iJt=v(()=>{m2();Dve=classDveextendsn0{constructor(){super(...arguments);x(this,"name");x(this,"traits");x(this,"keySchema");x(this,"valueSchema");x(this,"symbol",Dve.symbol)}};x(Dve,"symbol",Symbol.for("@smithy/map"));oJt=Dve});varjve,aJt,sJt=v(()=>{m2();jve=classjveextendsn0{constructor(){super(...arguments);x(this,"name");x(this,"traits");x(this,"input");x(this,"output");x(this,"symbol",jve.symbol)}};x(jve,"symbol",Symbol.for("@smithy/ope"));aJt=jve});varLve,$ve,yKe=v(()=>{m2();Lve=classLveextendsn0{constructor(){super(...arguments);x(this,"name");x(this,"traits");x(this,"memberNames");x(this,"memberList");x(this,"symbol",Lve.symbol)}};x(Lve,"symbol",Symbol.for("@smithy/str"));$ve=Lve});varFve,uJt,lJt=v(()=>{yKe();Fve=classFveextends$ve{constructor(){super(...arguments);x(this,"ctor");x(this,"symbol",Fve.symbol)}};x(Fve,"symbol",Symbol.for("@smithy/err"));uJt=Fve});functionh2(t){if(typeoft=="object")returnt;t=t|0;lete={},r=0;for(letnof["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])(t>>r++&1)===1&&(e[n]=1);returne}varbKe=v(()=>{});functionbne(t,e){if(tinstanceofna)returnObject.assign(t,{memberName:e,_isMemberSchema:!0});letr=na;returnnewr(t,e)}varok,na,_Ke,ePn,cJt=v(()=>{hKe();bKe();ok=classok{constructor(e,r){x(this,"ref");x(this,"memberName");x(this,"symbol",ok.symbol);x(this,"name");x(this,"schema");x(this,"_isMemberSchema");x(this,"traits");x(this,"memberTraits");x(this,"normalizedTraits");this.ref=e,this.memberName=r;letn=[],o=e,i=e;for(this._isMemberSchema=!1;_Ke(o);)n.push(o[1]),o=o[0],i=nk(o),this._isMemberSchema=!0;if(n.length>0){this.memberTraits={};for(leta=n.length-1;a>=0;--a){lets=n[a];Object.assign(this.memberTraits,h2(s))}}elsethis.memberTraits=0;if(iinstanceofok){leta=this.memberTraits;Object.assign(this,i),this.memberTraits=Object.assign({},a,i.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void0,this.memberName=r??i.memberName;return}if(this.schema=nk(i),ePn(this.schema)?(this.name=`${this.schema[1]}#${this.schema[2]}`,this.traits=this.schema[3]):(this.name=this.memberName??String(i),this.traits=0),this._isMemberSchema&&!r)thrownewError(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}static[Symbol.hasInstance](e){letr=this.prototype.isPrototypeOf(e);return!r&&typeofe=="object"
`),aPn={warn:console.warn}});function Uve(t){let e=t.getUTCFullYear(),r=t.getUTCMonth(),n=t.getUTCDay(),o=t.getUTCDate(),i=t.getUTCHours(),a=t.getUTCMinutes(),s=t.getUTCSeconds(),u=o<10?`0${o}`:`${o}`,l=i<10?`0${i}`:`${i}`,c=a<10?`0${a}`:`${a}`,d=s<10?`0${s}`:`${s}`;return`${sPn[n]},${u}${CKe[r]}${e}${l}:${c}:${d}GMT`}var sPn,CKe,uPn,CJt,lPn,xJt,cPn,dPn,fPn,TJt,OJt,_ne,pPn,mPn,hPn,SKe,gPn,yPn,bPn,XO,_Pn,vPn,tK,EJt=v(()=>{wKe();sPn=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],CKe=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];uPn=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),CJt=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=uPn.exec(t);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");let[r,n,o,i,a,s,u,l]=e,c=eK(tK(n)),d=XO(o,"month",1,12),f=XO(i,"day",1,31);return _ne(c,d,f,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l})},lPn=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),xJt=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=lPn.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=eK(tK(n)),f=XO(o,"month",1,12),p=XO(i,"day",1,31),m=_ne(d,f,p,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l});return c.toUpperCase()!="Z"&&m.setTime(m.getTime()-vPn(c)),m},cPn=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$/),dPn=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$/),fPn=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})$/),TJt=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-7231 date-times must be expressed as strings");let e=cPn.exec(t);if(e){let[r,n,o,i,a,s,u,l]=e;return _ne(eK(tK(i)),SKe(o),XO(n,"day",1,31),{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l})}if(e=dPn.exec(t),e){let[r,n,o,i,a,s,u,l]=e;return hPn(_ne(pPn(i),SKe(o),XO(n,"day",1,31),{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l}))}if(e=fPn.exec(t),e){let[r,n,o,i,a,s,u,l]=e;return _ne(eK(tK(l)),SKe(n),XO(o.trimLeft(),"day",1,31),{hours:i,minutes:a,seconds:s,fractionalMilliseconds:u})}throw new TypeError("Invalid RFC-7231 date-time value")},OJt=t=>{if(t==null)return;let e;if(typeof t=="number")e=t;else if(typeof t=="string")e=vJt(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))},_ne=(t,e,r,n)=>{let o=e-1;return yPn(t,o,r),new Date(Date.UTC(t,o,r,XO(n.hours,"hour",0,23),XO(n.minutes,"minute",0,59),XO(n.seconds,"seconds",0,60),_Pn(n.fractionalMilliseconds)))},pPn=t=>{let e=new Date().getUTCFullYear(),r=Math.floor(e/100)*100+eK(tK(t));return r<e?r+100:r},mPn=50*365*24*60*60*1e3,hPn=t=>t.getTime()-new Date().getTime()>mPn?new Date(Date.UTC(t.getUTCFullYear()-100,t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds(),t.getUTCMilliseconds())):t,SKe=t=>{let e=CKe.indexOf(t);if(e<0)throw new TypeError(`Invalidmonth:${t}`);return e+1},gPn=[31,28,31,30,31,30,31,31,30,31,30,31],yPn=(t,e,r)=>{let n=gPn[e];if(e===1&&bPn(t)&&(n=29),r>n)throw new TypeError(`Invaliddayfor${CKe[e]}in${t}:${r}`)},bPn=t=>t%4===0&&(t%100!==0||t%400===0),XO=(t,e,r,n)=>{let o=SJt(tK(t));if(o<r||o>n)throw new TypeError(`${e}mustbebetween${r}and${n},inclusive`);return o},_Pn=t=>t==null?0:wJt("0."+t)*1e3,vPn=t=>{let e=t[0],r=1;if(e=="+")r=1;else if(e=="-")r=-1;else throw new Typ
${s0(a)}`}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("/")?"/":""}`;return(0,G8t.escapeUri)(n).replace(/%2F/g,"/")}returne}validateResolvedCredentials(e){if(typeofe!="object"||typeofe.accessKeyId!="string"||typeofe.secretAccessKey!="string")thrownewError("Resolved credential object is not valid")}formatDate(e){letr=J8t(e).replace(/[\-:]/g,"");return{longDate:r,shortDate:r.slice(0,8)}}getCanonicalHeaderList(e){returnObject.keys(e).sort().join(";")}}});varPne,Z8t=v(()=>{lK();ck();dk();r8e();N8t();$8t();k8t();U8t();z8t();V8t();X8t();Pne=classextendspwe{constructor({applyChecksum:r,credentials:n,region:o,service:i,sha256:a,uriEscapePath:s=!0}){super({applyChecksum:r,credentials:n,region:o,service:i,sha256:a,uriEscapePath:s});x(this,"headerFormatter",newdwe)}asyncpresign(r,n={}){let{signingDate:o=newDate,expiresIn:i=3600,unsignableHeaders:a,unhoistableHeaders:s,signableHeaders:u,hoistableHeaders:l,signingRegion:c,signingService:d}=n,f=awaitthis.credentialProvider();this.validateResolvedCredentials(f);letp=c??awaitthis.regionProvider(),{longDate:m,shortDate:h}=this.formatDate(o);if(i>R8t)returnPromise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");lety=lwe(h,p,d??this.service),g=B8t(i8e(r),{unhoistableHeaders:s,hoistableHeaders:l});f.sessionToken&&(g.query[ZKe]=f.sessionToken),g.query[y8t]=swe,g.query[b8t]=`${f.accessKeyId}/${y}`,g.query[GKe]=m,g.query[v8t]=i.toString(10);letb=n8e(g,a,u);returng.query[_8t]=this.getCanonicalHeaderList(b),g.query[XKe]=awaitthis.getSignature(m,y,this.getSigningKey(f,p,h,d),this.createCanonicalRequest(g,b,awaitcwe(r,this.sha256))),g}asyncsign(r,n){returntypeofr=="string"?this.signString(r,n):r.headers&&r.payload?this.signEvent(r,n):r.message?this.signMessage(r,n):this.signRequest(r,n)}asyncsignEvent({headers:r,payload:n},{signingDate:o=newDate,priorSignature:i,signingRegion:a,signingService:s}){letu=a??awaitthis.regionProvider(),{shortDate:l,longDate:c}=this.formatDate(o),d=lwe(l,u,s??this.service),f=awaitcwe({headers:{},body:n},this.sha256),p=newthis.sha256;p.update(r);letm=s0(awaitp.digest()),h=[E8t,c,d,i,m,f].join(`
`);returnthis.signString(h,{signingDate:o,signingRegion:u,signingService:s})}asyncsignMessage(r,{signingDate:n=newDate,signingRegion:o,signingService:i}){returnthis.signEvent({headers:this.headerFormatter.format(r.message.headers),payload:r.message.body},{signingDate:n,signingRegion:o,signingService:i,priorSignature:r.priorSignature}).then(s=>({message:r.message,signature:s}))}asyncsignString(r,{signingDate:n=newDate,signingRegion:o,signingService:i}={}){leta=awaitthis.credentialProvider();this.validateResolvedCredentials(a);lets=o??awaitthis.regionProvider(),{shortDate:u}=this.formatDate(n),l=newthis.sha256(awaitthis.getSigningKey(a,s,u,i));returnl.update(q1(r)),s0(awaitl.digest())}asyncsignRequest(r,{signingDate:n=newDate,signableHeaders:o,unsignableHeaders:i,signingRegion:a,signingService:s}={}){letu=awaitthis.credentialProvider();this.validateResolvedCredentials(u);letl=a??awaitthis.regionProvider(),c=i8e(r),{longDate:d,shortDate:f}=this.formatDate(n),p=lwe(f,l,s??this.service);c.headers[QKe]=d,u.sessionToken&&(c.headers[C8t]=u.sessionToken);letm=awaitcwe(c,this.sha256);!q8t(Ene,c.headers)&&this.applyChecksum&&(c.headers[Ene]=m);leth=n8e(c,i,o),y=awaitthis.getSignature(d,p,this.getSigningKey(u,l,f,s),this.createCanonicalRequest(c,h,m));returnc.headers[YKe]=`${swe} Credential=${u.accessKeyId}/${p}, SignedHeaders=${this.getCanonicalHeaderList(h)}, Signature=${y}`,c}asyncgetSignature(r,n,o,i){leta=awaitthis.createStringToSign(r,n,i,swe),s=newthis.sha256(awaito);returns.update(q1(a)),s0(awaits.digest())}getSigningKey(r,n,o,i){returnA8t(this.sha256,r,o,n,i||this.service)}}});varY8t=v(()=>{});varQ8t=v(()=>{Z8t();dk();r8e();Y8t()});functionUPn(t,{credentials:e,credentialDefaultProvider:r}){letn;returne?e?.memoized?n=e:n=m5t(e,p5t,NKe):r?n=j1(r(Object.assign({},t,{parentClientConfig:t}))):n=async()=>{thrownewError("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")},n.memoized=!0,n}functionBPn(t,e){if(e.configBound)returne;letr=asyncn=>e({...n,callerClientConfig:t});returnr.memoized=e.memoized,r.configBound=!0,r}varmwe,eGt=v(()=>{nwe();ZO();Q8t();mwe=t=>{lete=t.credentials,r=!!t.credentials,n;Object.defineProperty(t,"credentials",{set(l){l&&l!==e&&l!==n&&(r=!0),e=l;letc=UPn(t,{credentials:e,credentialDefaultProvider:t.credentialDefaultProvider}),d=BPn(t,c);if(r&&!d.attributed){letf=typeofe=="object"&&e!==null;n=asyncp=>{leth=awaitd(p);returnf&&(!h.$source||Object.keys(h.$source).length===0)?uK(h,"CREDENTIALS_CODE","e"):h},n.memoized=d.memoized,n.configBound=d.configBound,n.attributed=!0}elsen=d},get(){returnn},enumerable:!0,configurable:!0}),t.credentials=e;let{signingEscapePath:o=!0,systemClockOffset:i=t.systemClockOffset||0,sha256:a}=t,s;returnt.signer?s=j1(t.signer):t.regionInfoProvider?s=()=>j1(t.region)().then(asyncl=>[awaitt.regionInfoProvider(l,{useFipsEndpoint:awaitt.useFipsEndpoint(),useDualstackEndpoint:awaitt.useDualstackEndpoint()})||{},l]).then(([l,c])=>{let{signingRegion:d,signingService:f}=l;t.signingRegion=t.signingRegion||d||c,t.signingName=t.signingName||f||t.serviceId;letp={...t,credentials:t.credentials,region:t.signingRegion,service:t.signingName,sha256:a,uriEscapePath:o},m=t.signerConstructor||Pne;returnnewm(p)}):s=asyncl=>{l=Object.assign({},{name:"sigv4",signingName:t.signingName||t.defaultSigningName,signingRegion:awaitj1(t.region)(),properties:{}},l);letc=l.signingRegion,d=l.signingName;t.signingRegion=t.signingRegion||c,t.signingName=t.signingName||d||t.serviceId;letf={...t,credentials:t.credentials,region:t.signingRegion,service:t.signingName,sha256:a,uriEscapePath:o},p=t.signerConstructor||Pne;returnnewp(f)},Object.assign(t,{systemClockOffset:i,signingEscapePath:o,signer:s})}});vartGt=v(()=>{l8t();d8t();f8t();eGt()});varrGt=v(()=>{tGt();c8t()});varnGt,hwe,oGt=v(()=>{nGt=typeofTextEncoder=="function"?newTextEncoder:null,hwe=t=>{if(typeoft=="string"){if(nGt)returnnGt.encode(t).byteLength;lete=t.length;for(letr=e-1;r>=0;r--){letn=t.charCodeAt(r);n>127&
${bk.toHex(a)}`}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("/")?"/":""}`;returnc0e.escapeUri(n).replace(/%2F/g,"/")}returne}validateResolvedCredentials(e){if(typeofe!="object"||typeofe.accessKeyId!="string"||typeofe.secretAccessKey!="string")thrownewError("Resolved credential object is not valid")}formatDate(e){letr=E1n(e).replace(/[\-:]/g,"");return{longDate:r,shortDate:r.slice(0,8)}}getCanonicalHeaderList(e){returnObject.keys(e).sort().join(";")}},r9e=classextendsg0e{constructor({applyChecksum:r,credentials:n,region:o,service:i,sha256:a,uriEscapePath:s=!0}){super({applyChecksum:r,credentials:n,region:o,service:i,sha256:a,uriEscapePath:s});x(this,"headerFormatter",newQGe)}asyncpresign(r,n={}){let{signingDate:o=newDate,expiresIn:i=3600,unsignableHeaders:a,unhoistableHeaders:s,signableHeaders:u,hoistableHeaders:l,signingRegion:c,signingService:d}=n,f=awaitthis.credentialProvider();this.validateResolvedCredentials(f);letp=c??awaitthis.regionProvider(),{longDate:m,shortDate:h}=this.formatDate(o);if(i>Xer)returnPromise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");lety=p0e(h,p,d??this.service),g=Qer(t9e(r),{unhoistableHeaders:s,hoistableHeaders:l});f.sessionToken&&(g.query[i9e]=f.sessionToken),g.query[$er]=d0e,g.query[Ler]=`${f.accessKeyId}/${y}`,g.query[n9e]=m,g.query[ker]=i.toString(10);letb=YGe(g,a,u);returng.query[Fer]=this.getCanonicalHeaderList(b),g.query[o9e]=awaitthis.getSignature(m,y,this.getSigningKey(f,p,h,d),this.createCanonicalRequest(g,b,awaitm0e(r,this.sha256))),g}asyncsign(r,n){returntypeofr=="string"?this.signString(r,n):r.headers&&r.payload?this.signEvent(r,n):r.message?this.signMessage(r,n):this.signRequest(r,n)}asyncsignEvent({headers:r,payload:n},{signingDate:o=newDate,priorSignature:i,signingRegion:a,signingService:s}){letu=a??awaitthis.regionProvider(),{shortDate:l,longDate:c}=this.formatDate(o),d=p0e(l,u,s??this.service),f=awaitm0e({headers:{},body:n},this.sha256),p=newthis.sha256;p.update(r);letm=bk.toHex(awaitp.digest()),h=[Jer,c,d,i,m,f].join(`
`;super(r),this.name="AggregateError",this.errors=e}};d9e.exports={AggregateError:c9e,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 B1n},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:z1n,deprecate(t,e){return t},addAbortListener:Wne().addAbortListener||function(e,r){if(e===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);htr(e,"signal"),V1n(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[F1n]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[k1n](){var o;(o=n)===null||o===void 0||o()}}},AbortSignalAny:q1n.any||function(e){if(e.length===1)return e[0];let r=new U1n,n=()=>r.abort();return e.forEach(o=>{htr(o,"signals"),o.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{e.forEach(o=>o.removeEventListener("abort",n))},{once:!0}),r.signal}};d9e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var Qb=S((Nva,btr)=>{"usestrict";var{format:H1n,inspect:v0e,AggregateError:W1n}=Xy(),J1n=globalThis.AggregateError||W1n,K1n=Symbol("kIsNodeError"),G1n=["string","function","number","object","Function","Object","boolean","bigint","symbol"],X1n=/^([A-Z][a-z0-9]*)+$/,Z1n="__node_internal_",w0e={};function R2(t,e){if(!t)throw new w0e.ERR_INTERNAL_ASSERTION(e)}function gtr(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 Y1n(t,e,r){if(typeof e=="function")return R2(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 R2(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:H1n(e,...r)}function Bg(t,e,r){r||(r=Error);class n extends r{constructor(...i){super(Y1n(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[K1n]=!0,w0e[t]=n}function ytr(t){let e=Z1n+t.name;return Object.defineProperty(t,"name",{value:e}),t}function Q1n(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new J1n([e,t],e.message);return r.code=e.code,r}return t||e}var f9e=class extends Error{constructor(e="Theoperationwasaborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new w0e.ERR_INVALID_ARG_TYPE("options","Object",r);super(e,r),this.code="ABORT_ERR",this.name="AbortError"}};Bg("ERR_ASSERTION","%s",Error);Bg("ERR_INVALID_ARG_TYPE",(t,e,r)=>{R2(typeof t=="string","'name'mustbeastring"),Array.isArray(e)||(e=[e]);let n="The";t.endsWith("argument")?n+=`${t} `:n+=`"${t}" ${t.includes(".")?"property":"argument"} `,n+="mustbe";let o=[],i=[],a=[];for(let u of e)R2(typeof u=="string","Allexpectedentrieshavetobeoftypestring"),G1n.includes(u)?o.push(u.toLowerCase()):X1n.test(u)?i.push(u):(R2(u!=="object",'The value "object" should be written as "Object"'),a.push(u));if(i.length>
`),pE(this,xoe,void0),pE(this,xCe,void0),pE(this,Toe,"-".repeat(2)),pE(this,K2,newTextEncoder),pE(this,Ooe,void0),pE(this,Eoe,void0),pE(this,TCe,void0),!ysr(t))thrownewTypeError("Expected first argument to be a FormData instance.");letn;if(dsr(e)?r=e:n=e,n||(n=XBn()),typeofn!="string")thrownewTypeError("Expected boundary argument to be a string.");if(r&&!dsr(r))thrownewTypeError("Expected options argument to be an object.");Coe(this,Eoe,Array.from(t.entries())),Coe(this,TCe,{...QBn,...r}),Coe(this,xoe,Uc(this,K2).encode(Uc(this,Ek))),Coe(this,xCe,Uc(this,xoe).byteLength),this.boundary=`form-data-boundary-${n}`,this.contentType=`multipart/form-data; boundary=${this.boundary}`,Coe(this,Ooe,Uc(this,K2).encode(`${Uc(this,Toe)}${this.boundary}${Uc(this,Toe)}${Uc(this,Ek).repeat(2)}`));leto={"Content-Type":this.contentType},i=hXe(this,gXe,bsr).call(this);i&&(this.contentLength=i,o["Content-Length"]=i),this.headers=YBn(Object.freeze(o)),Object.defineProperties(this,{boundary:CCe,contentType:CCe,contentLength:CCe,headers:CCe})}*values(){for(let[t,e]ofUc(this,Eoe)){letr=G2(e)?e:Uc(this,K2).encode(gsr(e));yieldhXe(this,OCe,_Xe).call(this,t,r),yieldr,yieldUc(this,xoe)}yieldUc(this,Ooe)}async*encode(){for(lettofthis.values())G2(t)?yield*GBn(t.stream()):yield*hsr(t)}[Symbol.iterator](){returnthis.values()}[Symbol.asyncIterator](){returnthis.encode()}};Ek=newWeakMap;xoe=newWeakMap;xCe=newWeakMap;Toe=newWeakMap;K2=newWeakMap;Ooe=newWeakMap;Eoe=newWeakMap;TCe=newWeakMap;OCe=newWeakSet;_Xe=function(t,e){letr="";if(r+=`${Uc(this,Toe)}${this.boundary}${Uc(this,Ek)}`,r+=`Content-Disposition: form-data; name="${psr(t)}"`,G2(e)&&(r+=`; filename="${psr(e.name)}"${Uc(this,Ek)}`,r+=`Content-Type: ${e.type||"application/octet-stream"}`),Uc(this,TCe).enableAdditionalHeaders===!0){letn=G2(e)?e.size:e.byteLength;n!=null&&!isNaN(n)&&(r+=`${Uc(this,Ek)}Content-Length: ${n}`)}returnUc(this,K2).encode(`${r}${Uc(this,Ek).repeat(2)}`)};gXe=newWeakSet;bsr=function(){lett=0;for(let[e,r]ofUc(this,Eoe)){letn=G2(r)?r:Uc(this,K2).encode(gsr(r)),o=G2(n)?n.size:n.byteLength;if(o==null||isNaN(o))return;t+=hXe(this,OCe,_Xe).call(this,e,n).byteLength,t+=o,t+=Uc(this,xCe)}returnString(t+Uc(this,Ooe).byteLength)}});varSsr=S((OSa,wsr)=>{"use strict";wsr.exports=typeofself=="object"?self.FormData:window.FormData});varCsr=S(zg=>{"use strict";vartzn=zg&&zg.__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]}),rzn=zg&&zg.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o8=zg&&zg.__importStar||function(){vart=function(e){returnt=Object.getOwnPropertyNames||function(r){varn=[];for(varoinr)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);returnn},t(e)};returnfunction(e){if(e&&e.__esModule)returne;varr={};if(e!=null)for(varn=t(e),o=0;o<n.length;o++)n[o]!=="default"&&tzn(r,e,n[o]);returnrzn(r,e),r}}(),Pk=zg&&zg.__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(zg,"__esModule",{value:!0});zg.WebFormData=zg.Node16FormData=zg.Node18FormData=void0;zg.newFormData=nzn;varECe=GK();functionvXe(t){returntypeoft=="object"&&t!=null&&"name"int}functionnzn(){returnPk(this,void0,void0,function*(){lett;returnECe.RUNTIME.type==="node"&&ECe.RUNTIME.parsedVersion!=null&&ECe.RUNTIME.parsedVersion>=18?t=newPCe:ECe.RUNTIME.type==="node"?t=newMCe:t=newRCe,yieldt.setup(),t})}varPCe=class{setup(){returnPk(this,void0,void0,function*(){this.fd=new(yieldPromise.resolve().then(()=>o8(ssr()))).FormData})}append(e
`);o.enqueue(s)}catch(i){o.error(i)}})},cancel(){returnjoe(this,void0,void0,function*(){varo;yield(o=r.return)===null||o===void0?void0:o.call(r)})}})}};Hg.StreamUtils=lZe;functionEur(t,e){returnLoe(this,arguments,function*(){varn,o,i,a;if(!t.body)throwe?.abort(),newl8.CohereError({message:"Attempted to iterate over a response with no body"});lets=newcZe,u=newMk,l=dZe(t.body);try{for(varc=!0,d=$oe(O2n(l)),f;f=yieldJl(d.next()),n=f.done,!n;c=!0){a=f.value,c=!1;letp=a;for(letmofu.decode(p)){leth=s.decode(m);h&&(yieldyieldJl(h))}}}catch(p){o={error:p}}finally{try{!c&&!n&&(i=d.return)&&(yieldJl(i.call(d)))}finally{if(o)throwo.error}}for(letpofu.flush()){letm=s.decode(p);m&&(yieldyieldJl(m))}})}functionO2n(t){returnLoe(this,arguments,function*(){varr,n,o,i;leta=newUint8Array;try{for(vars=!0,u=$oe(t),l;l=yieldJl(u.next()),r=l.done,!r;s=!0){i=l.value,s=!1;letc=i;if(c==null)continue;letd=cinstanceofArrayBuffer?newUint8Array(c):typeofc=="string"?newTextEncoder().encode(c):c,f=newUint8Array(a.length+d.length);f.set(a),f.set(d,a.length),a=f;letp;for(;(p=E2n(a))!==-1;)yieldyieldJl(a.slice(0,p)),a=a.slice(p)}}catch(c){n={error:c}}finally{try{!s&&!r&&(o=u.return)&&(yieldJl(o.call(u)))}finally{if(n)thrown.error}}a.length>0&&(yieldyieldJl(a))})}functionE2n(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}varcZe=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]=M2n(e,":");returno.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},Mk=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();thrownewl8.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);thrownewl8.CohereError({message:`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`})}thrownewl8.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}};Hg.LineDecoder=Mk;Mk.NEWLINE_CHARS=newSet([`
`)}}}}catch(P){s={error:P}}finally{try{!b&&!a&&(u=_.return)&&(yield u.call(_))}finally{if(s)throw s.error}}for(let P of O.flush()){let R=(0,uu.parseAWSEvent)(P);if(R){let I=yield(0,uu.mapResponseFromBedrock)(m,d,f,R);E.push(JSON.stringify(I)+`
`)}}return E.end(),{ok:!0,body:E,rawResponse:g.rawResponse}}else{let T=yield g.body;return{ok:!0,body:yield(0,uu.mapResponseFromBedrock)(m,d,f,T),rawResponse:g.rawResponse}}}catch(T){throw T}});uu.fetchOverride=dio});var lD=S(Lxe=>{"use strict";Object.defineProperty(Lxe,"__esModule",{value:!0});Lxe.CohereEnvironment=void 0;Lxe.CohereEnvironment={Production:"https://api.cohere.com"}});var kk=S((Jcr,Fxe)=>{(function(t,e,r){typeof Fxe<"u"&&Fxe.exports?Fxe.exports=r():typeof define=="function"&&define.amd?define(r):e[t]=r()})("urljoin",Jcr,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 Get=S(tv=>{"use strict";var fio=tv&&tv.__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]}),pio=tv&&tv.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),cie=tv&&tv.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&fio(r,e,n[o]);return pio(r,e),r}}(),I8=tv&&tv.__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())})},mio=tv&&tv.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(tv,"__esModule",{value:!0});tv.V2=void 0;var kxe=cie(lD()),oa=cie(se()),Vn=cie(D1()),qk=cie(uD()),qxe=mio(kk()),Jg=cie(kc()),Ket=class{constructor(e={}){this._options=e}chatStream(e,r){return oa.HttpResponsePromise.fromPromise(this.__chatStream(e,r))}__chatStream(e,r){return I8(this,void 0,void 0,function*(){var n,o,i;let a=yield((n=this._options.fetcher)!==null&&n!==void 0?n:oa.fetcher)({url:(0,qxe.default)((i=(o=yield oa.Supplier.get(this._options.baseUrl))!==null&&o!==void 0?o:yield oa.Supplier.get(this._options.environment))!==null&&i!==void 0?i:kxe.CohereEnvironment.Production,"v2/chat"),method:"POST",headers:Object.assign({Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield oa.Supplier.get(this._options.clientName))!=null?yield oa.Supplier.get(this._options.clientName):void 0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.19.0","User-Agent":"cohere-ai/7.19.0","X-Fern-Runtime":oa.RUNTIME.type,"X-Fern-Runtime-Version":oa.RUNTIME.version},r?.headers),contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},qk.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(a.ok)return{data:new oa.Stream({stream:a.body,parse:s=>I8(this,void 0,void
`}}),rawResponse:u.rawResponse};if(u.error.reason==="status-code")switch(u.error.statusCode){case400:thrownewNe.BadRequestError(u.error.body,u.rawResponse);case401:thrownewNe.UnauthorizedError(u.error.body,u.rawResponse);case403:thrownewNe.ForbiddenError(u.error.body,u.rawResponse);case404:thrownewNe.NotFoundError(u.error.body,u.rawResponse);case422:thrownewNe.UnprocessableEntityError(u.error.body,u.rawResponse);case429:thrownewNe.TooManyRequestsError(u.error.body,u.rawResponse);case498:thrownewNe.InvalidTokenError(u.error.body,u.rawResponse);case499:thrownewNe.ClientClosedRequestError(u.error.body,u.rawResponse);case500:thrownewNe.InternalServerError(u.error.body,u.rawResponse);case501:thrownewNe.NotImplementedError(u.error.body,u.rawResponse);case503:thrownewNe.ServiceUnavailableError(u.error.body,u.rawResponse);case504:thrownewNe.GatewayTimeoutError(u.error.body,u.rawResponse);default:thrownewDo.CohereError({statusCode:u.error.statusCode,body:u.error.body,rawResponse:u.rawResponse})}switch(u.error.reason){case"non-json":thrownewDo.CohereError({statusCode:u.error.statusCode,body:u.error.rawBody,rawResponse:u.rawResponse});case"timeout":thrownewDo.CohereTimeoutError("Timeout exceeded when calling POST /v1/chat.");case"unknown":thrownewDo.CohereError({message:u.error.errorMessage,rawResponse:u.rawResponse})}})}chat(e,r){returnft.HttpResponsePromise.fromPromise(this.__chat(e,r))}__chat(e,r){returnsv(this,void0,void0,function*(){varn,o,i;let{accepts:a}=e,s=tdr(e,["accepts"]),u=yield((n=this._options.fetcher)!==null&&n!==void0?n:ft.fetcher)({url:(0,Px.default)((i=(o=yieldft.Supplier.get(this._options.baseUrl))!==null&&o!==void0?o:yieldft.Supplier.get(this._options.environment))!==null&&i!==void0?i:Ex.CohereEnvironment.Production,"v1/chat"),method:"POST",headers:Object.assign({Authorization:yieldthis._getAuthorizationHeader(),"X-Client-Name":(yieldft.Supplier.get(this._options.clientName))!=null?yieldft.Supplier.get(this._options.clientName):void0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.19.0","User-Agent":"cohere-ai/7.19.0","X-Fern-Runtime":ft.RUNTIME.type,"X-Fern-Runtime-Version":ft.RUNTIME.version,Accepts:a??void0},r?.headers),contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},pd.ChatRequest.jsonOrThrow(s,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0})),{stream:!1}),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:3e5,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(u.ok)return{data:pd.NonStreamedChatResponse.parseOrThrow(u.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}),rawResponse:u.rawResponse};if(u.error.reason==="status-code")switch(u.error.statusCode){case400:thrownewNe.BadRequestError(u.error.body,u.rawResponse);case401:thrownewNe.UnauthorizedError(u.error.body,u.rawResponse);case403:thrownewNe.ForbiddenError(u.error.body,u.rawResponse);case404:thrownewNe.NotFoundError(u.error.body,u.rawResponse);case422:thrownewNe.UnprocessableEntityError(u.error.body,u.rawResponse);case429:thrownewNe.TooManyRequestsError(u.error.body,u.rawResponse);case498:thrownewNe.InvalidTokenError(u.error.body,u.rawResponse);case499:thrownewNe.ClientClosedRequestError(u.error.body,u.rawResponse);case500:thrownewNe.InternalServerError(u.error.body,u.rawResponse);case501:thrownewNe.NotImplementedError(u.error.body,u.rawResponse);case503:thrownewNe.ServiceUnavailableError(u.error.body,u.rawResponse);case504:thrownewNe.GatewayTimeoutError(u.error.body,u.rawResponse);default:thrownewDo.CohereError({statusCode:u.error.statusCode,body:u.error.body,rawResponse:u.rawResponse})}switch(u.error.reason){case"non-json":thrownewDo.CohereError({statusCode:u.error.statusCode,body:u.error.rawBody,rawResponse:u.rawResponse});case"timeout":thrownewDo.CohereTimeoutError("Timeout exceeded when calling POST
`}}),rawResponse:a.rawResponse};if(a.error.reason==="status-code")switch(a.error.statusCode){case 400:throw new Ne.BadRequestError(a.error.body,a.rawResponse);case 401:throw new Ne.UnauthorizedError(a.error.body,a.rawResponse);case 403:throw new Ne.ForbiddenError(a.error.body,a.rawResponse);case 404:throw new Ne.NotFoundError(a.error.body,a.rawResponse);case 422:throw new Ne.UnprocessableEntityError(a.error.body,a.rawResponse);case 429:throw new Ne.TooManyRequestsError(a.error.body,a.rawResponse);case 498:throw new Ne.InvalidTokenError(a.error.body,a.rawResponse);case 499:throw new Ne.ClientClosedRequestError(a.error.body,a.rawResponse);case 500:throw new Ne.InternalServerError(a.error.body,a.rawResponse);case 501:throw new Ne.NotImplementedError(a.error.body,a.rawResponse);case 503:throw new Ne.ServiceUnavailableError(a.error.body,a.rawResponse);case 504:throw new Ne.GatewayTimeoutError(a.error.body,a.rawResponse);default:throw new Do.CohereError({statusCode:a.error.statusCode,body:a.error.body,rawResponse:a.rawResponse})}switch(a.error.reason){case"non-json":throw new Do.CohereError({statusCode:a.error.statusCode,body:a.error.rawBody,rawResponse:a.rawResponse});case"timeout":throw new Do.CohereTimeoutError("TimeoutexceededwhencallingPOST/v1/generate.");case"unknown":throw new Do.CohereError({message:a.error.errorMessage,rawResponse:a.rawResponse})}})}generate(e,r){return ft.HttpResponsePromise.fromPromise(this.__generate(e,r))}__generate(e,r){return sv(this,void 0,void 0,function*(){var n,o,i;let a=yield((n=this._options.fetcher)!==null&&n!==void 0?n:ft.fetcher)({url:(0,Px.default)((i=(o=yield ft.Supplier.get(this._options.baseUrl))!==null&&o!==void 0?o:yield ft.Supplier.get(this._options.environment))!==null&&i!==void 0?i:Ex.CohereEnvironment.Production,"v1/generate"),method:"POST",headers:Object.assign({Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield ft.Supplier.get(this._options.clientName))!=null?yield ft.Supplier.get(this._options.clientName):void 0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.19.0","User-Agent":"cohere-ai/7.19.0","X-Fern-Runtime":ft.RUNTIME.type,"X-Fern-Runtime-Version":ft.RUNTIME.version},r?.headers),contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},pd.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(a.ok)return{data:pd.Generation.parseOrThrow(a.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}),rawResponse:a.rawResponse};if(a.error.reason==="status-code")switch(a.error.statusCode){case 400:throw new Ne.BadRequestError(a.error.body,a.rawResponse);case 401:throw new Ne.UnauthorizedError(a.error.body,a.rawResponse);case 403:throw new Ne.ForbiddenError(a.error.body,a.rawResponse);case 404:throw new Ne.NotFoundError(a.error.body,a.rawResponse);case 422:throw new Ne.UnprocessableEntityError(a.error.body,a.rawResponse);case 429:throw new Ne.TooManyRequestsError(a.error.body,a.rawResponse);case 498:throw new Ne.InvalidTokenError(a.error.body,a.rawResponse);case 499:throw new Ne.ClientClosedRequestError(a.error.body,a.rawResponse);case 500:throw new Ne.InternalServerError(a.error.body,a.rawResponse);case 501:throw new Ne.NotImplementedError(a.error.body,a.rawResponse);case 503:throw new Ne.ServiceUnavailableError(a.error.body,a.rawResponse);case 504:throw new Ne.GatewayTimeoutError(a.error.body,a.rawResponse);default:throw new Do.CohereError({statusCode:a.error.statusCode,body:a.error.body,rawResponse:a.rawResponse})}switch(a.error.reason){case"non-json":throw new Do.CohereError({statusCode:a.error.statusCode,body:a.error.rawBody,rawResponse:a.rawResponse});case"timeout":throw new Do.CohereTimeoutError("TimeoutexceededwhencallingPOST/v1/generate.");case"unknown":throw new
`).filter(Boolean).reduce((n,o)=>{let[i,a,...s]=o.split(""),u=Number.parseInt(a,10);return s.forEach((l,c)=>n[l]=u+c),n},{});for(let[n,o]of Object.entries(r)){let i=_dr.default.toByteArray(n);this.rankMap.set(i.join(","),o),this.textMap.set(o,i)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[o,i])=>(n[i]=this.textEncoder.encode(o),n),{})}encode(t,e=[],r="all"){let n=new RegExp(this.patStr,"ug"),o=gtt.specialTokenRegex(Object.keys(this.specialTokens)),i=[],a=new Set(e==="all"?Object.keys(this.specialTokens):e),s=new Set(r==="all"?Object.keys(this.specialTokens).filter(l=>!a.has(l)):r);if(s.size>0){let l=gtt.specialTokenRegex([...s]),c=t.match(l);if(c!=null)throw new Error(`The text contains a special token that is not allowed: ${c[0]}`)}let u=0;for(;;){let l=null,c=u;for(;o.lastIndex=c,l=o.exec(t),!(l==null||a.has(l[0]));)c=l.index+1;let d=l?.index??t.length;for(let p of t.substring(u,d).matchAll(n)){let m=this.textEncoder.encode(p[0]),h=this.rankMap.get(m.join(","));if(h!=null){i.push(h);continue}i.push(...aao(m,this.rankMap))}if(l==null)break;let f=this.specialTokens[l[0]];i.push(f),u=l.index+l[0].length}return i}decode(t){let e=[],r=0;for(let i=0;i<t.length;++i){let a=t[i],s=this.textMap.get(a)??this.inverseSpecialTokens[a];s!=null&&(e.push(s),r+=s.length)}let n=new Uint8Array(r),o=0;for(let i of e)n.set(i,o),o+=i.length;return this.textDecoder.decode(n)}},Gxe=gtt;oao(Gxe,"specialTokenRegex",t=>new RegExp(t.map(e=>sao(e)).join("|"),"g"))});var wdr=v(()=>{vdr()});async function btt(t){return t in Xxe||(Xxe[t]=lao.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>new Gxe(e)).catch(e=>{throw delete Xxe[t],e})),await Xxe[t]}async function Zxe(t){return btt(ytt(t))}var uao,Xxe,lao,_tt=v(()=>{Jo();Jz();wdr();uao={};$t(uao,{encodingForModel:()=>Zxe,getEncoding:()=>btt});Xxe={},lao=new ES({})});function Aw(t){return typeof t!="object"||!t?!1:!!("type"in t&&t.type==="function"&&"function"in t&&typeof t.function=="object"&&t.function&&"name"in t.function&&"parameters"in t.function)}var cao,Yxe,dao,Sdr,Cdr,fao,k8,bV,Nw=v(()=>{Jo();UC();Jz();Pg();lte();bdr();_tt();cao={};$t(cao,{BaseLangChain:()=>k8,BaseLanguageModel:()=>bV,calculateMaxTokens:()=>Cdr,getEmbeddingContextSize:()=>dao,getModelContextSize:()=>Sdr,getModelNameForTiktoken:()=>Yxe,isOpenAITool:()=>Aw});Yxe=t=>t.startsWith("gpt-5")?"gpt-5":t.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":t.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":t.startsWith("gpt-4-32k")?"gpt-4-32k":t.startsWith("gpt-4-")?"gpt-4":t.startsWith("gpt-4o")?"gpt-4o":t,dao=t=>{switch(t){case"text-embedding-ada-002":return 8191;default:return 2046}},Sdr=t=>{switch(Yxe(t)){case"gpt-5":case"gpt-5-turbo":case"gpt-5-turbo-preview":return 4e5;case"gpt-4o":case"gpt-4o-mini":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":return 128e3;case"gpt-4-turbo":case"gpt-4-turbo-preview":case"gpt-4-turbo-2024-04-09":case"gpt-4-0125-preview":case"gpt-4-1106-preview":return 128e3;case"gpt-4-32k":case"gpt-4-32k-0314":case"gpt-4-32k-0613":return 32768;case"gpt-4":case"gpt-4-0314":case"gpt-4-0613":return 8192;case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-16k-0613":return 16384;case"gpt-3.5-turbo":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-1106":case"gpt-3.5-turbo-0125":return 4096;case"text-davinci-003":case"text-davinci-002":return 4097;case"text-davinci-001":return 2049;case"text-curie-001":case"text-babbage-001":case"text-ada-001":return 2048;case"code-davinci-002":case"code-davinci-001":return 8e3;case"code-cushman-001":return 2048;case"claude-3-5-sonnet-20241022":case"claude-3-5-sonnet-20240620":case"claude-3-opus-20240229":case"claude-3-sonnet-20240229":case"claude-3-haiku-20240307":case"claude-2.1":return 2e5;case"claude-2.0":case"claude-instant-1.2":return 1e5;case"gemini-1.5-pro":case"gemini-1.5-pro-latest":case"gemini-1.5-flash":case"gemini-1.5-flash-latest":return 1e6;case"gemini-pro":case"gemini-pro-vision":return 32768;default:return 4097}};Cdr=async({prompt:t,modelName:e})=>{let r;try{r=(awa
`+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&i.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function ufr(t){var e,r,n,o;let i=[];if(!((r=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||r===void 0)&&r.parts)for(let a of(o=(n=t.candidates)===null||n===void 0?void 0:n[0].content)===null||o===void 0?void 0:o.parts)a.functionCall&&i.push(a.functionCall);if(i.length>0)return i}function aTe(t){return!!t.finishReason&&Xao.includes(t.finishReason)}function Hk(t){var e,r,n;let o="";if((!t.candidates||t.candidates.length===0)&&t.promptFeedback)o+="Response was blocked",!((e=t.promptFeedback)===null||e===void 0)&&e.blockReason&&(o+=`dueto${t.promptFeedback.blockReason}`),!((r=t.promptFeedback)===null||r===void 0)&&r.blockReasonMessage&&(o+=`:${t.promptFeedback.blockReasonMessage}`);else if(!((n=t.candidates)===null||n===void 0)&&n[0]){let i=t.candidates[0];aTe(i)&&(o+=`Candidatewasblockeddueto${i.finishReason}`,i.finishMessage&&(o+=`:${i.finishMessage}`))}return o}function Pie(t){return this instanceof Pie?(this.v=t,this):new Pie(t)}function Zao(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),o,i=[];return o={},a("next"),a("throw"),a("return"),o[Symbol.asyncIterator]=function(){return this},o;function a(f){n[f]&&(o[f]=function(p){return new Promise(function(m,h){i.push([f,p,m,h])>1||s(f,p)})})}function s(f,p){try{u(n[f](p))}catch(m){d(i[0][3],m)}}function u(f){f.value instanceof Pie?Promise.resolve(f.value.v).then(l,c):d(i[0][2],f)}function l(f){s("next",f)}function c(f){s("throw",f)}function d(f,p){f(p),i.shift(),i.length&&s(i[0][0],i[0][1])}}function Yao(t){let e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),r=tso(e),[n,o]=r.tee();return{stream:eso(n),response:Qao(o)}}async function Qao(t){let e=[],r=t.getReader();for(;;){let{done:n,value:o}=await r.read();if(n)return Ftt(rso(e));e.push(o)}}function eso(t){return Zao(this,arguments,function*(){let r=t.getReader();for(;;){let{value:n,done:o}=yield Pie(r.read());if(o)break;yield yield Pie(Ftt(n))}})}function tso(t){let e=t.getReader();return new ReadableStream({start(n){let o="";return i();function i(){return e.read().then(({value:a,done:s})=>{if(s){if(o.trim()){n.error(new Hh("Failed to parse stream"));return}n.close();return}o+=a;let u=o.match(lfr),l;for(;u;){try{l=JSON.parse(u[1])}catch{n.error(new Hh(`ErrorparsingJSONresponse:"${u[1]}"`));return}n.enqueue(l),o=o.substring(u[0].length),u=o.match(lfr)}return i()}).catch(a=>{let s=a;throw s.stack=a.stack,s.name==="AbortError"?s=new uTe("Request aborted when reading from the stream"):s=new Hh("Error reading from the stream"),s})}}})}function rso(t){let e=t[t.length-1],r={promptFeedback:e?.promptFeedback};for(let n of t){if(n.candidates){let o=0;for(let i of n.candidates)if(r.candidates||(r.candidates=[]),r.candidates[o]||(r.candidates[o]={index:o}),r.candidates[o].citationMetadata=i.citationMetadata,r.candidates[o].groundingMetadata=i.groundingMetadata,r.candidates[o].finishReason=i.finishReason,r.candidates[o].finishMessage=i.finishMessage,r.candidates[o].safetyRatings=i.safetyRatings,i.content&&i.content.parts){r.candidates[o].content||(r.candidates[o].content={role:i.content.role||"user",parts:[]});let a={};for(let s of i.content.parts)s.text&&(a.text=s.text),s.functionCall&&(a.functionCall=s.functionCall),s.executableCode&&(a.executableCode=s.executableCode),s.codeExecutionResult&&(a.codeExecutionResult=s.codeExecutionResult),Object.keys(a).length===0&&(a.text=""),r.candidates[o].content.parts.push(a)}o++}n.usageMetadata&&(r.usageMetadata=n.usageMetadata)}return r}async function mfr(t,e,r,n){let o=await Rie(e,xV.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(r),n);return Yao(o)}async function hfr(t,e,r,n){let i=await(await Rie(e,xV.GENERATE_CONTENT,t,!1,JSON.stringify(r),n)).json();return{response:Ftt(i)}}function gfr(t){if(t!=null){if(typeof t=="string")return{role:"system",parts:[{text:t}]};if(t.text)return{role:"system",parts:[t]};if(t.parts)return t.role?t:{role
`)===0?n.substr(1,n.length):n}).forEach(function(n){varo=n.split(":"),i=o.shift().trim();if(i){vara=o.join(":").trim();try{e.append(i,a)}catch(s){console.warn("Response "+s.message)}}}),e}functioneA(t,e){if(!(thisinstanceofeA))thrownewTypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(e||(e={}),this.type="default",this.status=e.status===void0?200:e.status,this.status<200||this.status>599)thrownewRangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=e.statusText===void0?"":""+e.statusText,this.headers=newzm(e.headers),this.url=e.url||"",this._initBody(t)}functionLfr(t,e){returnnewPromise(function(r,n){varo=newEV(t,e);if(o.signal&&o.signal.aborted)returnn(newOV("Aborted","AbortError"));vari=newXMLHttpRequest;functiona(){i.abort()}i.onload=function(){varl={statusText:i.statusText,headers:Mso(i.getAllResponseHeaders()||"")};o.url.indexOf("file://")===0&&(i.status<200||i.status>599)?l.status=200:l.status=i.status,l.url="responseURL"ini?i.responseURL:l.headers.get("X-Request-URL");varc="response"ini?i.response:i.responseText;setTimeout(function(){r(neweA(c,l))},0)},i.onerror=function(){setTimeout(function(){n(newTypeError("Network request failed"))},0)},i.ontimeout=function(){setTimeout(function(){n(newTypeError("Network request timed out"))},0)},i.onabort=function(){setTimeout(function(){n(newOV("Aborted","AbortError"))},0)};functions(l){try{returnl===""&&ey.location.href?ey.location.href:l}catch{returnl}}if(i.open(o.method,s(o.url),!0),o.credentials==="include"?i.withCredentials=!0:o.credentials==="omit"&&(i.withCredentials=!1),"responseType"ini&&(r_.blob?i.responseType="blob":r_.arrayBuffer&&(i.responseType="arraybuffer")),e&&typeofe.headers=="object"&&!(e.headersinstanceofzm||ey.Headers&&e.headersinstanceofey.Headers)){varu=[];Object.getOwnPropertyNames(e.headers).forEach(function(l){u.push(q8(l)),i.setRequestHeader(l,Jtt(e.headers[l]))}),o.headers.forEach(function(l,c){u.indexOf(c)===-1&&i.setRequestHeader(c,l)})}elseo.headers.forEach(function(l,c){i.setRequestHeader(c,l)});o.signal&&(o.signal.addEventListener("abort",a),i.onreadystatechange=function(){i.readyState===4&&o.signal.removeEventListener("abort",a)}),i.send(typeofo._bodyInit>"u"?null:o._bodyInit)})}varey,r_,Afr,Dfr,Oso,Rso,OV,Ffr=v(()=>{ey=typeofglobalThis<"u"&&globalThis||typeofself<"u"&&self||typeofwindow<"u"&&window||{},r_={searchParams:"URLSearchParams"iney,iterable:"Symbol"iney&&"iterator"inSymbol,blob:"FileReader"iney&&"Blob"iney&&function(){try{returnnewBlob,!0}catch{return!1}}(),formData:"FormData"iney,arrayBuffer:"ArrayBuffer"iney};r_.arrayBuffer&&(Afr=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],Dfr=ArrayBuffer.isView||function(t){returnt&&Afr.indexOf(Object.prototype.toString.call(t))>-1});zm.prototype.append=function(t,e){t=q8(t),e=Jtt(e);varr=this.map[t];this.map[t]=r?r+", "+e:e};zm.prototype.delete=function(t){deletethis.map[q8(t)]};zm.prototype.get=function(t){returnt=q8(t),this.has(t)?this.map[t]:null};zm.prototype.has=function(t){returnthis.map.hasOwnProperty(q8(t))};zm.prototype.set=function(t,e){this.map[q8(t)]=Jtt(e)};zm.prototype.forEach=function(t,e){for(varrinthis.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)};zm.prototype.keys=function(){vart=[];returnthis.forEach(function(e,r){t.push(r)}),Ktt(t)};zm.prototype.values=function(){vart=[];returnthis.forEach(function(e){t.push(e)}),Ktt(t)};zm.prototype.entries=function(){vart=[];returnthis.forEach(function(e,r){t.push([r,e])}),Ktt(t)};r_.iterable&&(zm.prototype[Symbol.iterator]=zm.prototype.entries);Oso=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];EV.prototype.clone=function(){returnnewEV(this,{body:this._bodyInit})};$fr.call(EV.prototype);$fr.call(eA.pro
`);r=a.pop()??"";for(let s of a)try{yield JSON.parse(s)}catch{console.warn("invalid json: ",s)}}r+=e.decode();for(let o of r.split(`
`).filter(i=>i!==""))try{yield JSON.parse(o)}catch{console.warn("invalid json: ",o)}},kso=t=>{if(!t)return qfr;let e=t.includes("://");t.startsWith(":")&&(t=`http://127.0.0.1${t}`,e=!0),e||(t=`http://${t}`);let r=new URL(t),n=r.port;n||(e?n=r.protocol==="https:"?"443":"80":n=kfr);let o="";r.username&&(o=r.username,r.password&&(o+=`:${r.password}`),o+="@");let i=`${r.protocol}//${o}${r.hostname}:${n}${r.pathname}`;return i.endsWith("/")&&(i=i.slice(0,-1)),i},qso=Object.defineProperty,Uso=(t,e,r)=>e in t?qso(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ztt=(t,e,r)=>(Uso(t,typeof e!="symbol"?e+"":e,r),r),U8=class{constructor(e){Ztt(this,"config"),Ztt(this,"fetch"),Ztt(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e?.headers},e?.proxy||(this.config.host=kso(e?.host??qfr)),this.fetch=e?.fetch??fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,r){r.stream=r.stream??!1;let n=`${this.config.host}/api/${e}`;if(r.stream){let i=new AbortController,a=await Wk(this.fetch,n,r,{signal:i.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");let s=Fso(a.body),u=new Qtt(i,s,()=>{let l=this.ongoingStreamedRequests.indexOf(u);l>-1&&this.ongoingStreamedRequests.splice(l,1)});return this.ongoingStreamedRequests.push(u),u}return await(await Wk(this.fetch,n,r,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!="string"){let r=new Uint8Array(e),n="",o=r.byteLength;for(let i=0;i<o;i++)n+=String.fromCharCode(r[i]);return btoa(n)}return e}async generate(e){return e.images&&(e.images=await Promise.all(e.images.map(this.encodeImage.bind(this)))),this.processStreamableRequest("generate",e)}async chat(e){if(e.messages)for(let r of e.messages)r.images&&(r.images=await Promise.all(r.images.map(this.encodeImage.bind(this))));return this.processStreamableRequest("chat",e)}async create(e){return this.processStreamableRequest("create",{...e})}async pull(e){return this.processStreamableRequest("pull",{name:e.model,stream:e.stream,insecure:e.insecure})}async push(e){return this.processStreamableRequest("push",{name:e.model,stream:e.stream,insecure:e.insecure})}async delete(e){return await Lso(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await Wk(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await Xtt(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await Wk(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await Wk(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await Wk(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await Xtt(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await Xtt(this.fetch,`${this.config.host}/api/version`,{headers:this.config.headers})).json()}async webSearch(e){if(!e.query||e.query.length===0)throw new Error("Query is required");return await(await Wk(this.fetch,"https://ollama.com/api/web_search",{...e},{headers:this.config.headers})).json()}async webFetch(e){if(!e.url||e.url.length===0)throw new Error("URL is required");return await(await Wk(this.fetch,"https://ollama.com/api/web_fetch",{...e},{headers:this.config.headers})).json()}},CIa=new U8});function Ix(t,e){if(t.function===void 0)return;let r;if(e?.partial)try{r=Mz(t.function.arguments??"{}")}catch{return}else try{r=JSON.parse(t.function.arguments)}catch(o){throw new Ih([`Function "${t.function.name}" arguments:`,"",t.function.arguments,"","are not valid JSON.",`Error: ${o.message}`].join(`
`))}let n={name:t.function.name,args:r,type:"tool_call"};return e?.returnId&&(n.id=t.id),n}function Jk(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 _0(t,e){return{name:t.function?.name,args:t.function?.arguments,id:t.id,error:e,type:"invalid_tool_call"}}var rrt,lv,Ufr=v(()=>{NQ();vS();QN();MJ();dF();A3e();rrt=class extends cF{constructor(e){super(e);x(this,"returnId",!1);x(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);x(this,"lc_serializable",!0);this.returnId=e?.returnId??this.returnId}static lc_name(){return"JsonOutputToolsParser"}_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(kl(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=>Ix(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}},lv=class extends rrt{constructor(e){super(e);x(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);x(this,"lc_serializable",!0);x(this,"returnId",!1);x(this,"keyName");x(this,"returnSingle",!1);x(this,"zodSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}static lc_name(){return"JsonOutputKeyToolsParser"}async _validateResult(e){if(this.zodSchema===void 0)return e;let r=await tF(this.zodSchema,e);if(r.success)return r.data;throw new Ih(`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 Bso,PV=v(()=>{Jo();Ufr();Bso={};$t(Bso,{JsonOutputKeyToolsParser:()=>lv,JsonOutputToolsParser:()=>rrt,convertLangChainToolCallToOpenAI:()=>Jk,makeInvalidToolCall:()=>_0,parseToolCall:()=>Ix})});var nrt,Bfr=v(()=>{Ifr();ta();YI();fTe();Ed();sw();pD();nO();fO();PV();au();uv();Ny();nrt=class extends jd{constructor(e){super(e??{});x(this,"model","llama3");x(this,"numa");x(this,"numCtx");x(this,"numBatch");x(this,"numGpu");x(this,"mainGpu");x(this,"lowVram");x(this,"f16Kv");x(this,"logitsAll");x(this,"vocabOnly");x(this,"useMmap");x(this,"useMlock");x(this,"embeddingOnly");x(this,"numThread");x(this,"numKeep");x(this,"seed");x(this,"numPredict");x(this,"topK");x(this,"topP");x(this,"tfsZ");x(this,"typicalP");x(this,"repeatLastN");x(this,"temperature");x(this,"repeatPenalty");x(this,"presencePenalty");x(this,"frequencyPenalty");x(this,"mirostat");x(this,"mirostatTau");x(this,"mirostatEta");x(this,"penalizeNewline");x(this,"streaming");x(this,"format");x(this,"keepAlive");x(this,"client");x(this,"checkOrPullModel",!1);x(this,"baseUrl","http://127.0.0.1:11434");x(this,"think");this.baseUrl=e?.baseUrl??Xr("OLLAMA_BASE_URL")??this.baseUrl,this.client=new U8({fetch:e?.fetch,host:this.baseUrl,headers:e?.headers}),this.model=e?.model??this.model,this.numa=e?.numa,this.numCtx=e?.numCtx,this.numBatch=e?.numBatch,this.numGpu=e?.numGpu,this.mainGpu=e?.mainGpu,this.lowVram=e?.lowVram,this.f16Kv=e?.f16Kv,this.logitsAll=e?.logitsAll,this.vocabOnly=e?.vocabOnly,this.useMmap=e?.useMmap,this.useMlock=e?.useMlock,this.embeddingOnly=e?.embeddingOnly,this.numThread=e?.numThread,this.numKeep=e?.numKeep,this.seed=e?.seed,this.numPredict=e?.numPredict,this.topK=e?.topK,this.topP=e?.topP,this.tfsZ=e?.tfsZ,this.typicalP
`,t}varHfr=v(()=>{});functionKr(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}functionPe(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)}varv0=v(()=>{});varart,srt=v(()=>{art=function(){let{crypto:t}=globalThis;if(t?.randomUUID)returnart=t.randomUUID.bind(t),t.randomUUID();lete=newUint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))}});functionNie(t){returntypeoft=="object"&&t!==null&&("name"int&&t.name==="AbortError"||"message"int&&String(t.message).includes("FetchRequestCanceledException"))}varDie,pTe=v(()=>{Die=t=>{if(tinstanceofError)returnt;if(typeoft=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){lete=newError(t.message,t.cause?{cause:t.cause}:{});returnt.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{returnnewError(JSON.stringify(t))}catch{}}returnnewError(t)}});varGt,Vm,zc,Kk,tA,B8,z8,V8,H8,W8,J8,K8,G8,X8,Z8,rA,nA=v(()=>{pTe();Gt=classextendsError{},Vm=classtextendsGt{constructor(e,r,n,o){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=o,this.requestID=o?.get("x-request-id"),this.error=r;leti=r;this.code=i?.code,this.param=i?.param,this.type=i?.type}staticmakeMessage(e,r,n){leto=r?.message?typeofr.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;returne&&o?`${e}${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}staticgenerate(e,r,n,o){if(!e||!o)returnnewKk({message:n,cause:Die(r)});leti=r?.error;returne===400?newB8(e,i,n,o):e===401?newz8(e,i,n,o):e===403?newV8(e,i,n,o):e===404?newH8(e,i,n,o):e===409?newW8(e,i,n,o):e===422?newJ8(e,i,n,o):e===429?newK8(e,i,n,o):e>=500?newG8(e,i,n,o):newt(e,i,n,o)}},zc=classextendsVm{constructor({message:e}={}){super(void0,void0,e||"Request was aborted.",void0)}},Kk=classextendsVm{constructor({message:e,cause:r}){super(void0,void0,e||"Connection error.",void0),r&&(this.cause=r)}},tA=classextendsKk{constructor({message:e}={}){super({message:e??"Request timed out."})}},B8=classextendsVm{},z8=classextendsVm{},V8=classextendsVm{},H8=classextendsVm{},W8=classextendsVm{},J8=classextendsVm{},K8=classextendsVm{},G8=classextendsVm{},X8=classextendsGt{constructor(){super("Could not parse response content as the length limit was reached")}},Z8=classextendsGt{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},rA=classextendsError{constructor(e){super(e)}}});functionlrt(t){returntypeoft!="object"?{}:t??{}}functionJfr(t){if(!t)return!0;for(leteint)return!1;return!0}functionKfr(t,e){returnObject.prototype.hasOwnProperty.call(t,e)}functionY8(t){returnt!=null&&typeoft=="object"&&!Array.isArray(t)}varVso,Wfr,nb,urt,Gfr,Xfr,hD=v(()=>{nA();Vso=/^[a-z][a-z0-9+.-]*:/i,Wfr=t=>Vso.test(t),nb=t=>(nb=Array.isArray,nb(t)),urt=nb;Gfr=(t,e)=>{if(typeofe!="number"||!Number.isInteger(e))thrownewGt(`${t} must be an integer`);if(e<0)thrownewGt(`${t} must be a positive integer`);returne},Xfr=t=>{try{returnJSON.parse(t)}catch{return}}});varoA,Q8=v(()=>{oA=t=>newPromise(e=>setTimeout(e,t))});varGk,crt=v(()=>{Gk="6.16.0"});functionHso(){returntypeofDeno<"u"&&Deno.build!=null?"deno":typeofEdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeofglobalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}functionJso(){if(typeofnavigator>"
`,"\r"]);MV.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function $ie(){}function vTe(t,e,r){return!e||wTe[t]>wTe[r]?$ie:e[t].bind(e)}function md(t){let e=t.logger,r=t.logLevel??"off";if(!e)return euo;let n=vpr.get(e);if(n&&n[0]===r)return n[1];let o={error:vTe("error",e,r),warn:vTe("warn",e,r),info:vTe("info",e,r),debug:vTe("debug",e,r)};return vpr.set(e,[r,o]),o}var wTe,wrt,euo,vpr,gD,Lie=v(()=>{hD();wTe={off:0,error:200,warn:300,info:400,debug:500},wrt=(t,e,r)=>{if(t){if(Kfr(wTe,t))return t;md(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(wTe))}`)}};euo={error:$ie,warn:$ie,info:$ie,debug:$ie},vpr=new WeakMap;gD=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*tuo(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Gt("Thedefaultreact-nativefetchimplementationdoesnotsupportstreaming.Pleaseuseexpo/fetch:https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new Gt("Attempted to iterate over a response with no body");let r=new Srt,n=new MV,o=prt(t.body);for await(let i of ruo(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*ruo(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"?eG(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let i;for(;(i=bpr(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function nuo(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var Fie,aA,Srt,Crt=v(()=>{v0();nA();jie();_pr();jie();pTe();_Te();Lie();nA();aA=class t{constructor(e,r,n){this.iterator=e,Fie.set(this,void 0),this.controller=r,Kr(this,Fie,n,"f")}static fromSSEResponse(e,r,n){let o=!1,i=n?md(n):console;async function*a(){if(o)throw new Gt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let s=!1;try{for await(let u of tuo(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 Vm(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 Vm(void 0,l.error,l.message,void 0);yield{event:u.event,data:l}}}s=!0}catch(u){if(Nie(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 MV,u=prt(e);for await(let l of u)for(let c of s.decode(l))yield c;for(let l of s.flush())yield l}async function*a(){if(o)throw new Gt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let s=!1;try{for await(let u of i())s||u&&(yield JSON.parse(u));s=!0}catch(u){if(Nie(u))return;throw u}finally{s||r.abort()}}return new t(a,r,n)}[(Fie=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,Pe(this,Fie,"f")),new t(()=>o(r),this.controller,Pe(this,Fie,"f"))]}toReadableStream(){let e=this,r;return frt({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=eG(JSON.stringify(o)+`
${d}`)}returna},Le=duo(Epr)});varIV,OTe=v(()=>{Vr();Lu();is();IV=classextendsJe{list(e,r={},n){returnthis._client.getAPIList(Le`/chat/completions/${e}/messages`,ci,{query:r,...n})}}});varAx=v(()=>{nA()});functionVie(t){returnt!==void0&&"function"int&&t.function!==void0}functionPpr(t,e){letr={...t};returnObject.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}functionHie(t){returnt?.$brand==="auto-parseable-response-format"}functionAV(t){returnt?.$brand==="auto-parseable-tool"}functionMpr(t,e){return!e||!Art(e)?{...t,choices:t.choices.map(r=>(Ipr(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void0}}))}:Wie(t,e)}functionWie(t,e){letr=t.choices.map(n=>{if(n.finish_reason==="length")thrownewX8;if(n.finish_reason==="content_filter")thrownewZ8;returnIpr(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(o=>huo(e,o))??void0}:void0,parsed:n.message.content&&!n.message.refusal?muo(e,n.message.content):null}}});return{...t,choices:r}}functionmuo(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}functionhuo(t,e){letr=t.tools?.find(n=>Vie(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:AV(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}functionRpr(t,e){if(!t||!("tools"int)||!t.tools)return!1;letr=t.tools?.find(n=>Vie(n)&&n.function?.name===e.function.name);returnVie(r)&&(AV(r)||r?.function.strict||!1)}functionArt(t){returnHie(t.response_format)?!0:t.tools?.some(e=>AV(e)||e.type==="function"&&e.function.strict===!0)??!1}functionIpr(t){for(leteoft||[])if(e.type!=="function")thrownewGt(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}functionApr(t){for(leteoft??[]){if(e.type!=="function")thrownewGt(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)thrownewGt(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}varrG=v(()=>{Ax()});varnG,Nrt,Drt=v(()=>{nG=t=>t?.role==="assistant",Nrt=t=>t?.role==="tool"});varjrt,ETe,PTe,Jie,Kie,MTe,Gie,bD,Xie,RTe,ITe,oG,Npr,Xk,ATe=v(()=>{v0();Ax();Xk=class{constructor(){jrt.add(this),this.controller=newAbortController,ETe.set(this,void0),PTe.set(this,()=>{}),Jie.set(this,()=>{}),Kie.set(this,void0),MTe.set(this,()=>{}),Gie.set(this,()=>{}),bD.set(this,{}),Xie.set(this,!1),RTe.set(this,!1),ITe.set(this,!1),oG.set(this,!1),Kr(this,ETe,newPromise((e,r)=>{Kr(this,PTe,e,"f"),Kr(this,Jie,r,"f")}),"f"),Kr(this,Kie,newPromise((e,r)=>{Kr(this,MTe,e,"f"),Kr(this,Gie,r,"f")}),"f"),Pe(this,ETe,"f").catch(()=>{}),Pe(this,Kie,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},Pe(this,jrt,"m",Npr).bind(this))},0)}_connected(){this.ended||(Pe(this,PTe,"f").call(this),this._emit("connect"))}getended(){returnPe(this,Xie,"f")}geterrored(){returnPe(this,RTe,"f")}getaborted(){returnPe(this,ITe,"f")}abort(){this.controller.abort()}on(e,r){return(Pe(this,bD,"f")[e]||(Pe(this,bD,"f")[e]=[])).push({listener:r}),this}off(e,r){letn=Pe(this,bD,"f")[e];if(!n)returnthis;leto=n.findIndex(i=>i.listener===r);returno>=0&&n.splice(o,1),this}once(e,r){return(Pe(this,bD,"f")[e]||(Pe(this,bD,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){returnnewPromise((r,n)=>{Kr(this,oG,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}asyncdone(){Kr(this,oG,!0,"f"),awaitPe(this,Kie,"f")}_emit(e,...r){if(Pe(this,Xie,"f"))return;e==="end"&&(Kr(this,Xie,!0,"f"),Pe(this,MTe,"f").call(this));letn=Pe(this,bD,"f")[e];if(n&&(Pe(this,bD,"f")[e]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...r))),e==="abort"){leto=r[0];!Pe(this,oG,"f")&&!n?.length
\r`.includes(t[n]);)n++};return a()},Hrt=t=>yuo(t,Wh.ALL^Wh.NUM)});var Wrt=v(()=>{Crt()});function _uo(t,e){let{id:r,choices:n,created:o,model:i,system_fingerprint:a,...s}=t,u={...s,id:r,choices:n.map(({message:l,finish_reason:c,index:d,logprobs:f,...p})=>{if(!c)throw new Gt(`missingfinish_reasonforchoice${d}`);let{content:m=null,function_call:h,tool_calls:y,...g}=l,b=l.role;if(!b)throw new Gt(`missingroleforchoice${d}`);if(h){let{arguments:_,name:w}=h;if(_==null)throw new Gt(`missingfunction_call.argumentsforchoice${d}`);if(!w)throw new Gt(`missingfunction_call.nameforchoice${d}`);return{...p,message:{content:m,function_call:{arguments:_,name:w},role:b,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}return y?{...p,index:d,finish_reason:c,logprobs:f,message:{...g,role:b,content:m,refusal:l.refusal??null,tool_calls:y.map((_,w)=>{let{function:T,type:O,id:E,...P}=_,{arguments:R,name:I,...N}=T||{};if(E==null)throw new Gt(`missingchoices[${d}].tool_calls[${w}].id
${$Te(t)}`);if(O==null)throw new Gt(`missingchoices[${d}].tool_calls[${w}].type
${$Te(t)}`);if(I==null)throw new Gt(`missingchoices[${d}].tool_calls[${w}].function.name
${$Te(t)}`);if(R==null)throw new Gt(`missingchoices[${d}].tool_calls[${w}].function.arguments
${$Te(t)}`);return{...P,id:E,type:O,function:{...N,name:I,arguments:R}}})}}:{...p,message:{...g,content:m,role:b,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}),created:o,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};return Mpr(u,e)}function $Te(t){return JSON.stringify(t)}var Wm,_D,aG,Zk,Jrt,DTe,Krt,Grt,Xrt,jTe,Zrt,Fpr,NV,LTe=v(()=>{v0();Lpr();Ax();rG();Wrt();Urt();NV=class t extends iG{constructor(e){super(),Wm.add(this),_D.set(this,void 0),aG.set(this,void 0),Zk.set(this,void 0),Kr(this,_D,e,"f"),Kr(this,aG,[],"f")}get currentChatCompletionSnapshot(){return Pe(this,Zk,"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())),Pe(this,Wm,"m",Jrt).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)Pe(this,Wm,"m",Krt).call(this,a);if(i.controller.signal?.aborted)throw new zc;return this._addChatCompletion(Pe(this,Wm,"m",jTe).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),Pe(this,Wm,"m",Jrt).call(this),this._connected();let o=aA.fromReadableStream(e,this.controller),i;for await(let a of o)i&&i!==a.id&&this._addChatCompletion(Pe(this,Wm,"m",jTe).call(this)),Pe(this,Wm,"m",Krt).call(this,a),i=a.id;if(o.controller.signal?.aborted)throw new zc;return this._addChatCompletion(Pe(this,Wm,"m",jTe).call(this))}[(_D=new WeakMap,aG=new WeakMap,Zk=new WeakMap,Wm=new WeakSet,Jrt=function(){this.ended||Kr(this,Zk,void 0,"f")},DTe=function(r){let n=Pe(this,aG,"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},Pe(this,aG,"f")[r.index]=n,n)},Krt=function(r){if(this.ended)return;let n=Pe(this,Wm,"m",Fpr).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=Pe(this,Wm,"m",DTe).call(this,i);i.finish_reason&&(Pe(this,Wm,"m",Xrt).call(this,i),a.current_tool_call_index!=null&&Pe(this,Wm,"m",Grt).call(this,i,a.current_tool_call_index));for(let s of o.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(Pe(this,Wm,"m",Xrt).call(this,i),a.current_tool_call_index!=null&&Pe(this,Wm,"m",Grt).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))}}},Grt=function(r,n){if(Pe(this,Wm,"m",DTe).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=Pe(this,_D,"f")?.tools?.find(s=>Vie(s)&&s.func
`);this.baseURL=s.baseURL,this.timeout=s.timeout??iot.DEFAULT_TIMEOUT,this.logger=s.logger??console;letu="warn";this.logLevel=u,this.logLevel=wrt(s.logLevel,"ClientOptions.logLevel",this)??wrt(Nx("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??rpr(),Kr(this,KTe,opr,"f"),this._options=s,this.apiKey=typeofr=="string"?r:"Missing Key",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){returngt([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return_rt(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Gk}`}defaultIdempotencyKey(){return`stainless-node-retry-${art()}`}makeStatusError(e,r,n,o){returnVm.generate(e,r,n,o)}async_callApiKey(){lete=this._options.apiKey;if(typeofe!="function")return!1;letr;try{r=awaite()}catch(n){throwninstanceofGt?n:newGt(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeofr!="string"||!r)thrownewGt(`Expected 'apiKey' function argument to return a string but it returned ${r}`);returnthis.apiKey=r,!0}buildURL(e,r,n){leto=!Pe(this,oot,"m",umr).call(this)&&n||this.baseURL,i=Wfr(e)?newURL(e):newURL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();returnJfr(a)||(r={...a,...r}),typeofr=="object"&&r&&!Array.isArray(r)&&(i.search=this.stringifyQuery(r)),i.toString()}asyncprepareOptions(e){awaitthis._callApiKey()}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){returnnewRV(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(md(this).debug(`[${l}] sending request`,gD({retryOfRequestLogID:n,method:o.method,url:s,options:o,headers:a.headers})),o.signal?.aborted)thrownewzc;letf=newAbortController,p=awaitthis.fetchWithTimeout(s,a,u,f).catch(Die),m=Date.now();if(pinstanceofglobalThis.Error){letg=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)thrownewzc;letb=Nie(p)||/timed? ?out/i.test(String(p)+("cause"inp?String(p.cause):""));if(r)returnmd(this).info(`[${l}] connection ${b?"timed out":"failed"} - ${g}`),md(this).debug(`[${l}] connection ${b?"timed out":"failed"} (${g})`,gD({retryOfRequestLogID:n,url:s,durationMs:m-d,message:p.message})),this.retryRequest(o,r,n??l);throwmd(this).info(`[${l}] connection ${b?"timed out":"failed"} - error; no more retries left`),md(this).debug(`[${l}] connection ${b?"timed out":"failed"} (error; no more retries left)`,gD({retryOfRequestLogID:n,url:s,durationMs:m-d,message:p.message})),b?newtA:newKk({cause:p})}leth=[...p.headers.entries()].filter(([g])=>g==="x-request-id").map(([g,b])=>", "+g+": "+JSON.stringify(b)).join(""),y=`[${l}${c}${h}] ${a.method}${s}${p.ok?"succeeded":"failed"} with status ${p.status} in ${m-d}ms`;if(!p.ok){letg=awaitthis.shouldRetry(p);if(r&&g){letE=`retrying, ${r} attempts remaining`;returnawaitnpr(p.body),md(this).info(`${y} - ${E}`),md(this).debug(`[${l}] response error (${E})`,gD({retryOfRequestLogID:n,url:p.ur
]`;continue}i+=o[l],o[l]==="\\"?a=!0:s&&o[l]==="]"?s=!1:!s&&o[l]==="["&&(s=!0)}try{letl=newRegExp(i)}catch{returnconsole.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}returni}});function_Oe(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===Ae.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:Dn(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};letr={type:"object",additionalProperties:Dn(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")returnr;if(t.keyType?._def.typeName===Ae.ZodString&&t.keyType._def.checks?.length){letn=Object.entries(yOe(t.keyType._def,e)).reduce((o,[i,a])=>i==="type"?o:{...o,[i]:a},{});return{...r,propertyNames:n}}elseif(t.keyType?._def.typeName===Ae.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};returnr}varvOe=v(()=>{cO();$d();bOe()});functionDhr(t,e){if(e.mapStrategy==="record")return_Oe(t,e);letr=Dn(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=Dn(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}}}varfit=v(()=>{$d();vOe()});functionjhr(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}}varpit=v(()=>{});function$hr(){return{not:{}}}varmit=v(()=>{});functionLhr(t){returnt.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}varhit=v(()=>{});functionkhr(t,e){if(e.target==="openApi3")returnFhr(t,e);letr=t.optionsinstanceofMap?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeNameincae&&(!n._def.checks||!n._def.checks.length))){letn=r.reduce((o,i)=>{leta=cae[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._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};returnFhr(t,e)}varcae,Fhr,wOe=v(()=>{$d();cae={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Fhr=(t,e)=>{letr=(t.optionsinstanceofMap?Array.from(t.options.values()):t.options).map((n,o)=>Dn(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeofn=="object"&&Object.keys(n).length>0));returnr.length?{anyOf:r}:void0}});functionqhr(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))returne.target==="openApi3"||e.nullableStrategy==="property"?{type:cae[t.innerType._def.typeName],nullable:!0}:{type:[cae[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){letn=Dn(t.innerType._def,{...e,currentPath:[...e.currentPath]});returnn&&"$ref"inn?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}letr=Dn(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});returnr&&{anyOf:[r,{type:"null"}]}}vargit=v(()=>{$d();wOe()});functionUhr(t,e){letr={type:"number"};if(!t.checks)returnr;for(letnoft.checks)switch(n.kind){case"int":r.type="integer",Zot(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?
${Yt.prettifyError(m)}`),new H6(h,JSON.stringify(e))}else{let m=Ku(o,this.schema);if(!m.valid){let h="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(h=`${h}
Result:${JSON.stringify(l)}`);else c=l;let f;qL(e)&&(f=e.id),!f&&DCt(a)&&(f=a.toolCall.id);let p=Jco({content:c,artifact:d,toolCallId:f,name:this.name,metadata:this.metadata});return await u?.handleToolEnd(p),p}},Bit=class extends Uit{constructor(e){super(e);x(this,"schema",wt.object({input:wt.string().optional()}).transform(e=>e.input))}call(e,r){let n=typeof e=="string"||e==null?{input:e}:e;return super.call(n,r)}},zit=class extends Bit{constructor(e){super(e);x(this,"name");x(this,"description");x(this,"func");this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}static lc_name(){return"DynamicTool"}async call(e,r){let n=HN(r);return n.runName===void 0&&(n.runName=this.name),super.call(e,n)}async _call(e,r,n){return this.func(e,r,n)}},wgr=class extends Uit{constructor(e){super(e);x(this,"description");x(this,"func");x(this,"schema");this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}static lc_name(){return"DynamicStructuredTool"}async call(e,r,n){let o=HN(r);return o.runName===void 0&&(o.runName=this.name),super.call(e,o,n)}_call(e,r,n){return this.func(e,r,n)}},Wco=class{getTools(){return this.tools}}});var Vit=v(()=>{dA();au();mq()});var Sgr=v(()=>{});var Cgr=v(()=>{});var xgr=v(()=>{});var Tgr=v(()=>{});var Ogr=v(()=>{});var Gco,Xco,Zco,Yco,Qco,edo,tdo,rdo,ndo,odo,Z4a,Egr=v(()=>{ta();mq();eH();Gco=Yt.object({type:Yt.literal("screenshot")}),Xco=Yt.object({type:Yt.literal("click"),x:Yt.number(),y:Yt.number(),button:Yt.enum(["left","right","wheel","back","forward"]).default("left")}),Zco=Yt.object({type:Yt.literal("double_click"),x:Yt.number(),y:Yt.number(),button:Yt.enum(["left","right","wheel","back","forward"]).default("left")}),Yco=Yt.object({type:Yt.literal("drag"),path:Yt.array(Yt.object({x:Yt.number(),y:Yt.number()}))}),Qco=Yt.object({type:Yt.literal("keypress"),keys:Yt.array(Yt.string())}),edo=Yt.object({type:Yt.literal("move"),x:Yt.number(),y:Yt.number()}),tdo=Yt.object({type:Yt.literal("scroll"),x:Yt.number(),y:Yt.number(),scroll_x:Yt.number(),scroll_y:Yt.number()}),rdo=Yt.object({type:Yt.literal("type"),text:Yt.string()}),ndo=Yt.object({type:Yt.literal("wait"),duration:Yt.number().optional()}),odo=Yt.discriminatedUnion("type",[Gco,Xco,Zco,Yco,Qco,edo,tdo,rdo,ndo]),Z4a=Yt.object({action:odo})});var ido,t2a,Pgr=v(()=>{mq();eH();ido=Yt.object({type:Yt.literal("exec"),command:Yt.array(Yt.string()),env:Yt.record(Yt.string(),Yt.string()).optional(),working_directory:Yt.string().optional(),timeout_ms:Yt.number().optional(),user:Yt.string().optional()}),t2a=Yt.discriminatedUnion("type",[ido])});var i2a,Mgr=v(()=>{mq();eH();i2a=Yt.object({commands:Yt.array(Yt.string()).describe("Array of shell commands to execute"),timeout_ms:Yt.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:Yt.number().optional().describe("Optional maximum number of characters to return from each command")})});var ado,sdo,udo,l2a,Rgr=v(()=>{mq();eH();ado=Yt.object({type:Yt.literal("create_file"),path:Yt.string(),diff:Yt.string()}),sdo=Yt.object({type:Yt.literal("update_file"),path:Yt.string(),diff:Yt.string()}),udo=Yt.object({type:Yt.literal("delete_file"),path:Yt.string()}),l2a=Yt.discriminatedUnion("type",[ado,sdo,udo])});var Igr=v(()=>{Vit();Sgr();Cgr();xgr();Tgr();Ogr();Egr();Pgr();Mgr();Rgr()});var Agr=v(()=>{sw();mq();Vz()});var Ngr=v(()=>{qG()});var Dgr=v(()=>{qG();EOe()});var iH=v(()=>{uq();lq();cq();dae();qG();COe();Nit();EOe();MOe();$it();Lit();bgr();Fit();_gr();kit();vgr();Vit();Igr();Agr();Ngr();Dgr();dA()});var $gr=S((EVa,jgr)=>{jgr.exports={createRequire:function(t){return typeof require<"u"?require:function(r){throw new Error('Dynamic require of "'+r+'" is not supported in this environment')}}}});var ldo,cdo,Lgr,Fgr=v(()=>{ldo=$($gr(),1),cdo=Object.defineProperty,Lgr=(t,e)=>{for(var r in e)cdo(t,r,{get:e[r],enumerable:!0})}});var ddo,Hit,kgr=v(()=>{Fgr();au();vV();zk();ddo={};Lgr(ddo,{JinaEmbeddings:()=>Hit});Hit=class extends y0{co
without CORS Error: `+zr(n)+`
with CORS Error: `+zr(o);thrownewError(i)}}}}});varBgr,AOe,zgr=v(()=>{Xe();Ye();Bt();Bgr=require("obsidian"),AOe=classt{constructor(){this.cachedBaseUrl=null}staticgetInstance(){returnt.instance||(t.instance=newt),t.instance}asyncresolveBaseUrl(e={}){letr=(e.overrideUrl||"").trim();if(r.length>0)returnthis.normalizeBaseUrl(r);if(this.cachedBaseUrl&&!e.forceRefresh)returnthis.cachedBaseUrl;if(!Bgr.Platform.isDesktopApp)returnnull;letn=awaitthis.readServiceConfig();if(!n)returnthis.cachedBaseUrl=null,null;leto=this.normalizeBaseUrl(`http://${n.host}:${n.port}`);returnthis.cachedBaseUrl=o,o}normalizeBaseUrl(e){returne.trim().replace(/\/+$/,"")}getServiceFilePath(){lete=this.getNodeRequire();if(!e)returnnull;letr=e("os");returne("path").join(r.homedir(),"Library","Application Support","Miyo","service.json")}asyncreadServiceConfig(){lete=this.getServiceFilePath();if(!e)returnnull;try{letr=this.getNodeRequire();if(!r)returnnull;leto=awaitr("fs").promises.readFile(e,"utf8"),i=JSON.parse(o);return!i.host||typeofi.host!="string"?(Te("Miyo service discovery missing host"),null):typeofi.port!="number"||Number.isNaN(i.port)?(Te("Miyo service discovery missing port"),null):(te().debug&&F(`Miyo service discovery resolved host=${i.host} port=${i.port}`),i)}catch(r){returnte().debug&&Te(`Miyo service discovery failed: ${zr(r)}`),null}}getNodeRequire(){lete=globalThis?.require;returntypeofe=="function"?e:null}}});varVgr,S0,BG=v(()=>{Xe();Ye();Bt();Vgr=require("obsidian");zgr();S0=class{constructor(){this.discovery=AOe.getInstance()}asyncresolveBaseUrl(e){letr=awaitthis.discovery.resolveBaseUrl({overrideUrl:e});if(!r)thrownewError("Miyo base URL not available");returnr}asyncisBackendAvailable(e){try{letr=awaitthis.resolveBaseUrl(e);return(awaitthis.requestJson(r,"/v0/health",{method:"GET"}))?.status==="ok"}catch(r){returnte().debug&&Te(`Miyo backend availability check failed: ${zr(r)}`),!1}}asyncupsertDocuments(e,r,n){leto={vault:r,documents:n};return(awaitthis.requestJson(e,"/v0/index/upsert",{method:"POST",body:o}))?.upserted??0}asyncdeleteByPath(e,r,n){leto={vault:r,path:n};return(awaitthis.requestJson(e,"/v0/index/by_path",{method:"DELETE",body:o}))?.deleted??0}asyncclearIndex(e,r){letn={vault:r};awaitthis.requestJson(e,"/v0/index/clear",{method:"POST",body:n})}asynclistFiles(e,r,n,o){returnthis.requestJson(e,"/v0/index/files",{method:"GET",query:{vault:r,offset:n,limit:o}})}asyncgetStats(e,r){returnthis.requestJson(e,"/v0/index/stats",{method:"GET",query:{vault:r}})}asyncgetDocumentsByPath(e,r,n){returnthis.requestJson(e,"/v0/index/documents",{method:"GET",query:{vault:r,path:n}})}asyncsearch(e,r,n,o,i){leta={query:n,vault:r,limit:o,...i&&i.length>0?{filters:i}:{}};returnte().debug&&F("Miyo search request:",{baseUrl:e,payload:a}),this.requestJson(e,"/v0/search",{method:"POST",body:a})}asyncsearchRelated(e,r,n){leto={file_path:r,...n?.sourceId?{vault:n.sourceId}:{},...typeofn?.limit=="number"?{limit:n.limit}:{},...n?.filters&&n.filters.length>0?{filters:n.filters}:{}};returnte().debug&&F("Miyo related search request:",{baseUrl:e,payload:o}),this.requestJson(e,"/v0/search/related",{method:"POST",body:o})}asyncparseDoc(e,r){returnthis.requestJson(e,"/v0/parse-doc",{method:"POST",body:{path:r}})}buildHeaders(){lete=te().selfHostApiKey,r={};returne&&(r.Authorization=`Bearer ${e}`,r["X-API-Key"]=e),r}asyncrequestJson(e,r,n){leto=newURL(r,e);n.query&&Object.entries(n.query).forEach(([u,l])=>{l!=null&&o.searchParams.set(u,String(l))});leti=n.body?JSON.stringify(n.body):void0;F("Miyo request:",{method:n.method,url:o.toString(),hasBody:!!i,...te().debug&&n.method==="POST"?{postBody:n.body}:{}});leta=await(0,Vgr.requestUrl)({url:o.toString(),method:n.method,headers:this.buildHeaders(),contentType:i?"application/json":void0,body:i,throw:!1});if(a.status>=400){letu=a.text?a.text:"";throwTe(`Miyo request failed (${a.status}): ${u}`),newError(`Miyo request failed with status ${a.status}`)}lets=this.parseResponseJson(a.json,a.text);returnte().debug&&F(`Miyo request
- `),Edo={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported.
- ${Odo}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmer property must be a function.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.oramasearch.com/open-source/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Custom stop words array must only contain strings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boost value must be a number greater than, or less than 0.",INVALID_FILTER_OPERATION:"You can only use one operation per filter, you requested %d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sort is disabled. Please read the documentation at https://docs.oramasearch for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead.
Input vectors must be of the size declared in the schema, as calculating similarity between vectors of different sizes can lead to unexpected results.`,WRONG_SEARCH_PROPERTY_TYPE:'Property "%s" is not searchable. Only "string" properties are searchable.',FACET_NOT_SUPPORTED:`Facet doens't support the type "%s".`,INVALID_DISTANCE_SUFFIX:'Invalid distance suffix "%s". Valid suffixes are: cm, m, km, mi, yd, ft.',INVALID_SEARCH_MODE:'Invalid search mode "%s". Valid modes are: "fulltext", "vector", "hybrid".',MISSING_VECTOR_AND_SECURE_PROXY:"No vector was provided and no secure proxy was configured. Please provide a vector or configure an Orama Secure Proxy to perform hybrid search.",MISSING_TERM:'"term" is a required parameter when performing hybrid search. Please provide a search term.',INVALID_VECTOR_INPUT:'Invalid "vector" property. Expected an object with "value" and "property" properties, but got "%s" instead.',PLUGIN_CRASHED:"A plugin crashed during initialization. Please check the error message for more information:",PLUGIN_SECURE_PROXY_NOT_FOUND:`Could not find '@orama/secure-proxy-plugin' installed in your Orama instance.
Please install it before proceeding with creating an answer session.
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL:`Could not find a chat model defined in the secure proxy plugin configuration.
Please provide a chat model before proceeding with creating an answer session.
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages."}});functionsyr(t){return{raw:Number(t),formatted:lH(t)}}functionuyr(t){if(t.id){if(typeoft.id!="string")throwUr("DOCUMENT_ID_MUST_BE_STRING",typeoft.id);returnt.id}returngae()}functionQit(t,e){for(let[r,n]ofObject.entries(e)){leto=t[r];if(!(typeofo>"u")&&!(n==="geopoint"&&typeofo=="object"&&typeofo.lon=="number"&&typeofo.lat=="number")&&!(n==="enum"&&(typeofo=="string"||typeofo=="number"))){if(n==="enum[]"&&Array.isArray(o)){leti=o.length;for(leta=0;a<i;a++)if(typeofo[a]!="string"&&typeofo[a]!="number")returnr+"."+a;continue}if(ID(n)){leti=tat(n);if(!Array.isArray(o)||o.length!==i)throwUr("INVALID_INPUT_VECTOR",r,i,o.length);continue}if(KG(n)){if(!Array.isArray(o))returnr;leti=eat(n),a=o.length;for(lets=0;s<a;s++)if(typeofo[s]!==i)returnr+"."+s;continue}if(typeofn=="object"){if(!o||typeofo!="object")returnr;leti=Qit(o,n);if(i)returnr+"."+i;continue}if(typeofo!==n)returnr}}}functionlyr(t){returnt==="geopoint"}functionID(t){returntypeoft=="string"&&/^vector\[\d+\]$/.test(t)}functionKG(t){returntypeoft=="string"&&Pdo[t]}functioneat(t){returnMdo[t]}functiontat(t){lete=Number(t.slice(7,-1));switch(!0){caseisNaN(e):throwUr("INVALID_VECTOR_VALUE",t);casee<=0:throwUr("INVALID_VECTOR_SIZE",t);default:returne}}varPdo,Mdo,yae=v(()=>{Jh();gd();gd();Pdo={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},Mdo={"string[]":"string","number[]":"number","boolean[]":"boolean","enum[]":"enum"}});functioncyr(){return{idToInternalId:newMap,internalIdToId:[],save:Rdo,load:Ido}}functionRdo(t){return{internalIdToId:t.internalIdToId}}functionIdo(t,e){let{internalIdToId:r}=e;t.internalDocumentIDStore.idToInternalId.clear(),t.internalDocumentIDStore.internalIdToId=[];letn=r.length;for(leto=0;o<n;o++){leti=r[o];t.internalDocumentIDStore.idToInternalId.set(i,o+1),t.internalDocumentIDStore.internalIdToId.push(i)}}functioncu(t,e){if(typeofe=="string"){letr=t.idToInternalId.get(e);if(r)returnr;letn=t.idToInternalId.size+1;returnt.idToInternalId.set(e,n),t.internalIdToId.push(e),n}returne>t.internalIdToId.length?cu(t,e.toString()):e}functionC0(t,e){if(t.internalIdToId.length<e)thrownewError(`Invalid internalId ${e}`);returnt.internalIdToId[e-1]}varx0=v(()=>{});functionNdo(t,e){return{sharedInternalDocumentStore:e,docs:{},count:0}}functionDdo(t,e){letr=cu(t.sharedInternalDocumentStore,e);returnt.docs[r]}functionjdo(t,e){letr=e.length,n=Array.from({length:r});for(leto=0;o<r;o++){leti=cu(t.sharedInternalDocumentStore,e[o]);n[o]=t.docs[i]}returnn}function$do(t){returnt.docs}functionLdo(t,e,r){letn=cu(t.sharedInternalDocumentStore,e);returntypeoft.docs[n]<"u"?!1:(t.docs[n]=r,t.count++,!0)}functionFdo(t,e){letr=cu(t.sharedInternalDocumentStore,e);returntypeoft.docs[r]>"u"?!1:(deletet.docs[r],t.count--,!0)}functionkdo(t){returnt.count}functionqdo(t,e){letr=e;return{docs:r.docs,count:r.count,sharedInternalDocumentStore:t}}functionUdo(t){return{docs:t.docs,count:t.count}}functiondyr(){return{create:Ndo,get:Ddo,getMultiple:jdo,getAll:$do,store:Ldo,remove:Fdo,count:kdo,load:qdo,save:Udo}}varrat=v(()=>{x0()});functionpyr(t,e){letr=[],n=t.plugins?.length;if(!n)returnr;for(leto=0;o<n;o++)try{leti=t.plugins[o];typeofi[e]=="function"&&r.push(i[e])}catch(i){throwconsole.error("Caught error in getAllPluginsByHook:",i),Ur("PLUGIN_CRASHED")}returnr}varfyr,myr=v(()=>{Jh();fyr=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeLoad","afterLoad","afterCreate"]});functionqx(t,e,r,n){if(t.some(Ld))return(async()=>{for(letioft)awaiti(e,r,n)})();for(letioft)i(e,r,n)}functioncH(t,e,r){if(t.some(Ld))return(async()=>{for(letooft)awaito(e,r)})();for(letoo
`,"",""];throw new Error(`Language ${r} is not supported.`)}}});var U_r=v(()=>{q_r()});function Sq(t){return Wat||(Wat=new Jat(t)),Wat}var zEe,BEe,Jat,Wat,Oae=v(()=>{Xe();mr();zEe=require("obsidian");U_r();BEe={maxChars:wye,overlap:0,maxBytesTotal:10*1024*1024},Jat=class{constructor(e){this.app=e;this.cache=new Map;this.memoryUsage=0}getCacheKey(e,r){return`${e}:${r.maxChars}:${r.overlap}`}createSplitter(e){return Hat.fromLanguage("markdown",{chunkSize:e.maxChars,chunkOverlap:e.overlap,separators:[`
`))}if(r.protocol==="http:"||r.protocol==="https:")return{type:"url",url:t};throw new Error([`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(`
`))}function hmo(t){let e=[];for(let r of t)if(r._getType()==="tool")if(typeof r.content=="string"){let n=e[e.length-1];n?._getType()==="human"&&Array.isArray(n.content)&&"type"in n.content[0]&&n.content[0].type==="tool_result"?n.content.push({type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}):e.push(new qs({content:[{type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}]}))}else e.push(new qs({content:[{type:"tool_result",...r.content!=null?{content:Ast(r)}:{},tool_use_id:r.tool_call_id}]}));else e.push(r);return e}function Kvr(t){if(t.id===void 0)throw new Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:t.id,name:t.name,input:t.args}}function*gmo(t){let e=["bash_code_execution_tool_result","input_json_delta","server_tool_use","text_editor_code_execution_tool_result","tool_result","tool_use","web_search_result","web_search_tool_result"],r=["text","text_delta"];for(let n of t){Ph(n)&&(yield GT(n,qvr));let o="cache_control"in n?n.cache_control:void 0;if(n.type==="image_url"){let i;typeof n.image_url=="string"?i=Jvr(n.image_url):typeof n.image_url=="object"&&n.image_url!==null&&"url"in n.image_url&&typeof n.image_url.url=="string"&&(i=Jvr(n.image_url.url)),i&&(yield{type:"image",source:i,...o?{cache_control:o}:{}})}else{if(kvr(n))return n;if(n.type==="document")yield{...n,...o?{cache_control:o}:{}};else if($vr(n))yield{type:"thinking",thinking:n.thinking,signature:n.signature,...o?{cache_control:o}:{}};else if(Lvr(n))yield{type:"redacted_thinking",data:n.data,...o?{cache_control:o}:{}};else if(Fvr(n))yield{type:"search_result",title:n.title,source:n.source,..."cache_control"in n&&n.cache_control?{cache_control:n.cache_control}:{},..."citations"in n&&n.citations?{citations:n.citations}:{},content:n.content};else if(r.find(i=>i===n.type)&&"text"in n)yield{type:"text",text:n.text,...o?{cache_control:o}:{},..."citations"in n&&n.citations?{citations:n.citations}:{}};else if(e.find(i=>i===n.type)){let i={...n};if("index"in i&&delete i.index,i.type==="input_json_delta"&&(i.type="tool_use"),"input"in i&&typeof i.input=="string")try{i.input=JSON.parse(i.input)}catch{i.input={}}yield{...i,...o?{cache_control:o}:{}}}else n.type==="container_upload"&&(yield{...n,...o?{cache_control:o}:{}})}}}function Ast(t){let{content:e}=t;return typeof e=="string"?e:Array.from(gmo(e))}function vPe(t){let e=hmo(t),r;e.length>0&&e[0]._getType()==="system"&&(r=t[0].content);let o=(r!==void 0?e.slice(1):e).map(i=>{let a;if(i._getType()==="human")a="user";else if(i._getType()==="ai")a="assistant";else if(i._getType()==="tool")a="user";else throw i._getType()==="system"?new Error("System messages are only permitted as the first passed message."):new Error(`Messagetype"${i.type}"isnotsupported.`);if(kl(i)&&i.response_metadata?.output_version==="v1")return{role:a,content:Hvr(i)};if(kl(i)&&i.tool_calls?.length){if(typeof i.content=="string")return i.content===""?{role:a,content:i.tool_calls.map(Kvr)}:{role:a,content:[{type:"text",text:i.content},...i.tool_calls.map(Kvr)]};{let{content:s}=i;return!i.tool_calls.every(l=>s.find(c=>(c.type==="tool_use"||c.type==="input_json_delta"||c.type==="server_tool_use")&&c.id===l.id))&&console.warn('The "tool_calls" field on a message is only respected if content is a string.'),{role:a,content:Ast(i)}}}else return{role:a,content:Ast(i)}});return{messages:ymo(o),system:r}}function ymo(t){if(!t||t.length<=1)return t;let e=[],r=t[0],n=i=>typeof i=="string"?[{type:"text",text:i}]:i,o=i=>i.role!=="user"||typeof i.content=="string"?!1:Array.isArray(i.content)&&i.content.every(a=>a.type==="tool_result");for(let i=1;i<t.length;i+=1){let a=t[i];o(r)&&o(a)?r={...r,content:[...n(r.content),...n(a.content)]}:(e.push(r),r=a)}return e.push(r),e}var Nst=v(()=>{Uvr();Wvr();ta()});function Gvr(t,e){let r={model_provider:"anthropic"};if(t.type==="message_start"){let{content:n,usage:o,...i}=t.message,a={};for(let[d,f]of Object.entries(i))f!=null&&(a[d]=f);let{input_tokens:s,output_tokens:u,...l}=o??{},c={input_tokens:s,output_tokens:u,total_tokens:s+u,input_token_details:{
`,t}functionDst(t){lete;returnt.status===400&&t.message.includes("tool")?e=wPe(t,"INVALID_TOOL_RESULTS"):t.status===401?e=wPe(t,"MODEL_AUTHENTICATION"):t.status===404?e=wPe(t,"MODEL_NOT_FOUND"):t.status===429?e=wPe(t,"MODEL_RATE_LIMIT"):e=t,e}varYvr=v(()=>{});functionhr(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}functionIe(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)}var$D=v(()=>{});varjst,Qvr=v(()=>{jst=function(){let{crypto:t}=globalThis;if(t?.randomUUID)returnjst=t.randomUUID.bind(t),t.randomUUID();lete=newUint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))}});functionLD(t){returntypeoft=="object"&&t!==null&&("name"int&&t.name==="AbortError"||"message"int&&String(t.message).includes("FetchRequestCanceledException"))}varkae,_9=v(()=>{kae=t=>{if(tinstanceofError)returnt;if(typeoft=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){lete=newError(t.message,t.cause?{cause:t.cause}:{});returnt.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{returnnewError(JSON.stringify(t))}catch{}}returnnewError(t)}});varun,Kh,oy,Pq,v9,w9,S9,C9,x9,T9,O9,E9,P9,zx=v(()=>{_9();un=classextendsError{},Kh=classtextendsun{constructor(e,r,n,o){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=o,this.requestID=o?.get("request-id"),this.error=r}staticmakeMessage(e,r,n){leto=r?.message?typeofr.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;returne&&o?`${e}${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}staticgenerate(e,r,n,o){if(!e||!o)returnnewPq({message:n,cause:kae(r)});leti=r;returne===400?neww9(e,i,n,o):e===401?newS9(e,i,n,o):e===403?newC9(e,i,n,o):e===404?newx9(e,i,n,o):e===409?newT9(e,i,n,o):e===422?newO9(e,i,n,o):e===429?newE9(e,i,n,o):e>=500?newP9(e,i,n,o):newt(e,i,n,o)}},oy=classextendsKh{constructor({message:e}={}){super(void0,void0,e||"Request was aborted.",void0)}},Pq=classextendsKh{constructor({message:e,cause:r}){super(void0,void0,e||"Connection error.",void0),r&&(this.cause=r)}},v9=classextendsPq{constructor({message:e}={}){super({message:e??"Request timed out."})}},w9=classextendsKh{},S9=classextendsKh{},C9=classextendsKh{},x9=classextendsKh{},T9=classextendsKh{},O9=classextendsKh{},E9=classextendsKh{},P9=classextendsKh{}});functionFst(t){returntypeoft!="object"?{}:t??{}}functiontwr(t){if(!t)return!0;for(leteint)return!1;return!0}functionrwr(t,e){returnObject.prototype.hasOwnProperty.call(t,e)}var_mo,ewr,$st,Lst,nwr,SPe,SH=v(()=>{zx();_mo=/^[a-z][a-z0-9+.-]*:/i,ewr=t=>_mo.test(t),$st=t=>($st=Array.isArray,$st(t)),Lst=$st;nwr=(t,e)=>{if(typeofe!="number"||!Number.isInteger(e))thrownewun(`${t} must be an integer`);if(e<0)thrownewun(`${t} must be a positive integer`);returne},SPe=t=>{try{returnJSON.parse(t)}catch{return}}});varowr,iwr=v(()=>{owr=t=>newPromise(e=>setTimeout(e,t))});varMq,kst=v(()=>{Mq="0.65.0"});functionvmo(){returntypeofDeno<"u"&&Deno.build!=null?"deno":typeofEdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeofglobalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}functionSmo(){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+
`,"\r"]);FD.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function Bae(){}function xPe(t,e,r){return!e||TPe[t]>TPe[r]?Bae:e[t].bind(e)}function Gh(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Omo;let n=_wr.get(e);if(n&&n[0]===r)return n[1];let o={error:xPe("error",e,r),warn:xPe("warn",e,r),info:xPe("info",e,r),debug:xPe("debug",e,r)};return _wr.set(e,[r,o]),o}var TPe,Hst,Omo,_wr,kD,OPe=v(()=>{SH();TPe={off:0,error:200,warn:300,info:400,debug:500},Hst=(t,e,r)=>{if(t){if(rwr(TPe,t))return t;Gh(r).warn(`${e}wassetto${JSON.stringify(t)},expectedoneof${JSON.stringify(Object.keys(TPe))}`)}};Omo={error:Bae,warn:Bae,info:Bae,debug:Bae},_wr=new WeakMap;kD=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()==="x-api-key"||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*Emo(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new un("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 un("Attempted to iterate over a response with no body");let r=new Wst,n=new FD,o=qae(t.body);for await(let i of Pmo(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*Pmo(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"?Uae(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let i;for(;(i=bwr(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function Mmo(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var zae,vA,Wst,Jst=v(()=>{$D();zx();M9();Vst();M9();_9();SH();zst();OPe();zx();vA=class t{constructor(e,r,n){this.iterator=e,zae.set(this,void 0),this.controller=r,hr(this,zae,n,"f")}static fromSSEResponse(e,r,n){let o=!1,i=n?Gh(n):console;async function*a(){if(o)throw new un("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let s=!1;try{for await(let u of Emo(e,r)){if(u.event==="completion")try{yield JSON.parse(u.data)}catch(l){throw i.error("Could not parse message into JSON:",u.data),i.error("From chunk:",u.raw),l}if(u.event==="message_start"||u.event==="message_delta"||u.event==="message_stop"||u.event==="content_block_start"||u.event==="content_block_delta"||u.event==="content_block_stop")try{yield JSON.parse(u.data)}catch(l){throw i.error("Could not parse message into JSON:",u.data),i.error("From chunk:",u.raw),l}if(u.event!=="ping"&&u.event==="error")throw new Kh(void 0,SPe(u.data)??u.data,void 0,e.headers)}s=!0}catch(u){if(LD(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 FD,u=qae(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 un("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(LD(u))return;throw u}finally{s||r.abort()}}return new t(a,r,n)}[(zae=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),o=i=>({next:()=>{if(i.length===0){let a=n.next();e.push(a),r.push(a)}return i.shift()}});return[new t(()=>o(e),this.controller,Ie(this,zae,"f")),new t(()=>o(r),this.controller,Ie(this,zae,"f"))]}toReadableStream(){let e=this,r;return Ust({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=Uae(JSON.stringify(o)+`
${d}`)}returna},ib=kmo(Ewr)});varI9,rut=v(()=>{wA();Rq();SA();RPe();R9();I9=classextendsFd{list(e={},r){let{betas:n,...o}=e??{};returnthis._client.getAPIList("/v1/files",P0,{query:o,...r,headers:ia([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},r?.headers])})}delete(e,r={},n){let{betas:o}=r??{};returnthis._client.delete(ib`/v1/files/${e}`,{...n,headers:ia([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString()},n?.headers])})}download(e,r={},n){let{betas:o}=r??{};returnthis._client.get(ib`/v1/files/${e}/content`,{...n,headers:ia([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}retrieveMetadata(e,r={},n){let{betas:o}=r??{};returnthis._client.get(ib`/v1/files/${e}`,{...n,headers:ia([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString()},n?.headers])})}upload(e,r){let{betas:n,...o}=e;returnthis._client.post("/v1/files",wwr({body:o,...r,headers:ia([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},r?.headers])},this._client))}}});varA9,nut=v(()=>{wA();Rq();SA();R9();A9=classextendsFd{retrieve(e,r={},n){let{betas:o}=r??{};returnthis._client.get(ib`/v1/models/${e}?beta=true`,{...n,headers:ia([{...o?.toString()!=null?{"anthropic-beta":o?.toString()}:void0},n?.headers])})}list(e={},r){let{betas:n,...o}=e??{};returnthis._client.getAPIList("/v1/models?beta=true",P0,{query:o,...r,headers:ia([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void0},r?.headers])})}}});varN9,out=v(()=>{zx();M9();Vst();N9=classt{constructor(e,r){this.iterator=e,this.controller=r}async*decoder(){lete=newFD;forawait(letrofthis.iterator)for(letnofe.decode(r))yieldJSON.parse(n);for(letrofe.flush())yieldJSON.parse(r)}[Symbol.asyncIterator](){returnthis.decoder()}staticfromResponse(e,r){if(!e.body)throwr.abort(),typeofglobalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?newun("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):newun("Attempted to iterate over a response with no body");returnnewt(qae(e.body),r)}}});varJae=v(()=>{zx()});varD9,iut=v(()=>{wA();Rq();SA();out();Jae();R9();D9=classextendsFd{create(e,r){let{betas:n,...o}=e;returnthis._client.post("/v1/messages/batches?beta=true",{body:o,...r,headers:ia([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}retrieve(e,r={},n){let{betas:o}=r??{};returnthis._client.get(ib`/v1/messages/batches/${e}?beta=true`,{...n,headers:ia([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString()},n?.headers])})}list(e={},r){let{betas:n,...o}=e??{};returnthis._client.getAPIList("/v1/messages/batches?beta=true",P0,{query:o,...r,headers:ia([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}delete(e,r={},n){let{betas:o}=r??{};returnthis._client.delete(ib`/v1/messages/batches/${e}?beta=true`,{...n,headers:ia([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString()},n?.headers])})}cancel(e,r={},n){let{betas:o}=r??{};returnthis._client.post(ib`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:ia([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString()},n?.headers])})}asyncresults(e,r={},n){leto=awaitthis.retrieve(e);if(!o.results_url)thrownewun(`No batch \`results_url\`; Has it finished processing? ${o.processing_status} - ${o.id}`);let{betas:i}=r??{};returnthis._client.get(o.results_url,{...n,headers:ia([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((a,s)=>N9.fromResponse(s.response,s.controller))}}});varaut=v(()=>{Jst()});varzmo,j9,Vmo,Hmo,APe,sut=v(()=>{zmo=t=>{lete=0,r=[];for(;e<t.length;){letn=t[e];if(n==="\\"){e++;continue}if(n==="{"){r.push({type:"brace",value:"{"}),e++;continue}if(n==="}"){r.push({type:"brace",value:"}"}),e++;continue}if(n==="["){r.push({type:"paren",value:"["}),e+
Pleasemigratetoanewermodel.Visithttps://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let i=this._client._options.timeout;if(!o.stream&&i==null){let a=UPe[o.model]??void 0;i=this._client.calculateNonstreamingTimeout(o.max_tokens,a)}return this._client.post("/v1/messages?beta=true",{body:o,timeout:i??6e5,...r,headers:ia([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers]),stream:e.stream??!1})}stream(e,r){return qPe.createMessage(this,e,r)}countTokens(e,r){let{betas:n,...o}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:o,...r,headers:ia([{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString()},r?.headers])})}toolRunner(e,r){return new F9(this._client,e,r)}};Nq.Batches=D9;Nq.BetaToolRunner=F9});var xA,gut=v(()=>{wA();rut();rut();nut();nut();hut();hut();xA=class extends Fd{constructor(){super(...arguments),this.models=new A9(this._client),this.messages=new Nq(this._client),this.files=new I9(this._client)}};xA.Models=A9;xA.Messages=Nq;xA.Files=I9});var OH,yut=v(()=>{wA();SA();OH=class extends Fd{create(e,r){let{betas:n,...o}=e;return this._client.post("/v1/complete",{body:o,timeout:this._client._options.timeout??6e5,...r,headers:ia([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers]),stream:e.stream??!1})}}});function Fwr(t){return t.type==="tool_use"||t.type==="server_tool_use"}var R0,Dq,tse,zPe,rse,nse,VPe,ose,BD,ise,HPe,WPe,k9,JPe,KPe,but,jwr,_ut,vut,wut,Sut,$wr,Lwr,GPe,kwr=v(()=>{$D();_9();Jae();aut();sut();Lwr="__json_buf";GPe=class t{constructor(){R0.add(this),this.messages=[],this.receivedMessages=[],Dq.set(this,void 0),this.controller=new AbortController,tse.set(this,void 0),zPe.set(this,()=>{}),rse.set(this,()=>{}),nse.set(this,void 0),VPe.set(this,()=>{}),ose.set(this,()=>{}),BD.set(this,{}),ise.set(this,!1),HPe.set(this,!1),WPe.set(this,!1),k9.set(this,!1),JPe.set(this,void 0),KPe.set(this,void 0),_ut.set(this,e=>{if(hr(this,HPe,!0,"f"),LD(e)&&(e=new oy),e instanceof oy)return hr(this,WPe,!0,"f"),this._emit("abort",e);if(e instanceof un)return this._emit("error",e);if(e instanceof Error){let r=new un(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new un(String(e)))}),hr(this,tse,new Promise((e,r)=>{hr(this,zPe,e,"f"),hr(this,rse,r,"f")}),"f"),hr(this,nse,new Promise((e,r)=>{hr(this,VPe,e,"f"),hr(this,ose,r,"f")}),"f"),Ie(this,tse,"f").catch(()=>{}),Ie(this,nse,"f").catch(()=>{})}get response(){return Ie(this,JPe,"f")}get request_id(){return Ie(this,KPe,"f")}async withResponse(){let e=await Ie(this,tse,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let r=new t;return r._run(()=>r._fromReadableStream(e)),r}static createMessage(e,r,n){let o=new t;for(let i of r.messages)o._addMessageParam(i);return o._run(()=>o._createMessage(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},Ie(this,_ut,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,r=!0){this.receivedMessages.push(e),r&&this._emit("message",e)}async _createMessage(e,r,n){let o=n?.signal,i;o&&(o.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),o.addEventListener("abort",i));try{Ie(this,R0,"m",vut).call(this);let{response:a,data:s}=await e.create({...r,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(a);for await(let u of s)Ie(this,R0,"m",wut).call(this,u);if(s.controller.signal?.aborted)throw new oy;Ie(this,R0,"m",Sut).call(this)}finally{o&&i&&o.removeEventListener("abort",i)}}_connected(e){this.ended||(hr(this,JPe,e,"f"),hr(this,KPe,e?.headers.get("request-id"),"f"),Ie(this,zPe,"f").call(this,e),this._emit("connect"))}get ended(){return Ie(this,ise,"f")}get errored(){return Ie(this,HPe,"f")}get aborted(){return Ie(this,WPe,"f")}abort(){this.controller.abort()}on(e,r){return(Ie(this,BD,"f")[e]||(Ie(this,BD,"f")[e]=[])).pu
Pleasemigratetoanewermodel.Visithttps://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let n=this._client._options.timeout;if(!e.stream&&n==null){let o=UPe[e.model]??void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,o)}return this._client.post("/v1/messages",{body:e,timeout:n??6e5,...r,stream:e.stream??!1})}stream(e,r){return GPe.createMessage(this,e,r)}countTokens(e,r){return this._client.post("/v1/messages/count_tokens",{body:e,...r})}},qwr={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"};jq.Batches=q9});var EH,Tut=v(()=>{wA();Rq();SA();R9();EH=class extends Fd{retrieve(e,r={},n){let{betas:o}=r??{};return this._client.get(ib`/v1/models/${e}`,{...n,headers:ia([{...o?.toString()!=null?{"anthropic-beta":o?.toString()}:void 0},n?.headers])})}list(e={},r){let{betas:n,...o}=e??{};return this._client.getAPIList("/v1/models",P0,{query:o,...r,headers:ia([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers])})}}});var Uwr=v(()=>{xwr();gut();yut();xut();Tut()});var ase,Bwr=v(()=>{ase=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()}});var Out,Eut,XPe,zwr,Vwr,Hwr,Tc,TA,Put=v(()=>{$D();Qvr();SH();iwr();_9();qst();M9();mwr();kst();zx();Rq();tut();Uwr();PPe();yut();Tut();gut();xut();qst();SA();Bwr();OPe();SH();Vwr="\\n\\nHuman:",Hwr="\\n\\nAssistant:",Tc=class{constructor({baseURL:e=ase("ANTHROPIC_BASE_URL"),apiKey:r=ase("ANTHROPIC_API_KEY")??null,authToken:n=ase("ANTHROPIC_AUTH_TOKEN")??null,...o}={}){Out.add(this),XPe.set(this,void 0);let i={apiKey:r,authToken:n,...o,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&lwr())throw new un(`It looks like you're running in a browser-like environment.
`);this.baseURL=i.baseURL,this.timeout=i.timeout??Eut.DEFAULT_TIMEOUT,this.logger=i.logger??console;leta="warn";this.logLevel=a,this.logLevel=Hst(i.logLevel,"ClientOptions.logLevel",this)??Hst(ase("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??dwr(),hr(this,XPe,pwr,"f"),this._options=i,this.apiKey=r,this.authToken=n}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,authToken:this.authToken,...e})}defaultQuery(){returnthis._options.defaultQuery}validateHeaders({values:e,nulls:r}){if(!(this.apiKey&&e.get("x-api-key"))&&!r.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!r.has("authorization"))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')}asyncauthHeaders(e){returnia([awaitthis.apiKeyAuth(e),awaitthis.bearerAuth(e)])}asyncapiKeyAuth(e){if(this.apiKey!=null)returnia([{"X-Api-Key":this.apiKey}])}asyncbearerAuth(e){if(this.authToken!=null)returnia([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){returnObject.entries(e).filter(([r,n])=>typeofn<"u").map(([r,n])=>{if(typeofn=="string"||typeofn=="number"||typeofn=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(r)}=`;thrownewun(`Cannot stringify type ${typeofn}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${Mq}`}defaultIdempotencyKey(){return`stainless-node-retry-${jst()}`}makeStatusError(e,r,n,o){returnKh.generate(e,r,n,o)}buildURL(e,r,n){leto=!Ie(this,Out,"m",zwr).call(this)&&n||this.baseURL,i=ewr(e)?newURL(e):newURL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();returntwr(a)||(r={...a,...r}),typeofr=="object"&&r&&!Array.isArray(r)&&(i.search=this.stringifyQuery(r)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)thrownewun("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return600*1e3}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){returnnewCH(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(Gh(this).debug(`[${l}] sending request`,kD({retryOfRequestLogID:n,method:o.method,url:s,options:o,headers:a.headers})),o.signal?.aborted)thrownewoy;letf=newAbortController,p=awaitthis.fetchWithTimeout(s,a,u,f).catch(kae),m=Date.now();if(pinstanceofglobalThis.Error){letg=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)thrownewoy;letb=LD(p)||/timed? ?out/i.test(String(p)+("cause"inp?String(p.cause):""));if(r)returnGh(this).info(`[${l}] connection ${b?"timed out":"failed"} - ${g}`),Gh(this).debug(`[${l}] connection ${b?"timed out":"failed"} (${g})`,kD({retryOfRequestLogID:n,url:s,durationMs:m-d,messag
Received: ${JSON.stringify(i,null,2)}`)};if(typeofi=="string")returni;if(Array.isArray(i)){letu=e(a),l=[];returni.forEach(c=>{if(c.type==="text"||c.type==="image_url")l.push(s(c,u));elsethrownewError('Mistral only supports types "text" or "image_url" for complex message types.')}),l}thrownewError(`Message content must be a string or an array.
Received: ${JSON.stringify(i,null,2)}`)},n=i=>{if(kl(i)&&i.tool_calls?.length)returni.tool_calls.map(a=>({...a,id:bse(a.id??"")})).map(Jk)},o=newSet;for(letioft)"tool_call_id"ini&&typeofi.tool_call_id=="string"&&o.add(bse(i.tool_call_id));returnt.flatMap(i=>{leta=n(i),s=r(i.content,i.getType());if("tool_call_id"ini&&typeofi.tool_call_id=="string")return[{role:e(i.getType()),content:s,name:i.name,toolCallId:bse(i.tool_call_id)}];if(kl(i)){if(a===void0)return[{role:e(i.getType()),content:s}];{letu=a.filter(l=>o.has(bse(l.id??"")));returnu.length===0?typeofs=="string"&&s.trim()===""||Array.isArray(s)&&s.length===0?[]:[{role:e(i.getType()),content:s}]:[{role:e(i.getType()),toolCalls:u}]}}return[{role:e(i.getType()),content:s}]})}functionKQo(t,e){let{message:r}=t;if(r===void0)thrownewError("No message found in response");letn=[];"toolCalls"inr&&Array.isArray(r.toolCalls)&&(n=r.toolCalls);leto=ilt(r.content);switch(r.role){case"assistant":{leti=[],a=[];for(letsofn)try{letu=Ix(s,{returnId:!0});i.push({...u,id:u.id??cMe().replace(/-/g,"")})}catch(u){a.push(_0(s,u.message))}returnnewPn({content:o,tool_calls:i,invalid_tool_calls:a,additional_kwargs:{},usage_metadata:e?{input_tokens:e.promptTokens,output_tokens:e.completionTokens,total_tokens:e.totalTokens}:void0})}default:returnnewqs({content:o})}}functionGQo(t,e){if(!t.content&&!t.toolCalls)returne?newEr({content:"",usage_metadata:e?{input_tokens:e.promptTokens,output_tokens:e.completionTokens,total_tokens:e.totalTokens}:void0}):null;letr=t.toolCalls?.length?t.toolCalls?.map((s,u)=>({...s,index:u,id:s.id??cMe().replace(/-/g,""),type:"function"})):void0,n="assistant";t.role&&(n=t.role);leto=ilt(t.content),i,a=[];if(r!==void0)for(letsofr){letu=s.function?.arguments,l=u===void0||typeofu=="string"?u:JSON.stringify(u);a.push({name:s.function?.name,args:l,id:s.id,index:s.index,type:"tool_call_chunk"})}elsei={};returnn==="user"?newrw({content:o}):n==="assistant"?newEr({content:o,tool_call_chunks:a,additional_kwargs:i,usage_metadata:e?{input_tokens:e.promptTokens,output_tokens:e.completionTokens,total_tokens:e.totalTokens}:void0}):n==="tool"?new_S({content:o,additional_kwargs:i,tool_call_id:r?.[0].id??""}):n==="function"?newtw({content:o,additional_kwargs:i}):newew({content:o,role:n})}functionozr(t){if(!(!t||!t.length))returnt.map(e=>{if("function"ine)return{type:e.type??"function",function:e.function};if(Xg(e)){letr=e.description??`Tool: ${e.name}`;return{type:"function",function:{name:e.name,description:r,parameters:Ii(e.schema)?Ci(e.schema):e.schema}}}thrownewError(`Unknown tool type passed to ChatMistral: ${JSON.stringify(e,null,2)}`)})}varizr,azr,Qft,szr=v(()=>{PSr();DSr();izr=$(nzr(),1),azr=$(X9(),1);ta();YI();Ed();Jz();au();fO();PV();sw();Ny();pD();uv();Qft=classextendsjd{constructor(e){super(e??{});x(this,"lc_namespace",["langchain","chat_models","mistralai"]);x(this,"model","mistral-small-latest");x(this,"apiKey");x(this,"endpoint");x(this,"serverURL");x(this,"temperature",.7);x(this,"streaming",!1);x(this,"topP",1);x(this,"maxTokens");x(this,"safeMode",!1);x(this,"safePrompt",!1);x(this,"randomSeed");x(this,"seed");x(this,"maxRetries");x(this,"lc_serializable",!0);x(this,"streamUsage",!0);x(this,"beforeRequestHooks");x(this,"requestErrorHooks");x(this,"responseHooks");x(this,"httpClient");x(this,"presencePenalty");x(this,"frequencyPenalty");x(this,"numCompletions");letr=e?.apiKey??Xr("MISTRAL_API_KEY");if(!r)thrownewError("API key MISTRAL_API_KEY is missing for MistralAI, but it is required.");this.apiKey=r,this.streaming=e?.streaming??this.streaming,this.serverURL=e?.serverURL??this.serverURL,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.maxTokens=e?.maxTokens??this.maxTokens,this.safePrompt=e?.safePrompt??this.safePrompt,this.randomSeed=e?.seed??e?.randomSeed??this.seed,this.seed=this.randomSeed,this.maxRetries=e?.maxRetries,this.httpClient=e?.httpClient,this.model=e?.model??e?.modelName??this.model,this.streamUsage=e?.streamUsage??this.streamUsage,this.beforeRequestHooks=
`,"\r"]);P3.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function mpt(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 Izr=v(()=>{});async function*dei(t,e){if(!t.body)throw e.abort(),new jr("Attempted to iterate over a response with no body");let r=new hpt,n=new P3,o=mpt(t.body);for await(let i of fei(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*fei(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=Mzr(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function pei(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var YA,hpt,vDe=v(()=>{Gue();Kw();Rzr();Izr();Xi();Kw();YA=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 dei(e,r))if(!i){if(a.data.startsWith("[DONE]")){i=!0;continue}if(a.event===null||a.event.startsWith("response.")||a.event.startsWith("transcript.")){let s;try{s=JSON.parse(a.data)}catch(u){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),u}if(s&&s.error)throw new Zm(void 0,s.error,void 0,gpt(e.headers));yield s}else{let s;try{s=JSON.parse(a.data)}catch(u){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),u}if(a.event=="error")throw new Zm(void 0,s.error,s.message,void 0);yield{event:a.event,data:s}}}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 P3,s=mpt(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 upt({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]=pei(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function _pt(t,e,r){if(t=await t,Nzr(t))return t;if(Azr(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=ole(o)?[await o.arrayBuffer()]:[o];return new hDe(i,e,r)}let n=await hei(t);if(e||(e=yei(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new hDe(n,e,r)}async function hei(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(ole(t))e.push(await t.arrayBuffer());else if(bei(t))for await(let r of t)e.push(r);else throw new Error(`Unexpecteddatatype:${typeoft};constructor:${t?.constructor?.name};props:${gei(t)}`);return e}function gei(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function yei(t){return ypt(t.name)||ypt(t.filename)||ypt(t.path)?.split(/[\\/]/).pop()}var Azr,Nzr,ole,mei,ypt,bei,vpt,Q0,Dzr,bpt,wDe=v(()=>{Gue();Gue();Azr=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",Nzr=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&ole(t),ole=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",mei=t=>Nzr(t)||Azr(t)||dpt(t);ypt=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},bei=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",vpt=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody",Q0=async t=>{let e=await Dzr(t.body);return lpt(e,t)},Dzr=async t=>{let e=new spt;return await Promise.all(Object.entries(t||{}).map(([r,n])=>bpt(e,r,n))),e},bpt=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Receivednullfor"${e}";topassnullinFormData,youmustusethestring'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(mei(r)){let n=await _pt(r);t.append(e,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>bpt(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>bpt(t,`${e}[${n}]`,o)));else throw new TypeError(`Invalidvaluegiventoform,expectedastring,number,boolean,object,Array,FileorBlobbutgot${r}instead`)}}});async function qzr(t){let{response:e}=t;if(t.options.stream)return g$("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):YA.fromSSEResponse(e,t.controller);if(e.status===204)return null;if(t.options.__binaryResponse)return e;let n=e.headers.get("content-type")?.split(";")[0]?.trim();if(n?.includes("application/json")||n?.endsWith("+json")){let a=await e.json();return g$("response",e.status,e.url,e.headers,a),Uzr(a,e)}let i=await e.text();return g$("response",e.status,e.url,e.headers,i),i}function Uzr(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}function xei(){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 Bzr(t){if(!t)return!0;for(let e in t)return!1;return!0}function zzr(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Fzr(t,e){fo
\r `.includes(t[n]);)n++};returna()},Hpt=t=>kei(t,rg.ALL^rg.NUM)});functionUei(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)thrownewjr(`missing finish_reason for choice ${d}`);let{content:m=null,function_call:h,tool_calls:y,...g}=l,b=l.role;if(!b)thrownewjr(`missing role for choice ${d}`);if(h){let{arguments:_,name:w}=h;if(_==null)thrownewjr(`missing function_call.arguments for choice ${d}`);if(!w)thrownewjr(`missing function_call.name for choice ${d}`);return{...p,message:{content:m,function_call:{arguments:_,name:w},role:b,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}returny?{...p,index:d,finish_reason:c,logprobs:f,message:{...g,role:b,content:m,refusal:l.refusal??null,tool_calls:y.map((_,w)=>{let{function:T,type:O,id:E,...P}=_,{arguments:R,name:I,...N}=T||{};if(E==null)thrownewjr(`missing choices[${d}].tool_calls[${w}].id
${$De(t)}`);return{...P,id:E,type:O,function:{...N,name:I,arguments:R}}})}}:{...p,message:{...g,content:m,role:b,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}),created:o,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};returnXzr(u,e)}function$De(t){returnJSON.stringify(t)}vareX,xu,Ym,v$,tX,IU,Wpt,DDe,Jpt,Kpt,Gpt,jDe,Xpt,n4r,rX,Zpt=v(()=>{Kw();Bpt();vDe();hle();r4r();eX=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},xu=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)},rX=classtextendsQ7{constructor(e){super(),Ym.add(this),v$.set(this,void0),tX.set(this,void0),IU.set(this,void0),eX(this,v$,e,"f"),eX(this,tX,[],"f")}getcurrentChatCompletionSnapshot(){returnxu(this,IU,"f")}staticfromReadableStream(e){letr=newt(null);returnr._run(()=>r._fromReadableStream(e)),r}staticcreateChatCompletion(e,r,n){leto=newt(r);returno._run(()=>o._runChatCompletion(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async_createChatCompletion(e,r,n){super._createChatCompletion;leto=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),xu(this,Ym,"m",Wpt).call(this);leti=awaite.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();forawait(letaofi)xu(this,Ym,"m",Jpt).call(this,a);if(i.controller.signal?.aborted)thrownewSm;returnthis._addChatCompletion(xu(this,Ym,"m",jDe).call(this))}async_fromReadableStream(e,r){letn=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),xu(this,Ym,"m",Wpt).call(this),this._connected();leto=YA.fromReadableStream(e,this.controller),i;forawait(letaofo)i&&i!==a.id&&this._addChatCompletion(xu(this,Ym,"m",jDe).call(this)),xu(this,Ym,"m",Jpt).call(this,a),i=a.id;if(o.controller.signal?.aborted)thrownewSm;returnthis._addChatCompletion(xu(this,Ym,"m",jDe).call(this))}[(v$=newWeakMap,tX=newWeakMap,IU=newWeakMap,Ym=newWeakSet,Wpt=function(){this.ended||eX(this,IU,void0,"f")},DDe=function(r){letn=xu(this,tX,"f")[r.index];returnn||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:newSet,current_tool_call_index:null},xu(this,tX,"f")[r.index]=n,n)},Jpt=function(r){if(this.ended)return;letn=xu(this,Ym,"m",n4r).call(this,r);this._emit("chunk",r,n);for(letoofr.choices){leti=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??[]});leta=xu(this,Ym,"m",DDe).call(this,i);i.finish_reason&&(xu(this,Ym,"m",Gpt).call(this,i),a.current_tool_call_index!=null&&xu(this,Ym,"m",Kpt).call(this,i,a.current_tool_call_index));for(letsofo.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(xu(this,Ym,"m",Gpt).call(this,i),a.current_tool_call_index!=null&&xu(this,Ym,"m",Kpt).call(this,i,a.current_tool_call_index)),a.cu
`)),i!==void0&&(u.max_tokens=i),this.anthropicVersion&&(u.anthropic_version=this.anthropicVersion),this.enableThinking?(u.thinking={type:"enabled",budget_tokens:2048},u.temperature=1,F("[BedrockChatModel] Enabled thinking mode for Claude model with temperature=1")):a!==void0&&(u.temperature=a),s!==void0&&(u.top_p=s),u}normaliseMessageContent(e){let{content:r}=e;returntypeofr=="string"?r:Array.isArray(r)?r.some(o=>typeofo=="object"&&o!==null&&(o.type==="image_url"||o.type==="image"))?r.map(o=>{if(typeofo=="string")return{type:"text",text:o};if(typeofo=="object"&&o!==null){if(o.type==="text"||o.type==="image_url"||o.type==="image")returno;if("text"ino&&typeofo.text=="string")return{type:"text",text:o.text};if("content"ino&&typeofo.content=="string")return{type:"text",text:o.content}}returnnull}).filter(o=>o!==null):r.map(o=>{if(typeofo=="string")returno;if(typeofo=="object"&&o!==null){if("text"ino&&typeofo.text=="string")returno.text;if("content"ino&&typeofo.content=="string")returno.content}return""}).join(""):typeofr=="object"&&r!==null&&"text"inr?r.text??"":""}extractText(e){returntypeofe?.outputText=="string"?e.outputText:Array.isArray(e?.content)?e.content.map(r=>{if(!r)return"";if(typeofr=="string")returnr;if(typeofr=="object"){if(typeofr.text=="string")returnr.text;if(r.text&&typeofr.text=="object"&&"text"inr.text)returnr.text.text??""}return""}).join(""):typeofe?.completion=="string"?e.completion:typeofe?.resultText=="string"?e.resultText:""}}});functionP4r(t){lete,r,n,o,i,a,s;returnu(),{feed:l,reset:u};functionu(){e=!0,r="",n=0,o=-1,i=void0,a=void0,s=""}functionl(d){r=r?r+d:d,e&&mti(r)&&(r=r.slice(M4r.length)),e=!1;letf=r.length,p=0,m=!1;for(;p<f;){m&&(r[p]===`
`;elseif(y==="event")a=w;elseif(y==="id"&&!w.includes("\0"))i=w;elseif(y==="retry"){letT=parseInt(w,10);Number.isNaN(T)||t({type:"reconnect-interval",value:T})}}}functionmti(t){returnM4r.every((e,r)=>t.charCodeAt(r)===e)}varM4r,R4r=v(()=>{M4r=[239,187,191]});functionRmt(t){returntinstanceofeC||tinstanceofError&&t.name==="AuthCancelledError"}vareC,Imt=v(()=>{eC=classtextendsError{constructor(r="Authentication cancelled by user."){super(r);this.name="AuthCancelledError";Object.setPrototypeOf(this,t.prototype)}}});varSle,I4r,hti,gti,yti,j4r,A4r,bti,_ti,N4r,vti,D4r,BU,KDe=v(()=>{Ye();vO();Sle=require("obsidian");R4r();Imt();I4r="Iv1.b507a08c87ecfe98",hti="https://github.com/login/device/code",gti="https://github.com/login/oauth/access_token",yti="https://api.github.com/copilot_internal/v2/token",j4r="https://api.githubcopilot.com",A4r=`${j4r}/chat/completions`,bti=`${j4r}/models`,_ti=60*1e3,N4r=60*60*1e3,vti=3,D4r={401:"Authentication failed - token may be expired",403:"Access denied - check your Copilot subscription",429:"Rate limited - please wait before retrying"},BU=classt{constructor(){this.abortController=null;this.refreshPromise=null;this.refreshAttempts=0;this.authGeneration=0}staticgetInstance(){returnt.instance||(t.instance=newt),t.instance}getAuthState(){lete=te(),r=!!e.githubCopilotAccessToken,n=!!e.githubCopilotToken,o=e.githubCopilotTokenExpiresAt,a=!(typeofo=="number"&&o>0)||o<Date.now();returnn&&!a||n&&r?{status:"authenticated"}:r?{status:"pending"}:{status:"idle"}}isAuthenticated(){returnthis.getAuthState().status==="authenticated"}asyncstartDeviceCodeFlow(){lete=newURLSearchParams({client_id:I4r,scope:"read:user"}).toString(),r=await(0,Sle.requestUrl)({url:hti,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:e,throw:!1}),n=this.getRequestUrlJson(r);if(r.status!==200){leti=typeofn.error_description=="string"?n.error_description:typeofn.error=="string"?n.error:"";thrownewError(i?`Failed to get device code: ${i}`:`Failed to get device code: ${r.status}`)}if(typeofn.device_code!="string"||typeofn.user_code!="string"||typeofn.expires_in!="number")thrownewError("Invalid device code response from GitHub");leto=typeofn.verification_uri=="string"?n.verification_uri:typeofn.verification_uri_complete=="string"?n.verification_uri_complete:null;if(!o)thrownewError("Invalid device code response from GitHub: missing verification URI");return{deviceCode:n.device_code,userCode:n.user_code,verificationUri:o,expiresIn:n.expires_in,interval:typeofn.interval=="number"&&n.interval>0?n.interval:5}}asyncpollForAccessToken(e,r,n,o){leti=this.authGeneration;this.abortPolling();leta=newAbortController;this.abortController=a;lets=Date.now()+n*1e3,u=0;try{for(;Date.now()<s;){if(a.signal.aborted||this.authGeneration!==i)throwneweC;if(u++,o?.(u),awaitthis.delay(r*1e3,a.signal),a.signal.aborted||this.authGeneration!==i)throwneweC;letl=newURLSearchParams({client_id:I4r,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}).toString(),c=await(0,Sle.requestUrl)({url:gti,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:l,throw:!1});if(a.signal.aborted||this.authGeneration!==i)throwneweC;letd=this.getRequestUrlJson(c);if(c.status!==200){letf=typeofd.error_description=="string"?d.error_description:typeofd.error=="string"?d.error:`HTTP ${c.status}`;thrownewError(`Token request failed: ${f}`)}if(typeofd.access_token=="string"&&d.access_token){if(a.signal.aborted||this.authGeneration!==i)throwneweC;returnF_({githubCopilotAccessToken:d.access_token}),d.access_token}if(d.error!=="authorization_pending"){if(d.error==="slow_down"){r+=5;continue}if(d.error==="device_code_expired"||d.error==="expired_token")thrownewError("Device code expired. Please restart authentication.");if(d.error==="access_denied")thrownewError("Authorization denied by user.");if(typeofd.error=="string"&&d.error)thrownewError(typeofd.error_description=="string"&&d.error_des
withoutCORSError:`+zr(n)+`
withCORSError:`+zr(o);throw new Error(i)}}}findModelByName(e){return te().activeModels.find(n=>n.name===e)}};bd.ANTHROPIC_THINKING_BUDGET_TOKENS=2048,bd.REASONING_MODEL_TEMPERATURE=1;tC=bd});var Dmt={};En(Dmt,{TieredLexicalRetriever:()=>uT});async function Cti(){try{if(!Amt){let e=await Promise.resolve().then(()=>(CX(),F4r));Amt=()=>e.default.getInstance()}return Amt().getChatModel()}catch{return null}}var Nmt,Amt,uT,xX=v(()=>{Xe();Ye();Bt();ND();f9();Nmt=require("obsidian");Oae();wH();Amt=null;uT=class extends Ux{constructor(r,n){super();this.app=r;this.options=n;this.lc_namespace=["tiered_lexical_retriever"];this.lastQueryExpansion=null;this.searchCore=new yPe(r,Cti),this.chunkManager=Sq(r)}getLastQueryExpansion(){return this.lastQueryExpansion}async getRelevantDocuments(r,n){try{let i=kS(r,this.app.vault).map(f=>f.basename),a=[...new Set([...this.options.salientTerms,...i])];te().debug&&F("TieredLexicalRetriever: Starting search",{query:r,salientTerms:a,maxK:this.options.maxK});let s=te(),u=await this.searchCore.retrieve(r,{maxResults:this.options.maxK,salientTerms:a,enableLexicalBoosts:s.enableLexicalBoosts,preExpandedQuery:this.options.preExpandedQuery}),l=u.results;this.lastQueryExpansion=u.queryExpansion;let c=await this.convertToDocuments(l),d=this.sortResults(c);return te().debug&&F("TieredLexicalRetriever: Search complete",{totalResults:d.length,searchResults:l.length}),d}catch(o){return Te("TieredLexicalRetriever: Error during search",o),[]}}async convertToDocuments(r){let n=[];for(let o of r)try{if(o.id.includes("#")){let[a]=o.id.split("#"),s=this.app.vault.getAbstractFileByPath(a);if(!s||!(s instanceof Nmt.TFile))continue;let u="",l=this.chunkManager;if(typeof l.getChunkText=="function"?u=await l.getChunkText(o.id):typeof l.getChunkTextSync=="function"&&(u=l.getChunkTextSync(o.id)||""),!u)continue;let c=this.app.metadataCache.getFileCache(s);n.push(new tl({pageContent:u,metadata:{path:a,chunkId:o.id,title:s.basename,mtime:s.stat.mtime,ctime:s.stat.ctime,tags:c?.tags?.map(d=>d.tag)||[],score:o.score,rerank_score:o.score,engine:o.engine||"chunk-v3",includeInContext:o.score>(this.options.minSimilarityScore||.1),explanation:o.explanation,isChunk:!0}}))}else{let a=this.app.vault.getAbstractFileByPath(o.id);if(!a||!(a instanceof Nmt.TFile))continue;let s=await this.app.vault.cachedRead(a);if(!s)continue;let u=this.app.metadataCache.getFileCache(a);n.push(new tl({pageContent:s,metadata:{path:o.id,title:a.basename,mtime:a.stat.mtime,ctime:a.stat.ctime,tags:u?.tags?.map(l=>l.tag)||[],score:o.score,rerank_score:o.score,engine:o.engine||"v3",includeInContext:o.score>(this.options.minSimilarityScore||.1),explanation:o.explanation,isChunk:!1}}))}}catch(i){Te(`TieredLexicalRetriever:Failedtoconvertresult${o.id}`,i)}return F(`TieredLexicalRetriever:Converted${n.length}resultstoDocuments`),n}sortResults(r){return r.sort((n,o)=>{let i=n.metadata.score||0,s=(o.metadata.score||0)-i;if(Math.abs(s)>.01)return s;if(n.metadata.isChunk&&o.metadata.isChunk&&n.metadata.path===o.metadata.path){let u=parseInt(n.metadata.chunkId?.split("#")[1]||"0"),l=parseInt(o.metadata.chunkId?.split("#")[1]||"0");return u-l}return s})}}});var k4r={};En(k4r,{MergedSemanticRetriever:()=>K3});var zU,K3,jmt=v(()=>{_Pe();wH();xX();ND();f9();zU=class zU extends Ux{constructor(r,n,o){super();this.app=r;this.options=n;this.lc_namespace=["merged_semantic_retriever"];this.originalMaxK=Math.max(1,n.maxK),this.returnAll=!!n.returnAll;let i=this.returnAll?ec:Math.min(this.originalMaxK*2,ec),a={...n,maxK:i,returnAll:this.returnAll};this.lexicalRetriever=new uT(r,a);let s=this.returnAll?ec:Math.min(this.originalMaxK*2,ec);this.semanticRetriever=o||new $ae({minSimilarityScore:n.minSimilarityScore??.1,maxK:s,salientTerms:n.salientTerms,timeRange:n.timeRange,textWeight:n.textWeight,returnAll:this.returnAll,useRerankerThreshold:n.useRerankerThreshold})}async getRelevantDocuments(r){let[n,o]=await Promise.all([this.lexicalRetriever.getRelevantDocuments(r),this.semanticRetriever.getRelevantDocuments(r)]),i=new Map;for(let u of n)this.insertResult(i,u,"lexic
{context}`,Gii=[LS.fromTemplate(Kii),$_.fromTemplate("{question}")],Xii=Ah.fromMessages(Gii),T3r=new iZ(Jii,[[aZ,Xii]])});var E3r=v(()=>{FS();e$e()});var P3r=v(()=>{FS();e$e()});function M3r(t,e={}){let{prompt:r=T3r.getPrompt(t),verbose:n}=e,o=new ag({prompt:r,llm:t,verbose:n});return new Zje({llmChain:o,verbose:n})}var R3r=v(()=>{cW();Xce();O3r();E3r();P3r()});var A3r={};En(A3r,{VectorDBQAChain:()=>Zii});var Zii,N3r=v(()=>{nZ();R3r();Zii=class I3r extends hb{constructor(r){super(r);x(this,"k",4);x(this,"inputKey","query");x(this,"vectorstore");x(this,"combineDocumentsChain");x(this,"returnSourceDocuments",!1);this.vectorstore=r.vectorstore,this.combineDocumentsChain=r.combineDocumentsChain,this.inputKey=r.inputKey??this.inputKey,this.k=r.k??this.k,this.returnSourceDocuments=r.returnSourceDocuments??this.returnSourceDocuments}static lc_name(){return"VectorDBQAChain"}get inputKeys(){return[this.inputKey]}get outputKeys(){return this.combineDocumentsChain.outputKeys.concat(this.returnSourceDocuments?["sourceDocuments"]:[])}async _call(r,n){if(!(this.inputKey in r))throw new Error(`Question key ${this.inputKey} not found.`);let o=r[this.inputKey],i=await this.vectorstore.similaritySearch(o,this.k,r.filter,n?.getChild("vectorstore")),a={question:o,input_documents:i},s=await this.combineDocumentsChain.call(a,n?.getChild("combine_documents"));return this.returnSourceDocuments?{...s,sourceDocuments:i}:s}_chainType(){return"vector_db_qa"}static async deserialize(r,n){if(!("vectorstore"in n))throw new Error("Need to pass in a vectorstore to deserialize VectorDBQAChain");let{vectorstore:o}=n;if(!r.combine_documents_chain)throw new Error("VectorDBQAChain must have combine_documents_chain in serialized data");return new I3r({combineDocumentsChain:await hb.deserialize(r.combine_documents_chain),k:r.k,vectorstore:o})}serialize(){return{_type:this._chainType(),combine_documents_chain:this.combineDocumentsChain.serialize(),k:this.k}}static fromLLM(r,n,o){let i=M3r(r);return new this({vectorstore:n,combineDocumentsChain:i,...o})}}});var D3r,j3r,Yii,$3r,L3r=v(()=>{FS();D3r=`You are given the below API Documentation:
Using this documentation, generate the full API url to call for answering the user question.
You should build the API url in order to get a response that is as short as possible, while still getting the necessary information to answer the question. Pay attention to deliberately exclude any unnecessary pieces of data in the API call.
`,this.references=[]),e}};bb.emphasis={filter:["em","i"],replacement:function(t,e,r){returnt.trim()?r.emDelimiter+t+r.emDelimiter:""}};bb.strong={filter:["strong","b"],replacement:function(t,e,r){returnt.trim()?r.strongDelimiter+t+r.strongDelimiter:""}};bb.code={filter:function(t){vare=t.previousSibling||t.nextSibling,r=t.parentNode.nodeName==="PRE"&&!e;returnt.nodeName==="CODE"&&!r},replacement:function(t){if(!t)return"";t=t.replace(/\r?\n|\r/g," ");for(vare=/^`|^ .*?[^ ].* $|`$/.test(t)?" ":"",r="`",n=t.match(/`+/gm)||[];n.indexOf(r)!==-1;)r=r+"`";returnr+e+t+e+r}};bb.image={filter:"img",replacement:function(t,e){varr=NLe(e.getAttribute("alt")),n=e.getAttribute("src")||"",o=NLe(e.getAttribute("title")),i=o?' "'+o+'"':"";returnn?"":""}};uGr.prototype={add:function(t,e){this.array.unshift(e)},keep:function(t){this._keep.unshift({filter:t,replacement:this.keepReplacement})},remove:function(t){this._remove.unshift({filter:t,replacement:function(){return""}})},forNode:function(t){if(t.isBlank)returnthis.blankRule;vare;return(e=mbt(this.array,t,this.options))||(e=mbt(this._keep,t,this.options))||(e=mbt(this._remove,t,this.options))?e:this.defaultRule},forEach:function(t){for(vare=0;e<this.array.length;e++)t(this.array[e],e)}};vbt=typeofwindow<"u"?window:{};sfi=ofi()?vbt.DOMParser:ifi();hfi=Array.prototype.reduce,gfi=[[/\\/g,"\\\\"],[/\*/g,"\\*"],[/^-/g,"\\-"],[/^\+ /g,"\\+ "],[/^(=+)/g,"\\$1"],[/^(#{1,6}) /g,"\\$1 "],[/`/g,"\\`"],[/^~~~/g,"\\~~~"],[/\[/g,"\\["],[/\]/g,"\\]"],[/^>/g,"\\>"],[/_/g,"\\_"],[/^(\d+)\. /g,"$1\\. "]];DLe.prototype={turndown:function(t){if(!_fi(t))thrownewTypeError(t+" is not a string, or an element/document/fragment node.");if(t==="")return"";vare=lGr.call(this,newufi(t,this.options));returnyfi.call(this,e)},use:function(t){if(Array.isArray(t))for(vare=0;e<t.length;e++)this.use(t[e]);elseif(typeoft=="function")t(this);elsethrownewTypeError("plugin must be a Function or an Array of Functions");returnthis},addRule:function(t,e){returnthis.rules.add(t,e),this},keep:function(t){returnthis.rules.keep(t),this},remove:function(t){returnthis.rules.remove(t),this},escape:function(t){returngfi.reduce(function(e,r){returne.replace(r[0],r[1])},t)}};dGr=DLe});function$Z(t){returntypeoft=="object"&&t!==null}functionLZ(t){if(typeoft=="string")returnt;if(t==null)return"";try{returnString(t)}catch{return""}}functiongGr(t){returntinstanceofError?t.message:LZ(t)}asyncfunctionvfi(t){awaitnewPromise(e=>setTimeout(e,t))}asyncfunctionyGr(t,e,r,n){leto=Date.now();for(;;){if(t())return;if(Date.now()-o>=e)thrownewiS(`${n} timed out after ${e}ms`);awaitvfi(r)}}functionpGr(t,e){letr=(t??"").trim();if(!r)return"";if(!e)returnr;try{returnnewURL(r,e).href}catch{returnr}}functionmGr(t){lete=(t??"").trim();returne?/[\s)]/.test(e)?`<${e}>`:e:""}functionwfi(t){lete=newdGr({headingStyle:"atx",hr:"---",bulletListMarker:"-",codeBlockStyle:"fenced",fence:"```",emDelimiter:"*",strongDelimiter:"**",linkStyle:"inlined"});returne.remove(["script","style","noscript"]),e.addRule("webviewer-link",{filter:"a",replacement:(r,n)=>{leto=n,i=o.getAttribute("href")??"",a=mGr(pGr(i,t)),s=r?.trim()||o.textContent||a;returna?`[${s}](${a})`:s}}),e.addRule("webviewer-image",{filter:"img",replacement:(r,n)=>{leto=n,i=o.getAttribute("alt")??"",a=o.getAttribute("src")??"",s=mGr(pGr(a,t));returns?``:""}}),e}functionwbt(t,e){if(!t.trim())return"";letr=wfi(e),i=newDOMParser().parseFromString(`<div>${t}</div>`,"text/html").body.firstElementChild;returni?r.turndown(i).replace(/\n{3,}/g,`
})()`,o="";try{leti=awaite.executeJavaScript(n);o=LZ(i)}catch(i){throwne("Failed to get selection HTML:",i),i}try{returnwbt(o,r)}catch(i){throwne("Failed to convert HTML to Markdown:",i),i}}asyncfunctionSGr(t){lete=DZ(t),r="";try{r=typeofe.getURL=="function"?e.getURL():""}catch{r=t.view?.url??""}letn=`(() => {
})()`,u=awaitr.executeJavaScript(s);if(!Sfi(u))thrownewError("Invalid transcript data structure");returnu}asyncfunctionOGr(t,e,r={}){let{preferCommand:n=!0,focusLeafBeforeCommand:o=!0}=r;if(n)try{returnawaite(ALe.SAVE_TO_VAULT,{leaf:t,focusLeaf:o}),F("Saved via webviewer:save-to-vault command"),{method:"command"}}catch(i){Te("save-to-vault command failed, falling back:",i)}try{returnawaitPromise.resolve(t.view.saveAsMarkdown()),F("Saved via view.saveAsMarkdown()"),{method:"view.saveAsMarkdown"}}catch(i){throwne("Failed to save Web Viewer page:",i),i}}varCbt=v(()=>{Xe();jZ();jLe()});function_b(t){if(typeoft!="string")returnnull;lete=t.trim();returne||null}functionkZ(t){if(typeoft!="string")returnnull;lete=t.trim();if(!e)returnnull;try{letr=newURL(e);r.hash="",(r.protocol==="http:"&&r.port==="80"||r.protocol==="https:"&&r.port==="443")&&(r.port=""),r.pathname!=="/"&&(r.pathname=r.pathname.replace(/\/+$/,""));letn=Array.from(r.searchParams.entries());returnn.length>0?(n.sort(([o,i],[a,s])=>o!==a?o.localeCompare(a):i.localeCompare(s)),r.search=`?${newURLSearchParams(n).toString()}`):r.search="",r.toString()}catch{returne}}functionPGr(t){return_b(t)??void0}functionxbt(t){lete=_b(t.url);if(!e)returnnull;letr=PGr(t.title),n=PGr(t.faviconUrl);return{url:e,title:r,faviconUrl:n,isLoaded:t.isLoaded,isActive:t.isActive?!0:void0}}functionDW(t){lete=newMap;for(letroft){letn=xbt(r);if(!n)continue;leto=e.get(n.url);if(!o){e.set(n.url,n);continue}e.set(n.url,{...o,title:n.title??o.title,faviconUrl:n.faviconUrl??o.faviconUrl,isLoaded:n.isLoaded??o.isLoaded,isActive:o.isActive||n.isActive?!0:void0})}returnArray.from(e.values())}functionMGr(t){lete=DW(t),r=!1;returne.map(n=>{if(!n.isActive)returnn;if(!r)returnr=!0,n;let{isActive:o,...i}=n;returni})}varqZ=v(()=>{});varCfi,kLe,RGr=v(()=>{Xe();jLe();jZ();qZ();Cfi=["did-finish-load","page-favicon-updated","page-title-updated"],kLe=classt{constructor(e){this.lastActiveLeaf=null;this.activeWebTabState={activeWebTabForMentions:null,activeOrLastWebTab:null};this.activeWebTabLeaf=null;this.activeWebTabListeners=newSet;this.activeWebTabTrackingRefs=null;this.activeWebTabTrackingPreserveViewTypes=[];this.webviewLoadListeners=newMap;this.webviewLoadCallbacks=newSet;this.cancelScheduledWebviewLoadNotify=null;this.app=e.app,this.isSupportedPlatform=e.isSupportedPlatform,this.getActiveLeaf=e.getActiveLeaf,this.getLeaves=e.getLeaves,this.getPageInfo=e.getPageInfo}getLastActiveLeaf(){lete=this.lastActiveLeaf;return!e||!Fde(e)?(this.lastActiveLeaf=null,null):_Gr(this.app,e)?e:(this.lastActiveLeaf=null,null)}findLeafByUrl(e,r={}){letn=e.trim();if(!n)returnnull;leto=this.getLeaves();for(letcofo)if(c?.view?.url===n)returnc;leti=kZ(n);if(!i)returnnull;leta=[];for(letcofo){letd=c?.view?.url;if(!d)continue;kZ(d)===i&&a.push(c)}if(a.length===0)returnnull;if(a.length===1)returna[0];lets=(r.title??"").trim();if(s){letc=s.toLowerCase(),d=[];for(letfofa)try{letm=(this.getPageInfo(f).title||"").trim();m&&m.toLowerCase()===c&&d.push(f)}catch{}if(d.length===1)returnd[0];if(d.length>1){letf=this.getActiveLeaf();if(f&&d.includes(f))returnf;letp=this.getLastActiveLeaf();returnp&&d.includes(p)?p:(Te("[WebViewerStateManager] Multiple leaves matched URL + title; returning first match.",{url:n,title:s,matches:d.length}),d[0])}}letu=this.getActiveLeaf();if(u&&a.includes(u))returnu;letl=this.getLastActiveLeaf();returnl&&a.includes(l)?l:(Te("[WebViewerStateManager] Multiple leaves matched URL; returning first match as fallback.",{url:n,matches:a.length}),a[0])}getActiveWebTabState(){returnthis.activeWebTabState}subscribeActiveWebTabState(e){returnthis.activeWebTabListeners.add(e),()=>{this.activeWebTabListeners.delete(e)}}subscribeToWebviewLoad(e){returnthis.webviewLoadCallbacks.add(e),()=>{this.webviewLoadCallbacks.delete(e)}}startActiveWebTabTracking(e={}){this.activeWebTabTrackingRefs&&this.stopActiveWebTabTracking(),this.activeWebTabTrackingPreserveViewTypes=[...e.preserveOnViewTypes??[]];letr=this.app.workspace.on("active-leaf-chan
`,o}};XEe=new WeakSet,uvr=function(e,r){let n=e.filter(o=>o.type==="group");for(let o of n)for(let i of e){if(i.id===o.id)continue;let a=i.x+i.width/2,s=i.y+i.height/2;a>=o.x&&s>=o.y&&a<=o.x+o.width&&s<=o.y+o.height&&r.push({id:crypto.randomUUID(),fromNode:o.id,toNode:i.id,label:"contains"})}};function $po(t,e){let r=e.adapter;if(r instanceof YEe.FileSystemAdapter)return r.getFullPath(t.path);let n=r;return typeof n.getFullPath=="function"?n.getFullPath(t.path):null}var ost=class{constructor(){this.miyoClient=new S0}async parsePdf(e,r){let n=te();if(!n.enableMiyo||e.extension.toLowerCase()!=="pdf")return null;let o=$po(e,r);if(!o)return Te(`[SelfHostPdfParser]Couldnotresolveabsolutepathfor${e.path};cannotcallMiyoparse-doc`),null;try{let i=await this.miyoClient.resolveBaseUrl(n.selfHostUrl),a=await this.miyoClient.parseDoc(i,o);if(typeof a.text!="string"||a.text.trim().length===0)throw new Error("Miyo parse-doc returned empty text");return F(`[SelfHostPdfParser]ParsedPDFviaMiyo:${e.path}`),a.text}catch(i){return Te(`[SelfHostPdfParser]Failedtoparse${e.path}viaMiyoparse-doc:${iinstanceofError?i.message:String(i)}`),null}}},ist=class{constructor(){this.supportedExtensions=["md"]}async parseFile(e,r){return await r.read(e)}},ZEe=class{constructor(e){this.supportedExtensions=["pdf"];this.brevilabsClient=e,this.pdfCache=KEe.getInstance(),this.selfHostPdfParser=new ost}async parseFile(e,r){try{F("Parsing PDF file:",e.path);let n=await this.pdfCache.get(e);if(n)return F("Using cached PDF content for:",e.path),n.response;let o=te();if(o_()&&o.enableMiyo&&e.extension.toLowerCase()==="pdf"){let s=await this.selfHostPdfParser.parsePdf(e,r);return s!==null?(await this.pdfCache.set(e,{response:s,elapsed_time_ms:0}),s):(ne(`[PDFParser]Miyoenabledbutparse-docfailedfor${e.path}`),`[Error:CouldnotextractcontentfromPDF${e.basename}]`)}let i=await r.readBinary(e);F("Calling pdf4llm API for:",e.path);let a=await this.brevilabsClient.pdf4llm(i);return await this.pdfCache.set(e,a),a.response}catch(n){return ne(`ErrorextractingcontentfromPDF${e.path}:`,n),`[Error:CouldnotextractcontentfromPDF${e.basename}]`}}async clearCache(){F("Clearing PDF cache"),await this.pdfCache.clear()}},ast=class{constructor(){this.supportedExtensions=["canvas"]}async parseFile(e,r){try{F("Parsing Canvas file:",e.path);let n=new GEe(r),o=await n.load(e);return n.buildPrompt(o)}catch(n){return ne(`ErrorparsingCanvasfile${e.path}:`,n),`[Error:CouldnotparseCanvasfile${e.basename}]`}}},u9=class u9{constructor(e,r=null){this.supportedExtensions=["pdf","602","abw","cgm","cwk","doc","docx","docm","dot","dotm","hwp","key","lwp","mw","mcw","pages","pbd","ppt","pptm","pptx","pot","potm","potx","rtf","sda","sdd","sdp","sdw","sgl","sti","sxi","sxw","stw","sxg","txt","uof","uop","uot","vor","wpd","wps","xml","zabw","epub","jpg","jpeg","png","gif","bmp","svg","tiff","webp","web","htm","html","xlsx","xls","xlsm","xlsb","xlw","csv","dif","sylk","slk","prn","numbers","et","ods","fods","uos1","uos2","dbf","wk1","wk2","wk3","wk4","wks","123","wq1","wq2","wb1","wb2","wb3","qpw","xlr","eth","tsv","mp3","mp4","mpeg","mpga","m4a","wav","webm"];this.brevilabsClient=e,this.projectContextCache=Fw.getInstance(),this.currentProject=r}static resetRateLimitNoticeTimer(){u9.lastRateLimitNoticeTime=0}async parseFile(e,r){try{if(F(`[Docs4LLMParser]Project${this.currentProject?.name}:Parsing${e.extension}file:${e.path}`),!this.currentProject)throw ne("[Docs4LLMParser] No project context for parsing file: ",e.path),new Error("No project context provided for file parsing");let n=await this.projectContextCache.getOrReuseFileContext(this.currentProject,e.path);if(n)return F(`[Docs4LLMParser]Project${this.currentProject.name}:Usingcachedcontentfor:${e.path}`),n;F(`[Docs4LLMParser]Project${this.currentProject.name}:Cachemissfor:${e.path}.ProceedingtoAPIcall.`);let o=await r.readBinary(e);F(`[Docs4LLMParser]Project${this.currentProject.name}:Callingdocs4llmAPIfor:${e.path}`);let i=await this.brevilabsClient.docs4llm(
`)}elsetypeofi.response=="object"?i.response.md?a=i.response.md:i.response.text?a=i.response.text:i.response.content?a=i.response.content:a=JSON.stringify(i.response,null,2):a=String(i.response);returnawaitthis.projectContextCache.setFileContext(this.currentProject,e.path,a),F(`[Docs4LLMParser] Project ${this.currentProject.name}: Successfully processed and cached: ${e.path}`),a}catch(n){throwne(`[Docs4LLMParser] Project ${this.currentProject?.name}: Error processing file ${e.path}:`,n),DD(n)&&this.showRateLimitNotice(n),n}}showRateLimitNotice(e){letr=Date.now();if(r-u9.lastRateLimitNoticeTime<6e4)return;u9.lastRateLimitNoticeTime=r;letn=avr(e);newYEe.Notice(`\u26A0\uFE0F Rate limit exceeded for document processing. Please try again in ${n}. Having fewer non-markdown files in the project will help.`,1e4)}asyncclearCache(){F("Cache clearing is now handled at the project level")}};u9.lastRateLimitNoticeTime=0;varIae=u9,Tq=class{constructor(e,r,n=!1,o=null){this.parsers=newMap;this.isProjectMode=n,this.currentProject=o,this.registerParser(newist),this.registerParser(newIae(e,o)),n||this.registerParser(newZEe(e)),this.registerParser(newast)}registerParser(e){for(letrofe.supportedExtensions)this.parsers.set(r,e)}asyncparseFile(e,r){letn=this.parsers.get(e.extension);if(!n)thrownewError(`No parser found for file type: ${e.extension}`);returnawaitn.parseFile(e,r)}supportsExtension(e){returnthis.parsers.has(e)}asyncclearPDFCache(){lete=this.parsers.get("pdf");einstanceofZEe&&awaite.clearCache()}};Bt();l1();vardW=require("obsidian");mA();ra();sd();mr();mr();Xe();Bt();varjD=class{constructor(e){this.chainManager=e}asynchandleResponse(e,r,n,o,i,a,s,u){if((e||u?.wasTruncated)&&!(n.signal.aborted&&n.signal.reason==="new-chat")){letp=r.contextEnvelope?.layers.find(g=>g.id==="L5_USER")?.text||r.originalMessage||r.message,m=s||e||"[Response truncated - no content generated]";awaitthis.chainManager.memoryManager.saveContext({input:p},{output:m});lety={message:e||(u?.wasTruncated?"_[The response was truncated before any content could be generated. Try increasing the max tokens limit.]_":""),sender:cw,isVisible:!0,timestamp:Mg(newDate),sources:a,responseMetadata:u};o(y),i("")}elsen.signal.reason==="new-chat"&&i("");letc=this.chainManager.memoryManager.getMemory().chatHistory.messages;F(`Chat memory updated:
`,{turns:Array.isArray(c)?c.length:0});letd=2e3;try{let{parseToolCallMarkers:f}=awaitPromise.resolve().then(()=>(dst(),lvr)),m=f(e).segments.map(y=>y.type==="text"?y.content:"").join("").trim();m||(m=e||"");leth=m.length>d?m.slice(0,d)+"... (truncated)":m;F(`Final AI response (truncated):
`,h)}catch{letf=typeofe=="string"?e:String(e??""),p=f.length>d?f.slice(0,d)+"... (truncated)":f;F(`Final AI response (truncated):
`,p)}returne}asynchandleError(e,r){letn=zr(e);ne("Error during LLM invocation:",n);leto=e?.response?.data?.error||n,i=o?.code||n,a="";e?.message?.includes("Invalid license key")?a="Invalid Copilot Plus license key. Please check your license key in settings.":i==="model_not_found"?a="You do not have access to this model or the model does not exist, please check with your API provider.":a=`${i}`,ne(o),r(this.enhancedErrorMsg(a,n,e))}enhancedErrorMsg(e,r,n){leto=e.search("Troubleshooting URL");returne=o!==-1?e.slice(0,o):e,this.isAuthenticationError(n,r)&&(e=`Something went wrong. Please check if you have set your API key.
`+u.text),i&&F("[LayerToMessagesConverter] Added L2 (cumulative context) to system")),a.push({role:"system",content:f.join(`
`)}),i&&F("[LayerToMessagesConverter] Added L1 (System) + L2 (Cumulative) as stable prefix")}if(c&&c.text&&i&&F("[LayerToMessagesConverter] L4 (Strip) found but skipped (using LangChain memory)"),o){letf=[];if(l&&l.segments.length>0&&u){letp=newSet(u.segments.map(y=>y.id)),m=[],h=[];for(letyofl.segments)p.has(y.id)?m.push(y.id):h.push(y);if(m.length>0||h.length>0){lety=[];m.length>0&&y.push(`Context attached to this message:
`+m.map(g=>`- ${g}`).join(`
`)+`
Find them in the Context Library in the system prompt above.`),h.length>0&&y.push(h.map(g=>g.content).join(`
`)),f.push(y.join(`
`)),i&&F(`[LayerToMessagesConverter] Added L3: ${m.length} references, ${h.length} new items`)}}elsel&&l.text&&(f.push(l.text),i&&F("[LayerToMessagesConverter] Added L3 (all new context)"));f.length>0&&d&&d.text&&f.push(`---
`)}functionEq(t){let{messages:e,modelName:r,contextEnvelope:n}=t;try{l9={timestamp:newDate().toISOString(),modelName:r,serializedMessages:Hpo(e),messagesArray:e,contextEnvelope:n}}catch{l9={timestamp:newDate().toISOString(),modelName:r,serializedMessages:String(e),messagesArray:e,contextEnvelope:n}}}functionc9(){l9=null}asyncfunctionQEe(){if(!l9)return;let{timestamp:t,modelName:e,serializedMessages:r,messagesArray:n,contextEnvelope:o}=l9,i=[`### Prompt \u2014 ${t}${e?` \u2014 ${e}`:""}`,"","**Actual Messages Sent to LLM:**","","```json",r,"```",""],a=Wpo(n,o);i.push("**Layered Context Metadata:**"),i.push(""),i.push("```"),i.push(a),i.push("```"),i.push(""),fye(i),l9=null}functiondvr(t){lete=t.response_metadata||{};returne.finish_reason==="length"?{wasTruncated:!0,message:"Response truncated due to token limit"}:e.stop_reason==="max_tokens"?{wasTruncated:!0,message:"Response truncated due to max_tokens limit"}:e.finishReason==="MAX_TOKENS"||e.finish_reason==="MAX_TOKENS"?{wasTruncated:!0,message:"Response truncated due to MAX_TOKENS limit"}:{wasTruncated:!1,message:null}}functionfvr(t){lete=t.response_metadata||{};returne.tokenUsage?{inputTokens:e.tokenUsage.promptTokens,outputTokens:e.tokenUsage.completionTokens,totalTokens:e.tokenUsage.totalTokens}:e.usage?{inputTokens:e.usage.input_tokens||e.usage.inputTokens||e.usage.inputTokenCount||e.usage.prompt_tokens,outputTokens:e.usage.output_tokens||e.usage.outputTokens||e.usage.outputTokenCount||e.usage.completion_tokens,totalTokens:e.usage.total_tokens||e.usage.totalTokens||(e.usage.input_tokens||e.usage.inputTokenCount||0)+(e.usage.output_tokens||e.usage.outputTokenCount||0)}:t.usage_metadata?{inputTokens:t.usage_metadata.input_tokens,outputTokens:t.usage_metadata.output_tokens,totalTokens:t.usage_metadata.total_tokens}:null}functionJpo(t){return`<errorChunk>${t}</errorChunk>`}functionePe(t,e){letr=Jpo(t);returne?`${e}
${r}`:`
${r}`}ta();Xe();functionpst(t,e,r){returnnewMh({content:r,tool_call_id:t,name:e})}functiontPe(){lett=Date.now(),e=Math.random().toString(36).substring(2,11);return`call_${t}_${e}`}functionrPe(t){lete=[];for(letroft.values()){if(!r.name)continue;letn={};if(r.args)try{n=JSON.parse(r.args)}catch{ne(`[ToolCall] Failed to parse args for tool "${r.name}": ${r.args}`),n={}}e.push({id:r.id||tPe(),name:r.name,args:n})}returne}functionpvr(t,e){returnnewPn({content:t,tool_calls:e.map(r=>({id:r.id,name:r.name,args:r.args,type:"tool_call"}))})}Xe();vardv=class{constructor(e,r=!1){this.updateCurrentAiMessage=e;this.excludeThinking=r;this.hasOpenThinkBlock=!1;this.fullResponse="";this.errorResponse="";this.wasTruncated=!1;this.tokenUsage=null;this.hasHandledTextLevelThinkTag=!1;this.toolCallChunks=newMap;this.accumulatedToolCalls=[];F(`[ThinkBlockStreamer] Created with excludeThinking=${r}`)}handleTextLevelThinkTags(){lete=this.fullResponse.includes("</think>"),r=this.fullResponse.includes("<think>");if(e){if(this.excludeThinking){if(r)this.fullResponse=this.fullResponse.replace(/<think>[\s\S]*?<\/think>/g,"").trim();else{letn=this.fullResponse.indexOf("</think>");this.fullResponse=this.fullResponse.substring(n+8).trim()}return}!r&&!this.hasHandledTextLevelThinkTag&&(this.hasHandledTextLevelThinkTag=!0,Te("Detected </think> closing tag without opening <think> tag. This may indicate a misconfigured chat template in LM Studio. Adding opening tag."),this.fullResponse="<think>"+this.fullResponse)}}handleClaudeChunk(e){letr="",n=!1;for(letoofe)switch(o.type){case"text":r+=o.text;break;case"thinking":if(n=!0,this.excludeThinking)break;this.hasOpenThinkBlock||(this.fullResponse+=`
<think>`,this.hasOpenThinkBlock=!0),this.fullResponse+=e.additional_kwargs.delta.reasoning),!0):(typeofe.content=="string"&&e.content&&this.hasOpenThinkBlock&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),typeofe.content=="string"&&e.content&&(this.fullResponse+=e.content),!1)}handleToolCallChunks(e){letr=e.tool_call_chunks;if(!(!r||!Array.isArray(r)))for(letnofr){leto=n.index??0,i=this.toolCallChunks.get(o)||{name:"",args:""};n.id&&(i.id=n.id),n.name&&(i.name+=n.name),n.args&&(i.args+=n.args),this.toolCallChunks.set(o,i)}}processChunk(e){dvr(e).wasTruncated&&(this.wasTruncated=!0);letn=fvr(e);n&&(this.tokenUsage=n),this.handleToolCallChunks(e);leto=Array.isArray(e.content)||e.additional_kwargs?.delta?.reasoning||e.additional_kwargs?.reasoning_details&&Array.isArray(e.additional_kwargs.reasoning_details)&&e.additional_kwargs.reasoning_details.length>0||e.additional_kwargs?.reasoning_content;this.hasOpenThinkBlock&&!o&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),Array.isArray(e.content)?this.handleClaudeChunk(e.content):e.additional_kwargs?.reasoning_content?this.handleDeepseekChunk(e):o?this.handleOpenRouterChunk(e):this.handleDeepseekChunk(e),this.handleTextLevelThinkTags(),this.updateCurrentAiMessage(this.fullResponse)}processErrorChunk(e){this.errorResponse=ePe(e)}getToolCalls(){returnthis.accumulatedToolCalls.length>0?this.accumulatedToolCalls:rPe(this.toolCallChunks)}hasToolCalls(){returnthis.toolCallChunks.size>0||this.accumulatedToolCalls.length>0}setToolCalls(e){this.accumulatedToolCalls=e}buildAIMessage(){lete=this.getToolCalls();returnpvr(this.fullResponse,e)}close(){returnthis.hasOpenThinkBlock&&(this.fullResponse+="</think>"),this.handleTextLevelThinkTags(),this.errorResponse&&(this.fullResponse+=this.errorResponse),this.updateCurrentAiMessage(this.fullResponse),{content:this.fullResponse,wasTruncated:this.wasTruncated,tokenUsage:this.tokenUsage}}};ra();varAae=classextendsjD{asyncconstructMessages(e){if(!e.contextEnvelope)thrownewError("[LLMChainRunner] Context envelope is required but not available. Cannot proceed with LLM chain.");F("[LLMChainRunner] Using envelope-based context");letr=_A.convert(e.contextEnvelope,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),n=[],o=r.find(s=>s.role==="system");o&&n.push(o);leti=this.chainManager.memoryManager.getMemory();awaitOq(i,n);leta=r.find(s=>s.role==="user");if(a)if(e.content&&Array.isArray(e.content)){lets=e.content.map(u=>u.type==="text"?{...u,text:a.content}:u);n.push({role:"user",content:s})}elsen.push(a);returnn}asyncrun(e,r,n,o,i){leta=te(),s=B_(),u=!1;try{u=!qS(s,a.activeModels).capabilities?.includes("reasoning")}catch(f){F("Could not determine model capabilities, defaulting to include thinking blocks",f)}letl=newdv(n,u);try{letf=awaitthis.constructMessages(e),m=this.chainManager.chatModelManager.getChatModel()?.modelName;Eq({messages:f,modelName:m,contextEnvelope:e.contextEnvelope}),F(`Final Request to AI:
`,f);leth=awaitVb(()=>this.chainManager.chatModelManager.getChatModel().stream(f,{signal:r.signal}));forawait(letyofh){if(r.signal.aborted){F("Stream iteration aborted",{reason:r.signal.reason});break}l.processChunk(y)}}catch(f){f.name==="AbortError"||r.signal.aborted?F("Stream aborted by user",{reason:r.signal.reason}):awaitthis.handleError(f,l.processErrorChunk.bind(l))}letc=l.close(),d={wasTruncated:c.wasTruncated,tokenUsage:c.tokenUsage??void0};returnr.signal.aborted&&r.signal.reason==="new-chat"?(n(""),""):(awaitthis.handleResponse(c.content,e,r,o,n,void0,void0,d),c.content)}};mr();Bt();asyncfunctionnPe(t,e){letr=`Given the following conversation and a follow up question,
summarize the conversation as context and keep the follow up question unchanged, in its original language.
If the follow up question is unrelated to its preceding messages, return this follow up question directly.
If it is related, then combine the summary and the follow up question to construct a standalone question.
Make sure to keep any [[]] wrapped note titles in the question unchanged.
If there's nothing in the chat history, just return the follow up question.
`);returnawaitVb(async()=>{leti=await(awaitry.instance.getCurrentChainManager().chatModelManager.getChatModelWithTemperature(0)).invoke([{role:"user",content:r.replace("{chat_history}",n).replace("{question}",t)}]),a=Rte(i.content);return_ye(a)})}Xe();Xe();Fc();Ye();Xe();Bt();ND();f9();varoPe=classextendsUx{constructor(r,n,o){super();this.lc_namespace=["self_host_retriever"];this.app=r,this.backend=n,this.options={...o,minSimilarityScore:o.minSimilarityScore??.01,salientTerms:o.salientTerms??[],returnAll:o.returnAll??!1}}asyncgetRelevantDocuments(r,n){try{if(!awaitthis.backend.isAvailable())returnTe("SelfHostRetriever: Backend is not available"),[];leta=kS(r,this.app.vault).map(f=>f.basename),s=[...newSet([...this.options.salientTerms||[],...a])],u=this.buildFilter(),l=this.options.returnAll?100:this.options.maxK,c=awaitthis.backend.search(r,{limit:l,minScore:this.options.minSimilarityScore,filter:u});F(`SelfHostRetriever: Found ${c.length} results for query "${r.substring(0,50)}..."`);letd=this.convertToDocuments(c);returns.length>0?this.boostBySalientTerms(d,s):d}catch(o){returnTe(`SelfHostRetriever: Search failed: ${o}`),[]}}buildFilter(){letr={};returnthis.options.timeRange&&(r.mtime={gte:this.options.timeRange.startTime,lte:this.options.timeRange.endTime}),this.options.tagTerms&&this.options.tagTerms.length>0&&(r.tags={containsAny:this.options.tagTerms}),Object.keys(r).length>0?r:void0}convertToDocuments(r){returnr.map(n=>newtl({pageContent:n.content,metadata:{...n.metadata,score:n.score,rerank_score:n.score,id:n.id,source:"self_host"}}))}boostBySalientTerms(r,n){returnr.map(a=>{lets=a.pageContent.toLowerCase(),u=(a.metadata?.title||"").toLowerCase();if(n.some(c=>s.includes(c.toLowerCase())||u.includes(c.toLowerCase()))){letc=(a.metadata?.score||0)*1.1;returnnewtl({pageContent:a.pageContent,metadata:{...a.metadata,score:c,rerank_score:c,salientBoost:!0}})}returna}).sort((a,s)=>(s.metadata?.score||0)-(a.metadata?.score||0))}getBackend(){returnthis.backend}};ND();f9();Xe();BG();NOe();Ye();wH();varbPe=classextendsUx{constructor(r,n){super();this.app=r;this.options=n;this.lc_namespace=["miyo_semantic_retriever"];this.client=newS0,this.returnAll=!!n.returnAll,this.maxK=Math.max(1,n.maxK),this.minSimilarityScore=n.minSimilarityScore??.1}asyncgetRelevantDocuments(r,n){leto=awaitthis.searchMiyo(r),i=this.deduplicateResults(o);returnte().debug&&this.logDebugInfo(r,o,i),i}asyncsearchMiyo(r){try{letn=awaitthis.client.resolveBaseUrl(te().selfHostUrl),o=this.returnAll?ec:this.maxK,i=this.buildSearchFilters();te().debug&&F("MiyoSemanticRetriever: search params:",{baseUrl:n,limit:o,maxK:this.maxK,minSimilarityScore:this.minSimilarityScore,returnAll:this.returnAll,filters:i});lets=(awaitthis.client.search(n,zG(this.app),r,o,i)).results||[],u=s.filter(l=>this.isScoreAboveThreshold(l));returnte().debug&&F(`MiyoSemanticRetriever: received ${s.length} results, ${u.length} after threshold`),u.map(l=>this.toDocument(l))}catch(n){returnTe(`MiyoSemanticRetriever: search failed: ${n}`),[]}}buildSearchFilters(){if(!this.options.timeRange)return;let{startTime:r,endTime:n}=this.options.timeRange;return[{field:"mtime",gte:r,lte:n}]}toDocument(r){letn=r.metadata??{},o=n.chunkId||(r.chunk_index!==void0?`${r.path}#${r.chunk_index}`:void0),i=typeofr.score=="number"?r.score.toFixed(2):"?";returnnewtl({pageContent:r.chunk_text??"",metadata:{...n,score:r.score,explanation:`miyo ${i}`,path:r.path,mtime:r.mtime,ctime:r.ctime,title:r.title??"",id:r.id,embeddingModel:r.embedding_model,tags:r.tags??[],extension:r.extension,created_at:r.created_at,nchars:r.nchars,chunkId:o}})}isScoreAboveThreshold(r){letn=r.score;returntypeofn!="number"||Number.isNaN(n)?!0:n>=this.minSimilarityScore}deduplicateResults(r){letn=newMap,o=i=>{leta=this.getDocumentKey(i);n.has(a)||n.set(a,i)};returnr.forEach(o),te().debug&&n.size!==r.length&&F(`MiyoSemanticRetriever: deduplicated semantic results from ${r.length} to ${n.size}`),Array.from(n.values())}logDebugInfo(r,n,o){F("*** MIYO SEMANTIC RETRIEVER DEBUG INFO: ***"),F("
1. START with [^1] and increment sequentially ([^1], [^2], [^3], etc.) with NO gaps
2. BE SELECTIVE: ONLY cite when introducing NEW factual claims, specific data, or direct quotes from sources
3. IMPORTANT: Do NOT cite every sentence or bullet point. This creates clutter and poor readability.
4. DO NOT cite for:
- General knowledge or common facts
- Your own analysis or synthesis
- Transitional or concluding statements
- Every single sentence (AVOID CITATION CLUTTER - aim for 1-3 citations per paragraph maximum)
5. Citations are for SOURCE ATTRIBUTION, not for proving every statement
6. GOOD: One citation per key concept. BAD: Citation after every sentence.
7. Place citations immediately after the specific claim: "ThestudyfoundX[^1]" not "ThestudyfoundX.[^1]"
8. Do not reuse any bracketed numbers that appear inside the source content itself
9. If multiple source chunks come from the same document, cite each relevant chunk separately (e.g., [^1] and [^2] can both be from the same document title)
10. End with '#### Sources' section containing: [^n]: [[Title]] (one per line, matching citation order)`,xti=`WEB CITATION RULES:
1. START with [^1] and increment sequentially ([^1], [^2], [^3], etc.) with NO gaps
2. Cite ONLY when introducing new factual claims, statistics, or direct quotes from the search results
3. After every cited claim, place the corresponding footnote immediately after the sentence ("ThestudyfoundX[^1]")
4. End with '#### Sources' and provide definitions EXACTLY in this format: [^n]: [Short Title](URL)
IMPORTANT: Each source definition must follow this exact pattern:
- Start with [^n]: (where n is the citation number)
- Follow with [Title](URL) where Title is SHORT (2-5 words) and wrapped in square brackets
- Example: [^1]: [Paul Graham Essay](https://paulgraham.com/wealth.html)
- DO NOT write long descriptions - keep titles concise`;function H4r(t,e=!0){return e?`
<guidance>
${V4r}
IMAGE INCLUSION:
When the retrieved documents contain relevant images (in formats like  or ![[image.png]]), include them in your response at appropriate locations using their exact original markdown format from the source.
Source Catalog (for reference only):
${t.join(`
`)}
</guidance>`:`
<guidance>
IMAGE INCLUSION:
When the retrieved documents contain relevant images (in formats like  or ![[image.png]]), include them in your response at appropriate locations using their exact original markdown format from the source.
</details>`}functionG4r(t,e=!0){if(!e)returnt;letr=Eti(t);if(!r)returnt;let{mainContent:n,sourcesBlock:o}=r;o=Pti(o);leti=Mti(o);if(i.length===0){letd=Lti(o);returnz4r(n,d)}leta=Rti(n,i);n=Iti(n,a);lets=Ati(o,a),{uniqueItems:u,consolidationMap:l}=Nti(s);l.size>0&&(n=Dti(n,l),s=u);letc=s.map((d,f)=>d?{index:f+1,html:d}:null).filter($ti);returnz4r(n,c)}functiontje(t){returnt.map(e=>{letr=e.title||e.path||"Untitled",n=e.path||r;return`- [[${r}]] (${n})`})}ra();varCle=classextendsjD{asyncrun(e,r,n,o,i){leta=te(),s=B_(),u=!1;try{u=!qS(s,a.activeModels).capabilities?.includes("reasoning")}catch(p){F("Could not determine model capabilities, defaulting to include thinking blocks",p)}letl=newdv(n,u);try{letp=e.contextEnvelope;if(!p)thrownewError("[VaultQA] Context envelope is required but not available. Cannot proceed with VaultQA chain.");leth=p.layers.find(re=>re.id==="L5_USER")?.text||e.message,y=this.extractTagTerms(h);F("[VaultQA] Extracted tags before condensing:",y);letg=this.chainManager.memoryManager.getMemory(),b=awaitg.loadMemoryVariables({}),_=gye(b),w=h;_.length>0&&(F("[VaultQA] Condensing query with chat history for better retrieval"),w=awaitnPe(h,_),F("[VaultQA] Standalone question:",w));letT=te(),O=y.length>0,P=awaitnewVU(app,{salientTerms:O?[...y]:[],maxK:Ly,returnAll:O}).getRelevantDocuments(w),R=lT.isMiyoActive(),I=awaitlT.createRetriever(app,{minSimilarityScore:.01,maxK:Ly,salientTerms:O?[...y]:[],tagTerms:y,returnAll:O},R?{enableMiyo:!1,enableSemanticSearchV3:!1}:{}),N=I.retriever;F(`VaultQA: Using ${I.type} retriever - ${I.reason}`);letz=awaitN.getRelevantDocuments(w),{filterResults:V,searchResults:k}=TX(P,z),X=[...V,...k],B=X.length>Ly,Q=X.slice(0,Ly);this.chainManager.storeRetrieverDocuments(Q);letY=Q.map(re=>{letZ=re.metadata?.title||"Untitled",le=re.metadata?.path||Z;return`<${CWe}>
IMPORTANT: The retrieval limit of ${Ly} documents was reached. ${X.length-Ly} additional matching documents were omitted. Inform the user: "Note: The retrieval cap was reached \u2014 some matching documents were not included. Upgrade to Copilot Plus for more complete answers."`:"",W=`
Answer the question based only on the following context:
`+Y+W4r(de,T.enableInlineCitations)+L;F("[VaultQA] Using envelope-based context construction with LayerToMessagesConverter");letie=_A.convert(p,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),j=ie.find(re=>re.role==="system");j&&K.push({role:Mte(oe),content:j.content}),awaitOq(g,K);letA=ie.find(re=>re.role==="user");if(A){letre=W+`
`+A.content;if(e.content&&Array.isArray(e.content)){letZ=e.content.map(le=>le.type==="text"?{...le,text:re}:le);K.push({role:"user",content:Z})}elseK.push({role:"user",content:re})}letU=oe?.modelName;Eq({messages:K,modelName:U,contextEnvelope:e.contextEnvelope}),F(`Final Request to AI:
`,K);letH=awaitVb(()=>this.chainManager.chatModelManager.getChatModel().stream(K,{signal:r.signal}));forawait(letreofH){if(r.signal.aborted){F("VaultQA stream iteration aborted",{reason:r.signal.reason});break}l.processChunk(re)}}catch(p){p.name==="AbortError"||r.signal.aborted?F("VaultQA stream aborted by user",{reason:r.signal.reason}):awaitthis.handleError(p,l.processErrorChunk.bind(l))}letc=l.close(),d={wasTruncated:c.wasTruncated,tokenUsage:c.tokenUsage??void0};if(r.signal.aborted&&r.signal.reason==="new-chat")returnn(""),"";letf=this.addSourcestoResponse(c.content);returnawaitthis.handleResponse(f,e,r,o,n,void0,void0,d),f}addSourcestoResponse(e){letr=te();if(!J4r(e))returne;letn=this.chainManager.getRetrievedDocuments(),o=T1t(n).map(i=>({title:i}));returnQDe(e,o,r.enableInlineCitations)}extractTagTerms(e){returnh9(e)}};varOX=["@vault","@websearch","@composer","@memory"];mr();Xe();Fc();Ye();Ye();mr();Xe();XC();XC();Ye();varQw=pF(),HU=bc([]),$mt=bc(""),X4r=bc(!1);functionrje(){returnL_(HU,{store:Qw})}functionZ4r(){returnu1($mt,{store:Qw})}functionEX(){returnQw.get(HU)}functionG3(){returnQw.get($mt)}functionnje(t){Qw.set(HU,t)}functionX3(t){lete=Qw.get(HU),r=e.findIndex(n=>n.title===t.title);if(r!==-1){letn=[...e];n[r]=t,Qw.set(HU,n)}elseQw.set(HU,[...e,t])}functionPX(t){lete=Qw.get(HU);Qw.set(HU,e.filter(r=>r.title!==t))}functionWU(t){Qw.set($mt,t)}functionxle(t){Qw.set(X4r,t)}functionTle(){returnQw.get(X4r)}varLmt=newSet;functionJU(t){Lmt.add(t)}functionKU(t){Lmt.delete(t)}functionC$(t){returnLmt.has(t)}functionoje(){returnte().defaultSystemPromptTitle}functionY4r(){lett=EX(),e=G3();if(e){letn=t.find(o=>o.title===e);if(n)returnn.content}letr=oje();if(r){letn=t.find(o=>o.title===r);if(n)returnn.content}return""}functionQ4r(){lett=oje();WU(t)}functionFmt(){xle(!1),WU("")}functionije(){returnY4r()||te()?.userSystemPrompt||""}functionx$(){lett=ije();if(Tle())returnt;letr=L1t;returnt?`${r}
<user_custom_instructions>
${t}
</user_custom_instructions>`:r}asyncfunctionT$(t){lete=x$();if(!t)returnF("No UserMemoryManager provided to getSystemPromptWithMemory"),e;letr=awaitt.getUserMemoryPrompt();returnr?`${r}
${e}`:e}varMX=require("obsidian");$r();Xe();Ye();functioncT(){}cT.prototype={diff:function(e,r){varn,o=arguments.length>2&&arguments[2]!==void0?arguments[2]:{},i=o.callback;typeofo=="function"&&(i=o,o={});vara=this;functions(w){returnw=a.postProcess(w,o),i?(setTimeout(function(){i(w)},0),!0):w}e=this.castInput(e,o),r=this.castInput(r,o),e=this.removeEmpty(this.tokenize(e,o)),r=this.removeEmpty(this.tokenize(r,o));varu=r.length,l=e.length,c=1,d=u+l;o.maxEditLength!=null&&(d=Math.min(d,o.maxEditLength));varf=(n=o.timeout)!==null&&n!==void0?n:1/0,p=Date.now()+f,m=[{oldPos:-1,lastComponent:void0}],h=this.extractCommon(m[0],r,e,0,o);if(m[0].oldPos+1>=l&&h+1>=u)returns(e2r(a,m[0].lastComponent,r,e,a.useLongestToken));vary=-1/0,g=1/0;functionb(){for(varw=Math.max(y,-c);w<=Math.min(g,c);w+=2){varT=void0,O=m[w-1],E=m[w+1];O&&(m[w-1]=void0);varP=!1;if(E){varR=E.oldPos-w;P=E&&0<=R&&R<u}varI=O&&O.oldPos+1<l;if(!P&&!I){m[w]=void0;continue}if(!I||P&&O.oldPos<E.oldPos?T=a.addToPath(E,!0,!1,0,o):T=a.addToPath(O,!1,!0,1,o),h=a.extractCommon(T,r,e,w,o),T.oldPos+1>=l&&h+1>=u)returns(e2r(a,T.lastComponent,r,e,a.useLongestToken));m[w]=T,T.oldPos+1>=l&&(g=Math.min(g,w-1)),h+1>=u&&(y=Math.max(y,w+1))}c++}if(i)(functionw(){setTimeout(function(){if(c>d||Date.now()>p)returni();b()||w()},0)})();elsefor(;c<=d&&Date.now()<=p;){var_=b();if(_)return_}},addToPath:function(e,r,n,o,i){vara=e.lastComponent;returna&&!i.oneChangePerToken&&a.added===r&&a.removed===n?{oldPos:e.oldPos+o,lastComponent:{count:a.count+1,added:r,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+o,lastComponent:{count:1,added:r,removed:n,previousComponent:a}}},extractCommon:function(e,r,n,o,i){for(vara=r.length,s=n.length,u=e.oldPos,l=u-o,c=0;l+1<a&&u+1<s&&this.equals(n[u+1],r[l+1],i);)l++,u++,c++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});returnc&&!i.oneChangePerToken&&(e.lastComponent={count:c,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=u,l},equals:function(e,r,n){returnn.comparator?n.comparator(e,r):e===r||n.ignoreCase&&e.toLowerCase()===r.toLowerCase()},removeEmpty:function(e){for(varr=[],n=0;n<e.length;n++)e[n]&&r.push(e[n]);returnr},castInput:function(e){returne},tokenize:function(e){returnArray.from(e)},join:function(e){returne.join("")},postProcess:function(e){returne}};functione2r(t,e,r,n,o){for(vari=[],a;e;)i.push(e),a=e.previousComponent,deletee.previousComponent,e=a;i.reverse();for(vars=0,u=i.length,l=0,c=0;s<u;s++){vard=i[s];if(d.removed)d.value=t.join(n.slice(c,c+d.count)),c+=d.count;else{if(!d.added&&o){varf=r.slice(l,l+d.count);f=f.map(function(p,m){varh=n[c+m];returnh.length>p.length?h:p}),d.value=t.join(f)}elsed.value=t.join(r.slice(l,l+d.count));l+=d.count,d.added||(c+=d.count)}}returni}varJps=newcT;functiont2r(t,e){varr;for(r=0;r<t.length&&r<e.length;r++)if(t[r]!=e[r])returnt.slice(0,r);returnt.slice(0,r)}functionr2r(t,e){varr;if(!t||!e||t[t.length-1]!=e[e.length-1])return"";for(r=0;r<t.length&&r<e.length;r++)if(t[t.length-(r+1)]!=e[e.length-(r+1)])returnt.slice(-r);returnt.slice(-r)}functionkmt(t,e,r){if(t.slice(0,e.length)!=e)throwError("string ".concat(JSON.stringify(t)," doesn't start with prefix ").concat(JSON.stringify(e),"; this is a bug"));returnr+t.slice(e.length)}functionqmt(t,e,r){if(!e)returnt+r;if(t.slice(-e.length)!=e)throwError("string ".concat(JSON.stringify(t)," doesn't end with suffix ").concat(JSON.stringify(e),"; this is a bug"));returnt.slice(0,-e.length)+r}functionOle(t,e){returnkmt(t,e,"")}functionaje(t,e){returnqmt(t,e,"")}functionn2r(t,e){returne.slice(0,Fti(t,e))}functionFti(t,e){varr=0;t.length>e.length&&(r=t.length-e.length);varn=e.length;t.length<e.length&&(n=t.length);varo=Array(n),i=0;o[0]=0;for(vara=1;a<n;a++){for(e[a]==e[i]?o[a]=o[i]:o[a]=i;i>0&&e[a]!=e[i];)i=o[i];e[a]==e[i]&&i++}i=0;for(vars=r;s<t.length;s++){for(;i>0&&t[s]!=e[i];)i=o[i];t[s]==e[i]&&i++}returni}varsje="a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\
The path must end with explicit file extension, such as .md or .canvas .
Prefer to create new files in existing folders or root folder unless the user's request specifies otherwise.
The path must be relative to the root of the vault.`),content:wt.union([wt.string(),wt.object({}).passthrough()]).describe(`(Required) The content to write to the file. Can be either a string or an object.
ALWAYS provide the COMPLETE intended content of the file, without any truncation or omissions.
You MUST include ALL parts of the file, even if they haven't been modified.
# For string content
* Use when writing text files like .md, .txt, etc.
# For object content
* Use when writing structured data files like .json, .canvas, etc.
* The object will be automatically converted to JSON string format
# Canvas JSON Format (JSON Canvas spec 1.0)
Required node fields: id, type, x, y, width, height
}`),confirmation:wt.preprocess(t=>{if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t},wt.boolean()).optional().default(!0).describe("(Optional)WhethertoaskforchangeconfirmationwithpreviewUIbeforewritingchanges.Default:true.Settofalsetoskippreviewandapplychangesimmediately.")}),fje=cc({name:"writeToFile",description:`Request to write content to a file at the specified path and show the changes in a Change Preview UI.
# Steps to find the the target path
1. Extract the target file information from user message and find out the file path from the context.
2. If target file is not specified, use the active note as the target file.
3. If still failed to find the target file or the file path, ask the user to specify the target file.
`,schema:Wti,func:async({path:t,content:e,confirmation:r=!0})=>{let n=D1t(t);n!==t&&(Te(`Filename too long, truncated for filesystem compatibility: "${t}" \u2192 "${n}"`),t=n);let o=typeof e=="string"?e:JSON.stringify(e,null,2);if(te().autoAcceptEdits||r===!1)try{let u=await p2r(t);return await app.vault.modify(u,o),{result:"accepted",message:"Filechangesappliedwithoutpreview.Donotretryorattemptalternativeapproachestomodifythisfileinresponsetothecurrentuserrequest."}}catch(u){return{result:"failed",message:`Error writing to file without preview: ${u?.message||u}`}}let s=await m2r(t,o);return{result:s,message:`File change result: ${s}. Do not retry or attempt alternative approaches to modify this file in response to the current user request.`}}}),Jti=wt.object({path:wt.string().describe("(Required)Thepathofthefiletomodify(relativetotherootofthevaultandincludethefileextension)."),diff:wt.string().describe(`(Required) One or more SEARCH/REPLACE blocks. Each block MUST follow this exact format with these exact markers:
------- SEARCH
[exact content to find, including all whitespace and indentation]
=======
[new content to replace with]
+++++++ REPLACE
WHEN TO USE THIS TOOL vs writeToFile:
- Use replaceInFile for: small edits, fixing typos, updating specific sections, targeted changes
- Use writeToFile for: creating new files, major rewrites, when you can't identify specific text to replace
CRITICAL RULES:
1. SEARCH content must match EXACTLY - every character, space, and line break
2. Use the exact markers: "-------SEARCH", "=======", "+++++++REPLACE"
3. For multiple changes, include multiple SEARCH/REPLACE blocks in order
4. Keep blocks concise - include only the lines being changed plus minimal context
COMMON MISTAKES TO AVOID:
- Wrong: Using different markers like "----SEARCH" or "SEARCH-------"
- Wrong: Including too many unchanged lines
- Wrong: Not matching whitespace/indentation exactly`)});function Ale(t){return t.replace(/\r\n/g,`
`):l}var h2r=cc({name:"replaceInFile",description:"RequesttoreplacesectionsofcontentinanexistingfileusingSEARCH/REPLACEblocksthatdefineexactchangestospecificpartsofthefile.ThistoolshouldbeusedwhenyouneedtomaketargetedchangestospecificpartsofaLARGEfile.",schema:Jti,func:async({path:t,diff:e})=>{let r=app.vault.getAbstractFileByPath(t);if(!r||!(r instanceof MX.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=Gti(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 c of a){let{searchText:d,replaceText:f}=c,p=Ale(o),m=Ale(d);if(!p.includes(m))if(p.includes(m.trimEnd()))d=d.trimEnd(),f=f.trimEnd();else return`Search text not found in file ${t} : "${d}".`;let h=o;o=Kti(o,d,f),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`;if(te().autoAcceptEdits)try{return await app.vault.modify(r,o),{result:"accepted",blocksApplied:s,message:`Applied ${s} SEARCH/REPLACE block(s) without preview. Do not call this tool again to modify this file in response to the current user request.`}}catch(c){return{result:"failed",blocksApplied:s,message:`Error applying changes without preview: ${c?.message||c}`}}let l=await m2r(t,o);return{result:l,blocksApplied:s,message:`Applied ${s} SEARCH/REPLACE block(s) (replacing all occurrences). Result: ${l}. 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.`}}});function Gti(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}Xe();var zmt=t=>{switch(t){case"@vault":return"Searchthroughyourvaultforrelevantinformation";case"@websearch":return"Searchthewebforinformation";case"@composer":return"Editexistingnotesorcreatenewnotes.";case"@memory":return"Saveinformationtousermemory";default:return""}},E$=class{static async callTool(e,r){if(!e)throw new Error("Toolisundefined");let n=await e.call(r);return n??(Te(`[ToolCall] Tool "${e.name}" returned null/undefined`),null)}};function g2r(t){let e=t.trim();if(!e)return"note";let r=e.match(/^\[\[([\s\S]+?)\]\]$/),n=r?r[1]:e,[o="",i=""]=n.split("|"),a=i.trim();if(a.length>0)return a;let s=o.trim(),[u]=s.split("#"),l=(u||s).trim()||e,c=l.split("/").filter(Boolean),d=c.length>0?c[c.length-1]:l;return d.replace(/\.[^/.]+$/,"")||d||"note"}var y2r=180;function Xti(t){let e=t.trim();return e.length<=y2r?e:`${e.slice(0,y2r)}\u2026`}function Zti(t){if(!t||typeof t!="object")return null;let e=typeof t.status=="string"?t.status:null,r=typeof t.message=="string"&&t.message.trim().length>0?Xti(t.message):null,n=typeof t.notePath=="string"?t.notePath:"",i=(typeof t.noteTitle=="string"&&t.noteTitle.trim().length>0?t.noteTitle.trim():g2r(n))||g2r(n);if(e==="invalid_path")return r??`\u26A0\uFE0F Invalid note path "${i}"`;if(e==="not_found")return r??`\u26A0\uFE0F Note "${i}" not found`;if(e==="not_unique"){let c=Array.isArray(t.candidates)?t.candidates.length:0;return r||(c>0?`\u26A0\uFE0F Multiple matches for "${i}" (${c} candidates)`:`\u26A0\uFE0F Multiple matches for "${i}"`)}if(e==="empty")return r??`\u26A0\uFE0F "${i}" contains no readable content`;if(e==="out_of_range"){if(r)return r;let c=typeof t.totalChunks=="number"&&Number.isFinite(t.totalChunks)?t.totalChunks:null,d=typeof t.chunkIndex=="number"&&Number.isFinite(t.chunkIndex)?t.chunkIndex:null;if(d!==null&&c!==null){let f=Math.max(c-1,0);return`\u26A0\uFE0F Chunk ${d} exceeds available range (max index ${f})`}return"\u26A0\uFE0FRequestedchunkisoutofrange"}let a=typeof t.chunkIndex=="number"&&Number.isFinite(t.chunkIndex)?t.chunkIndex:0,s=typeof t.totalChunks=="number"&&Number.isFinite(t.totalChunks)?t.totalChunks:null,u=!!t.hasMore,l=[`\u2705 Read "${i||"note"}"`];return s&&s>0?l.push(`chunk ${a+1} of ${s}`):l.push(`chunk ${a+1}`),u&&l.push("moreavailable"),l.join("\xB7")}var P$=class{static format(e,r){try{let n=r;if(typeof n=="string"&&n.startsWith("ENC:"))try{n=decodeURIComponent(n.slice(4))}catch{}let o;try{o=JSON.parse(n)}catch{o=n}switch(e){case"localSearch":return this.formatLocalSearch(o);case"webSearch":return this.formatWebSearch(o);case"youtubeTranscription":return this.formatYoutubeTranscription(o);case"writeToFile":
No matching notes found.`;let r=e.length,n=e.slice(0,10),o=n.some(s=>typeof s?.rerank_score=="number"||typeof s?.score=="number"||s?.source),i=n.map((s,u)=>o?this.formatSearchItem(s,u):this.formatBasicSearchItem(s,u)).join(`
`),a=r>10?`
... and ${r-10} more results`:"";return`\u{1F4DA} Found ${r} relevant notes
Top results:
${i}${a}`}static formatLocalSearch(e){if(typeof e=="string"){let n=e.match(/<localSearch[^>]*>([\s\S]*)<\/localSearch>/);if(n){let o=n[1].trim(),i=o.match(/<document>/g);if((i?i.length:0)===0)return`\u{1F4DA} Found 0 relevant notes
No matching notes found.`;let s=[],u=/<document>([\s\S]*?)<\/document>/g,l;for(;(l=u.exec(o))!==null;){let c=l[1],d=c.match(/<title>([\s\S]*?)<\/title>/),f=c.match(/<path>([\s\S]*?)<\/path>/),p=c.match(/<modified>([\s\S]*?)<\/modified>/),m=(d?.[1]||"Untitled").trim(),h=(f?.[1]||"").trim(),y=(p?.[1]||"").trim();s.push({title:m,path:h,mtime:y||null})}return this.formatLocalSearchDocuments(s)}}let r=this.parseSearchResults(e);return Array.isArray(r)?r.length===0?typeof e=="string"&&!e.includes("<localSearch")&&!e.includes('"type":"local_search"')?e:`\u{1F4DA} Found 0 relevant notes
`),n=["\u{1F310}WebSearchResults"],o=!1,i=[],a=[];for(let s of r){if(s.includes("Sources:")){o=!0;continue}o?a.push(s):s.includes("Herearethewebsearchresults")||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} YouTube Transcripts (${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("...(transcripttruncatedfordisplay)");break}o.elapsed_time_ms&&(n.push(""),n.push(`Processing time: ${(o.elapsed_time_ms/1e3).toFixed(1)}s`))}else n.push(`\u274C Failed to transcribe: ${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("...(transcripttruncatedfordisplay)");break}return r.elapsed_time_ms&&(n.push(""),n.push(`Processing time: ${(r.elapsed_time_ms/1e3).toFixed(1)}s`)),n.join(`
<recent_conversations> are the recent conversations between you and the user.
You can use it to provide more context for your responses.
Only use the recent conversations if they are relevant to the current conversation.`),e.enableSavedMemory&&this.savedMemoriesContent&&(r+=`<saved_memories>
${this.savedMemoriesContent}
</saved_memories>
<saved_memories> are important memories that the user explicitly asked you to remember.
Use these memories to provide more personalized and contextually relevant responses.`),r.length>0?r:null}catch(e){return ne("[UserMemoryManager]Errorreadingusermemorycontent:",e),null}}getTimestamp(){let e=new Date,r=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0"),i=String(e.getHours()).padStart(2,"0"),a=String(e.getMinutes()).padStart(2,"0");return`${r}-${n}-${o} ${i}:${a}`}async createConversationSection(e,r){let{title:n,summary:o}=await this.extractTitleAndSummary(e,r),i=this.getTimestamp(),a=`## ${n}
`;return a+=`**Time:** ${i}
`,a+=`**Summary:** ${o}
`,a}async updateMemory(e,r){if(this.isUpdatingMemory){F("[UserMemoryManager]Memoryupdatealreadyinprogress,skipping.");return}this.isUpdatingMemory=!0;try{if(await this.ensureMemoryFolderExists(),!r){ne("[UserMemoryManager]Nochatmodelavailable,skippingmemoryupdate");return}if(e.length===0){F("[UserMemoryManager]Nomessagesavailable,skippingmemoryupdate");return}let n=await this.createConversationSection(e,r);await this.addToRecentConversationsFile(this.getRecentConversationFilePath(),n)}catch(n){ne("[UserMemoryManager]Erroranalyzingchatmessagesforusermemory:",n)}finally{this.isUpdatingMemory=!1}}async ensureMemoryFolderExists(){let r=te().memoryFolderName;await $c(r)}getRecentConversationFilePath(){return`${te().memoryFolderName}/Recent Conversations.md`}getSavedMemoriesFilePath(){return`${te().memoryFolderName}/Saved Memories.md`}async updateSavedMemoryFile(e,r,n){let o=this.app.vault.getAbstractFileByPath(e),i=o instanceof RX.TFile?await this.app.vault.read(o):"";if(!n)return{error:"Nochatmodelavailable,skippingmemoryupdate"};let a=`You maintain a user's long-term personal memory list as concise bullet points.
You task is to update the user's memory list with the new statement.
Rules:
- Keep only stable, evergreen facts or preferences that will help future conversations.
- Remove duplicates and near-duplicates by merging them into one concise statement.
- If the new statement conflicts with older ones, keep the most recent truth and remove obsolete/conflicting entries.
- Prefer short, specific, and unambiguous phrasing.
- Preserve the language used in the input memories.
- Output only the memory content with each as a bullet point.
# OUTPUT FORMAT
Return the updated memory list with each as a bullet point.
* Use the same language as the conversation`,i=`<conversation_text>
${n}
</conversation_text>
Generate a title and summary for this conversation:`,a=[new Od(o),new qs(i)];try{let u=(await r.invoke(a)).text,l=this.extractJsonFromResponse(u);try{let c=JSON.parse(l);return{title:c.title||"UntitledConversation",summary:c.summary||"Nosummaryavailable"}}catch(c){return ne("[UserMemoryManager]FailedtoparseLLMresponseasJSON:",c),{title:"UntitledConversation",summary:"Summarygenerationfailed"}}}catch(s){return ne("[UserMemoryManager]Failedtoextracttitleandsummary:",s),{title:"UntitledConversation",summary:"Summarygenerationfailed"}}}};Xe();CX();var tri=wt.object({statement:wt.string().min(1).describe("Theuserstatementforexplicitlyupdatingsavedmemories")}),pje=cc({name:"updateMemory",description:"Updatetheusermemorywhentheuserexplicitlyaskstoupdatethememory",schema:tri,func:async({statement:t})=>{try{let e=new GU(app),r=tC.getInstance().getChatModel(),n=await e.updateSavedMemory(t,r);return n.error?{success:!1,message:n.error}:{success:!0,message:`Memory updated successfully into ${e.getSavedMemoriesFilePath()}: ${n.content}`}}catch(e){return ne("[updateMemoryTool]Errorupdatingmemory:",e),{success:!1,message:`Failed to save memory: ${e.message}`}}}});var Nle=require("obsidian");Xe();var Hmt=200;function mje(t){return t.replace(/\\/g,"/").toLowerCase()}function rri(t){return t.replace(/\.[^/.]+$/,"")}function nri(t,e){if(e.length===0)return!1;let n=mje(t).split("/").filter(Boolean);if(n.length<e.length)return!1;let o=n.slice(-e.length);for(let i=0;i<e.length;i+=1){let a=e[i];if(!a)return!1;let s=o[i];if(i===o.length-1){let u=rri(s);if(!s.includes(a)&&!u.includes(a))return!1}else if(!s.includes(a))return!1}return!0}function Wmt(t){return/\.[^/]+$/.test(t)}async function ori(t){let e=b=>{let _=app.vault.getAbstractFileByPath(b);return _ instanceof Nle.TFile?_:null},r=t.trim(),n=r.match(/^\s*\[\[([\s\S]+?)\]\]\s*$/),i=(n?n[1]:r).trim(),[a]=i.split("|"),[s]=a.split("#"),u=s.trim(),l=Array.from(new Set([r,i,u].map(b=>b.trim()).filter(Boolean)));for(let b of l){let _=e(b);if(_)return{type:"resolved",file:_};if(!Wmt(b))for(let w of[".md",".canvas"]){let T=e(`${b}${w}`);if(T)return{type:"resolved",file:T}}}let c=app.metadataCache,d=u.trim();if(c&&d){let b=new Set([d]);if(!Wmt(d))for(let _ of[".md",".canvas"])b.add(`${d}${_}`);for(let _ of b){let w=c.getFirstLinkpathDest?.(_,"");if(w instanceof Nle.TFile)return{type:"resolved",file:w}}}if(!d)return{type:"not_found"};let f=app.vault.getMarkdownFiles?.()??[];if(f.length===0)return{type:"not_found"};let p=mje(d),m=new Set([p]);if(!Wmt(d))for(let b of[".md",".canvas"])m.add(mje(`${d}${b}`));for(let b of f){let _=mje(b.path);if(m.has(_))return{type:"resolved",file:b}}let h=d.split("/").pop();if(h){let b=h.toLowerCase(),_=f.filter(w=>w.basename.toLowerCase()===b);if(_.length===1)return{type:"resolved",file:_[0]};if(_.length>1)return{type:"not_unique",matches:_}}let y=p.split("/").filter(Boolean);if(y.length===0)return{type:"not_found"};let g=f.filter(b=>nri(b.path,y));return g.length===1?{type:"resolved",file:g[0]}:g.length>1?{type:"not_unique",matches:g}:{type:"not_found"}}async function iri(t){try{return await app.vault.cachedRead(t)}catch(e){return Te(`readNote: failed to read ${t.path}`,e),""}}function ari(){let t=new Map,e=app.vault.getMarkdownFiles?.()??[];for(let r of e)if(r instanceof Nle.TFile){let n=t.get(r.basename)??[];n.push(r),t.set(r.basename,n)}return t}function sri(t,e,r){let n=t.trim();if(!n)return[];let o=new Map,i=app.metadataCache.getFirstLinkpathDest?.(n,e);if(i instanceof Nle.TFile&&o.set(i.path,i),!/\.[^./]+$/.test(n)){let a=n.split("/").pop()??n,s=r.get(a)??[];for(let u of s)o.set(u.path,u)}return Array.from(o.values())}function uri(t,e){if(!t)return[];let r=/\[\[([^\]]+)\]\]/g,n=new Map,o=null,i;for(;(i=r.exec(t))!==null;){if(i.index>0&&t[i.index-1]==="!")continue;let a=i[1]?.trim();if(!a)continue;let[s,u]=a.split("|"),[l,c]=s.split("#"),d=l?.trim();if(!d)continue;let f=`${d}|${u??""}|${c??""}`;if(n.has(f))continue;o||(o=ari());let p=sri(d,e.path,o);n.set(f,{linkText:d,displayText:u?.trim()||d,section:c?.trim()||void 0
`).trimEnd(),heading:d})}return i}var cri=wt.object({notePath:wt.string().min(1).describe("Fullpathtothenote(relativetothevaultroot)thatneedstoberead,suchas'Projects/plan.md'."),chunkIndex:wt.preprocess(t=>{if(typeof t=="string"){let e=t.trim();if(e.length===0)return;let r=Number(e);return Number.isFinite(r)?r:t}return t},wt.number().int().min(0)).optional().describe("0-basedchunkindextoread.Omittoreadthefirstchunk.")}),_2r=cc({name:"readNote",description:"Readasinglenoteinsearchv3sizedchunks.Useonlywhenyoualreadyknowtheexactnotepathandneeditscontents.",schema:cri,func:async({notePath:t,chunkIndex:e=0})=>{let r=t.trim();if(r.startsWith("/"))return{notePath:r,status:"invalid_path",message:"Providethenotepathrelativetothevaultrootwithoutaleadingslash."};let n=await ori(r);if(n.type==="not_found")return Te(`readNote: note not found or not a file (${r})`),{notePath:r,status:"not_found",message:`Note "${r}" was not found or is not a readable file.`};if(n.type==="not_unique")return Te(`readNote: ambiguous note path "${r}" matched multiple files`,n.matches.map(f=>f.path)),{notePath:r,status:"not_unique",message:`Multiple notes match "${r}". Provide a more specific path.`,candidates:n.matches.map(f=>({path:f.path,title:f.basename}))};let o=n.file,i=o.path,a=await iri(o),s=lri(o,a),u=s.length;if(u===0)return{notePath:i,status:"empty",message:`No readable content was found in "${i}".`};if(e>=u)return{notePath:i,status:"out_of_range",message:`Chunk index ${e} exceeds available chunks (last index ${u-1}).`,totalChunks:u};let l=s[e];F(`readNote: returning chunk ${l.chunkIndex} of ${u} for ${i}`);let c=l.chunkIndex<u-1,d=uri(l.content,o);return{notePath:i,noteTitle:o.basename,heading:l.heading,chunkId:l.id,chunkIndex:l.chunkIndex,totalChunks:u,hasMore:c,nextChunkIndex:c?l.chunkIndex+1:null,content:l.content,mtime:o.stat.mtime,linkedNotes:d.length>0?d:void 0}}});mr();mA();Xe();Fc();Ye();Xe();Fc();Ye();Bt();async function Jmt(t,e,r){try{if(!t||!t.name)return{toolName:t?.name||"unknown",result:"Error:Invalidtoolcall-missingtoolname",success:!1};let o=e.find(c=>c.name===t.name);if(!o){let c=e.map(d=>d.name).join(",");return{toolName:t.name,result:`Error: Tool '${t.name}' not found. Available tools: ${c}. Make sure you have the tool enabled in the Agent settings.`,success:!1}}let a=yd.getInstance().getToolMetadata(t.name);if(a?.isPlusOnly&&!await E0()&&!o_())return{toolName:t.name,result:`Error: ${hje(t.name)} requires a Copilot Plus subscription`,success:!1};let s={...t.args};a?.requiresUserMessageContent&&r&&(s._userMessageContent=r);let u=12e4;typeof a?.timeoutMs=="number"&&(u=a.timeoutMs);let l;return!u||u===1/0?l=await E$.callTool(o,s):l=await Promise.race([E$.callTool(o,s),new Promise((c,d)=>setTimeout(()=>d(new Error(`Tool execution timed out after ${u}ms`)),u))]),l==null?(Te(`Tool ${t.name} returned null/undefined result`),{toolName:t.name,result:JSON.stringify({message:"Toolexecutedbutreturnednoresult",status:"empty"}),success:!0}):{toolName:t.name,result:typeof l=="string"?l:JSON.stringify(l),success:!0}}catch(o){let i=zr(o);return i.includes("schema")?ne(`[ToolCall] Schema validation failed for "${t.name}". Args: ${JSON.stringify(t.args,null,2)}`):ne(`[ToolCall] Error executing "${t.name}": ${i}`),{toolName:t.name,result:`Error: ${i}`,success:!1}}}function hje(t){return t==="localSearch"?te().enableSemanticSearchV3?"vaultsearch(semantic)":"vaultsearch(index-free)":{webSearch:"websearch",getFileTree:"filetree",getCurrentTime:"currenttime",getTimeRangeMs:"timerange",getTimeInfoByEpoch:"timeinfo",convertTimeBetweenTimezones:"timezoneconverter",startPomodoro:"pomodorotimer",pomodoroTool:"pomodorotimer",youtubeTranscription:"YouTubetranscription",indexVault:"vaultindexing",indexTool:"index",writeToFile:"fileeditor",replaceInFile:"fileeditor"}[t]||t}function Kmt(t){return{localSearch:"\u{1F50D}",webSearch:"\u{1F310}",getFileTree:"\u{1F4C1}",getCurrentTime:"\u{1F552}",getTimeRangeMs:"\u{1F4C5}",getTimeInfoByEpoch:"\u{1F570}\uFE0F",convertTimeBetw
`+`Semantic search index has been refreshed with ${r} documents.`,documentCount:r}}catch(e){return{success:!1,message:`Failed to index with semantic search: ${e.message}`}}else return{success:!0,message:"Tieredlexicalretrieveruseson-demandindexing.Nomanualindexingrequired."}}}),pri=wt.object({query:wt.string().min(1).describe("Thesearchquerytosearchtheinternet"),chatHistory:wt.array(wt.object({role:wt.enum(["user","assistant"]),content:wt.string()})).describe("Previousconversationturnsforcontext(usuallyemptyarray)")}),yje=cc({name:"webSearch",description:"SearchtheINTERNET(NOTvaultnotes)whenuserexplicitlyasksforweb/onlineinformation",schema:pri,func:async({query:t,chatHistory:e})=>{try{let r=await nPe(t,e),n,o;if(o_()&&nvr()){let a=await ovr(r);n=a.content,o=a.citations}else{let a=await Ql.getInstance().webSearch(r);n=a.response.choices[0].message.content,o=a.response.citations||[]}return[{type:"web_search",content:n,citations:o,instruction:K4r()}]}catch(r){return console.error(`Error processing web search query ${t}:`,r),{error:`Web search failed: ${r}`}}}});var eht=5e5,mri=500,v2r=50,hri=wt.object({includeInline:wt.boolean().optional().describe("Includeinlinetagsinadditiontofrontmattertags.Defaultstotrue."),maxEntries:wt.number().int().min(1).max(5e3).optional().describe("Maximumnumberoftagentriestoreturn,sortedbyoccurrences.Responsesarecappedat~500KB.")}).describe("Parametersforretrievingthetaglist.");function gri(){return typeof app>"u"||!app?.metadataCache?null:app.metadataCache}function w2r(t){let e={};if(!t)return e;for(let[r,n]of Object.entries(t)){let o=r?.trim();if(!o)continue;let i=o.replace(/^#+/,"").trim().toLowerCase();if(!i)continue;let a=`#${i}`;if(a==="#")continue;let s=Number.isFinite(n)?Math.max(0,Math.floor(n)):0;e[a]=(e[a]||0)+s}return e}function yri(t,e,r){let n=t,o=w2r(n.getFrontmatterTags?.()),i=e?w2r(n.getTags?.()):{},a=new Set([...Object.keys(o),...e?Object.keys(i):[]]),s=[],u=0;for(let c of a){let d=o[c]??0,f=e?Math.max(0,i[c]??0):0,p=0,m=d;e&&(f>=d?(p=f-d,m=f):f>0&&(p=f,m=d+p)),m!==0&&(u+=m,s.push({tag:c,occurrences:m,frontmatterOccurrences:d,inlineOccurrences:p}))}s.sort((c,d)=>d.occurrences===c.occurrences?c.tag.localeCompare(d.tag):d.occurrences-c.occurrences);let l=s.slice(0,r);return{totalUniqueTags:s.length,returnedTagCount:l.length,totalOccurrences:u,includedSources:e?["frontmatter","inline"]:["frontmatter"],truncated:l.length<s.length,tags:l}}function bri(t){let e=t,r=JSON.stringify(e);if(r.length<=eht)return e;let n=e.tags.length;for(;r.length>eht&&n>v2r;)n=Math.max(v2r,Math.floor(n/2)),e={...e,tags:t.tags.slice(0,n),returnedTagCount:n,truncated:!0},r=JSON.stringify(e);return r.length>eht?{totalUniqueTags:t.totalUniqueTags,returnedTagCount:0,totalOccurrences:t.totalOccurrences,includedSources:t.includedSources,truncated:!0,tags:[],note:"Taglistexceededthesizelimit.RequestanarrowerscopeorspecifyasmallermaxEntriesvalue."}:e}function S2r(t){return`A JSON object lists the vault tags and their occurrence counts:
* totalUniqueTags: number of unique tags indexed across the vault
* returnedTagCount: number of tag entries included in this response
* totalOccurrences: total tag occurrences across included sources
* includedSources: sources represented in the counts (frontmatter, inline)
* truncated: whether the list was shortened due to limits
* tags: array of tag objects { tag, occurrences, frontmatterOccurrences, inlineOccurrences }
IMPORTANT: This tool is typically used as the first step before localSearch when searching notes by time.
EXAMPLE WORKFLOW:
1. User: "what did I do last week"
2. First call getTimeRangeMs with timeExpression: "last week"
3. Then use the returned time range with localSearch`)}),func:async({timeExpression:t})=>{lete=uii(t);returne||{error:`Unable to parse time expression: ${t}`}}});functioncii(t){lete=t.toString().length===10?t*1e3:t,r=$n.fromMillis(e);returnlii(r)}varAHr=cc({name:"getTimeInfoByEpoch",description:"Convert a Unix timestamp (in seconds or milliseconds) to detailed time information",schema:wt.object({epoch:wt.number().describe("Unix timestamp in seconds or milliseconds")}),func:async({epoch:t})=>cii(t)});asyncfunctiondii(t,e,r){letn=rgt(e),o=rgt(r);try{leti=$n.now().setZone(n),a=bVr(t,i.toJSDate());if(!a)thrownewError(`Could not parse time: ${t}`);lets=$n.fromJSDate(a,{zone:n}),u=s.setZone(o);if(!u.isValid)thrownewError("Invalid timezone conversion");letl=u.toJSDate(),c=u.offset;return{epoch:Math.floor(l.getTime()),isoString:l.toISOString(),userLocaleString:u.toLocaleString($n.DATETIME_FULL),localDateString:u.toISODate()||"",timezoneOffset:c,timezone:u.offsetNameShort||o,originalTime:s.toLocaleString($n.TIME_SIMPLE)+" "+s.offsetNameShort,convertedTime:u.toLocaleString($n.TIME_SIMPLE)+" "+u.offsetNameShort}}catch(i){thrownewError(`Failed to convert time: ${i.message}`)}}varNHr=cc({name:"convertTimeBetweenTimezones",description:"Convert a specific time from one timezone to another using UTC offsets",schema:wt.object({time:wt.string().describe(`Time to convert. Supports various formats:
- 12-hour: "6pm", "3:30 PM", "11:45 am"
- 24-hour: "18:00", "15:30", "23:45"
- Relative: "noon", "midnight"`),fromOffset:wt.string().describe(`Source UTC offset. Must be numeric, not timezone name.
Examples: "-8" for PT, "+0" for London, "+8" for Beijing`),toOffset:wt.string().describe(`Target UTC offset. Must be numeric, not timezone name.
Examples: "+9" for Tokyo, "-5" for NY, "+5:30" for Mumbai
EXAMPLE USAGE:
- "what time is 6pm PT in Tokyo" \u2192 time: "6pm", fromOffset: "-8", toOffset: "+9"
- "convert 3:30 PM EST to London time" \u2192 time: "3:30 PM", fromOffset: "-5", toOffset: "+0"
- "what is 9am Beijing time in New York" \u2192 time: "9am", fromOffset: "+8", toOffset: "-5"`)}),func:async({time:t,fromOffset:e,toOffset:r})=>dii(t,e,r)});mA();Fc();Ye();Bt();varDHr=5e4,jHr=cc({name:"youtubeTranscription",description:"Get transcripts of YouTube videos when the user provides YouTube URLs",schema:wt.object({_userMessageContent:wt.string().optional().describe("Internal: user message content injected by the system")}),func:asynct=>{let{_userMessageContent:e}=t;if(typeofe!="string")return{success:!1,message:"Invalid input: User message must be a string"};if(e.length>DHr)return{success:!1,message:`Input too long: Maximum allowed length is ${DHr} characters`};letr=M1t(e);if(r.length===0)return{success:!1,message:"No YouTube URLs found in the user prompt. URLs must be in the user prompt instead of the context notes."};letn=awaitPromise.all(r.map(asynci=>{try{leta=o_()&&te().supadataApiKey?awaitJEe(i):awaitQl.getInstance().youtube4llm(i);returna.response.transcript?{url:i,success:!0,transcript:a.response.transcript,elapsed_time_ms:a.elapsed_time_ms}:{url:i,success:!1,message:"Transcript not available. Only English videos with auto transcript enabled are supported"}}catch(a){returnconsole.error(`Error transcribing YouTube video ${i}:`,a),{url:i,success:!1,message:"An error occurred while transcribing the YouTube video"}}}));return{success:n.some(i=>i.success),results:n,total_urls:r.length}}});varfii=[{tool:gje,metadata:{id:"localSearch",displayName:"Vault Search",description:"Search through your vault notes",category:"search",copilotCommands:["@vault"],customPromptInstructions:`For localSearch (searching notes based on their contents in the vault):
- You MUST always provide both "query" (string) and "salientTerms" (array of strings)
- salientTerms MUST be extracted from the user's original query - never invent new terms
- They are keywords used for BM25 full-text search to find notes containing those exact words
- Treat every token that begins with "#" as a high-priority salient term. Keep the leading "#" and the full tag hierarchy (e.g., "#project/phase1").
- Include tagged terms alongside other meaningful words; never strip hashes or rewrite tags into plain words.
- Extract meaningful content words from the query (nouns, verbs, names, etc.)
- Exclude common words like "what", "I", "do", "the", "a", etc.
- Exclude time expressions like "last month", "yesterday", "last week"
- Preserve the original language - do NOT translate terms to English
Evaluating search results and re-searching:
- Results include a relevance quality summary: high (score \u22650.7), medium (0.3-0.7), low (<0.3)
- If most results are low relevance or miss key concepts from the user's question:
1. Try searching again with synonyms or related terms
2. Use more specific phrasing if query was too broad
3. Use more general phrasing if query was too narrow
- Example: "machine learning algorithms" returned low results \u2192 try "ML models", "neural networks", or "AI techniques"
For time-based searches (e.g., "what did I do last week"):
1. First call getTimeRangeMs with timeExpression: "last week"
2. Then use localSearch with the returned timeRange, query matching the user's question, and salientTerms: [] (empty for generic time queries)
For time-based searches with meaningful terms (e.g., "python debugging notes from yesterday"):
1. First call getTimeRangeMs with timeExpression: "yesterday"
2. Then use localSearch with the returned timeRange, query: "python debugging notes", salientTerms: ["python", "debugging", "notes"]
For exhaustive "find all" searches:
- Set returnAll: true when the user wants ALL matching notes (e.g., "find all my X", "list every Y", "show me all Z", "how many notes about W")
- Keep returnAll: false (or omit) for normal questions seeking specific information
- When setting returnAll: true, also call getFileTree to get all note titles as reference. This helps verify search completeness and identify notes the search may have missed.`}},{tool:yje,metadata:{id:"webSearch",displayName:"Web Search",description:"Search the INTERNET (NOT vault notes) when user explicitly asks for web/online information",category:"search",copilotCommands:["@websearch","@web"],customPromptInstructions:`For webSearch:
- ONLY use when the user's query contains explicit web-search intent like:
* "Google", "search online", "look up online", "search the web"
- Always provide an empty chatHistory array
Example: "search the web for python tutorials" \u2192 query: "python tutorials", chatHistory: []`}},{tool:MHr,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):
- If the user mentions a specific city, country, or timezone name (e.g., "Tokyo", "Japan", "JST"), you MUST convert it to the correct UTC offset and pass it via the timezoneOffset parameter (e.g., "+9").
- Only omit timezoneOffset when the user asks for the current local time without naming any location or timezone.
- If you cannot confidently determine the offset from the user request, ask the user to clarify before calling the tool.
Examples:
- "what time is it" (local time) \u2192 call with no parameters
- "what time is it in Tokyo" (UTC+9) \u2192 timezoneOffset: "+9"
- "what time is it in New York" (UTC-5 or UTC-4 depending on DST) \u2192 timezoneOffset: "-5"`}},{tool:AHr,metadata:{id:"getTimeInfoByEpoch",displayName:"Get Time Info",description:"Convert epoch timestamp to human-readable format",category:"time",isAlwaysEnabled:!0}},{tool:IHr,metadata:{id:"getTimeRangeMs",displayName:"Get Time Range",description:"Convert time expressions to date ranges",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For time-based queries:
- Use this tool to convert time expressions like "last week", "yesterday", "last month" to proper time ranges
- This is typically the first step before using localSearch with a time range
Example: For "last week" \u2192 timeExpression: "last week"`}},{tool:NHr,metadata:{id:"convertTimeBetweenTimezones",displayName:"Convert Timezones",description:"Convert time between different timezones",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For timezone conversions:
Example: "what time is 6pm PT in Tokyo" (PT is UTC-8 or UTC-7, Tokyo is UTC+9) \u2192 time: "6pm", fromOffset: "-8", toOffset: "+9"`}},{tool:_2r,metadata:{id:"readNote",displayName:"Read Note",description:"Read a specific note in sequential chunks using its own line-chunking logic.",category:"file",requiresVault:!0,isAlwaysEnabled:!0,customPromptInstructions:`For readNote:
- Decide based on the user's request: only call this tool when the question requires reading note content.
- If the user asks about a note title that is already mentioned in the current or previous turns of the conversation, or linked in <active_note> or <note_context> blocks, call readNote directly\u2014do not use localSearch to look it up. Even if the note title mention is partial but similar to what you have seen in the context, try to infer the correct note path from context. Skip the tool when a note is irrelevant to the user query.
- If the user asks about notes linked from that note, read the original note first, then follow the "linkedNotes" paths returned in the tool result to inspect those linked notes.
- Always start with chunk 0 (omit chunkIndex or set it to 0). Only request the next chunk if the previous chunk did not answer the question.
- Pass vault-relative paths without a leading slash. If a call fails, adjust the path (for example, add ".md" or use an alternative candidate) and retry only if necessary.
- Every tool result may include a "linkedNotes" array. If the user needs information from those linked notes, call readNote again with one of the provided candidate paths, starting again at chunk 0. Do not expand links you don't need.
- Stop calling readNote as soon as you have the required information.
- Always call getFileTree to get the exact note path if it is not provided in the context before calling readNote.
Examples:
- First chunk: notePath: "Projects/launch-plan.md" (chunkIndex omitted or 0)
- Next chunk: notePath: "Projects/launch-plan.md", chunkIndex: 1`}},{tool:fje,metadata:{id:"writeToFile",displayName:"Write to File",description:"Create or modify files in your vault",category:"file",requiresVault:!0,timeoutMs:0,copilotCommands:["@composer"],customPromptInstructions:`For writeToFile:
- NEVER display the file content directly in your response
- Always pass the complete file content to the tool
- Include the full path to the file
- You MUST explicitly call writeToFile for any intent of updating or creating files
- Do not call writeToFile tool again if the result is not accepted
- Do not call writeToFile tool if no change needs to be made
- Always create new notes in root folder or folders the user explicitly specifies
- When creating a new note in a folder, you MUST use getFileTree to get the exact folder path first
Examples:
- Basic: path: "path/to/note.md", content: "FULL CONTENT OF THE NOTE"
- Skip confirmation: path: "path/to/note.md", content: "FULL CONTENT", confirmation: false`}},{tool:h2r,metadata:{id:"replaceInFile",displayName:"Replace in File",description:"Make targeted changes to existing files using SEARCH/REPLACE blocks",category:"file",requiresVault:!0,timeoutMs:0,customPromptInstructions:`For replaceInFile:
- Remember: Small edits \u2192 replaceInFile, Major rewrites \u2192 writeToFile
- SEARCH text must match EXACTLY including all whitespace
- The diff parameter uses SEARCH/REPLACE block format
Example: To add "Bob Johnson" to attendees list in notes/meeting.md:
path: "notes/meeting.md"
diff: "------- SEARCH\\n## Attendees\\n- John Smith\\n- Jane Doe\\n=======\\n## Attendees\\n- John Smith\\n- Jane Doe\\n- Bob Johnson\\n+++++++ REPLACE"`}},{tool:jHr,metadata:{id:"youtubeTranscription",displayName:"YouTube Transcription",description:"Get transcripts from YouTube videos",category:"media",isPlusOnly:!0,requiresUserMessageContent:!0,customPromptInstructions:`For youtubeTranscription:
- Use when user provides YouTube URLs
- No parameters needed - the tool will process URLs from the conversation`}}];functionpii(t){yd.getInstance().register({tool:b2r(t.getRoot()),metadata:{id:"getFileTree",displayName:"File Tree",description:"Browse vault file structure",category:"file",isAlwaysEnabled:!0,requiresVault:!0,isBackground:!0,customPromptInstructions:`For getFileTree:
- Use to browse the vault's file structure including paths of notes and folders
- Always call this tool to explore the exact path of notes or folders when you are not given the exact path.
- DO NOT use this tool to look up note contents or metadata - use localSearch or readNote instead.
- No parameters needed
Example queries that should use getFileTree:
- "Create a new note in the projects folder" \u2192 call getFileTree to get the exact folder path
- "Create a new note using the quick note template" \u2192 call getFileTree to look up the template path
- "How many files are in the projects folder" \u2192 call getFileTree to list all files`}})}functionmii(){yd.getInstance().register({tool:C2r(),metadata:{id:"getTagList",displayName:"Tag List",description:"List vault tags with occurrence statistics",category:"file",isAlwaysEnabled:!0,requiresVault:!0,isBackground:!0,customPromptInstructions:`For getTagList:
- Use to inspect existing tags before suggesting new ones or reorganizing notes.
- Omit parameters to include both frontmatter and inline tags.
- Set includeInline to false when you only need frontmatter-defined tags.
- Use maxEntries to limit output for very large vaults.
Examples:
- Default (all tags): call with no parameters
- Frontmatter only: includeInline: false`}})}functionhii(){yd.getInstance().register({tool:pje,metadata:{id:"updateMemory",displayName:"Update Memory",description:"Save information to user memory when the user explicitly asks to remember something or update the memory",category:"memory",copilotCommands:["@memory"],isAlwaysEnabled:!0,customPromptInstructions:`For updateMemory:
- Use this tool to update the memory when the user explicitly asks to update the memory
- DO NOT use for general information - only for personal facts, preferences, or specific things the user wants stored
Example: statement: "I'm studying Japanese and I'm preparing for JLPT N3"`}})}functioneZ(t){lete=yd.getInstance(),r=te(),n=e.getToolMetadata("getFileTree")!==void0,o=t!==void0,i=e.getToolMetadata("updateMemory")!==void0,a=r.enableSavedMemory;(e.getAllTools().length===0||n!==o||i!==a)&&(e.clear(),e.registerAll(fii),t&&(pii(t),mii()),r.enableSavedMemory&&hii())}Bt();Bt();varHje=class{constructor(e,r){this.toolManager=e;this.writeToFileTool=r;this.buffer=""}findCompleteBlock(e){letr=/<writeToFile>[\s\S]*?<\/writeToFile>/,n=e.match(r);return!n||n.index===void0?null:{block:n[0],endIdx:n.index+n[0].length}}async*processChunk(e){letr="";if(Array.isArray(e.content))for(letoofe.content)o.type==="text"&&o.text!=null&&(r+=o.text);elsee.content!=null&&(r=e.content);r&&(this.buffer+=r),yielde;letn=this.findCompleteBlock(this.buffer);for(;n;){let{block:o,endIdx:i}=n,a=o.match(/<path>([\s\S]*?)<\/path>/),s=o.match(/<content>([\s\S]*?)<\/content>/),u=a?a[1].trim():void0,l=s?s[1].trim():void0;try{letc=awaitthis.toolManager.callTool(this.writeToFileTool,{path:u,content:l}),d=P$.format("writeToFile",c);yield{...e,content:`
`||t==="\r"}functionRc(t){returntypeoft!="string"?"":t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}functionJHr(t){returntypeoft!="string"?"":t.replace(/'/g,"'").replace(/"/g,'"').replace(/>/g,">").replace(/</g,"<").replace(/&/g,"&")}ra();varaN=classextendsjD{constructor(){super(...arguments);this.lastCitationSources=null}getAvailableToolsForPlanning(){letr=yd.getInstance();returnr.getAllTools().length===0&&eZ(this.chainManager.app?.vault),r.getAllTools().map(o=>o.tool).filter(o=>o.name==="getCurrentTime"||o.name==="convertTimeBetweenTimezones"||o.name==="getTimeInfoByEpoch"||o.name==="getTimeRangeMs"||o.name==="getFileTree")}asyncplanToolCalls(r,n){leto=this.getAvailableToolsForPlanning();if(typeofn.bindTools!="function")returnTe("[CopilotPlus] Model does not support native tool calling, skipping tool planning"),{toolCalls:[],salientTerms:this.extractSalientTermsFromQuery(r),returnAll:!1};leti=n.bindTools(o),s=[{role:Mte(n),content:`You are a helpful AI assistant. Analyze the user's message and determine if any tools should be called.
Guidelines:
- Use tools when the user's request requires external information or computation
- For time-related queries, use getTimeRangeMs to convert time expressions to timestamps
- For file structure queries, use getFileTree to explore the vault
- If no tools are needed, respond with your analysis
After analyzing, extract key search terms from the user's message that would be useful for searching notes:
- Extract meaningful nouns, topics, and specific concepts
- Preserve the EXACT words and language from the user's message (works for any language)
- Exclude time expressions (those are handled by tools)
Include your extracted terms as: [SALIENT_TERMS: term1, term2, term3]
If the user wants ALL matching notes (e.g., "find all my X", "list every Y", "show me all Z", "how many notes about W"), output: [RETURN_ALL: true]
Otherwise omit RETURN_ALL or output: [RETURN_ALL: false]`},{role:"user",content:r}];F("[CopilotPlus] Requesting tool planning with native tool calling...");letu=awaitVb(()=>i.invoke(s)),l=u.tool_calls||[],c=typeofu.content=="string"?u.content:String(u.content);F("[CopilotPlus] Native tool calls:",l.length);let{salientTerms:d,returnAll:f}=this.extractPlanningFieldsFromResponse(c,r),p=[];for(letmofl){leth=o.find(y=>y.name===m.name);h?(p.push({tool:h,args:m.args}),F(`[CopilotPlus] Tool call: ${m.name}`,m.args)):Te(`[CopilotPlus] Tool '${m.name}' not found in available tools`)}return{toolCalls:p,salientTerms:d,returnAll:f}}extractPlanningFieldsFromResponse(r,n){leto,i=r.match(/\[SALIENT_TERMS:\s*([^\]]+?)\s*\]/i);if(i){letu=i[1].split(",").map(l=>l.trim()).filter(l=>l.length>0);o=u.length>0?u:this.extractSalientTermsFromQuery(n)}elseo=this.extractSalientTermsFromQuery(n);leta=r.match(/\[RETURN_ALL:\s*(true|false)\s*\]/i),s=a?a[1].toLowerCase()==="true":!1;return{salientTerms:o,returnAll:s}}extractSalientTermsFromQuery(r){returnr.split(/[\s\p{P}]+/u).filter(n=>n.length>=3).slice(0,10)}asyncprocessAtCommands(r,n,o){leti=r.toLowerCase(),a=this.removeAtCommands(r),s=[...n];if(i.includes("@vault")&&(s.some(l=>l.tool.name==="localSearch")||s.push({tool:gje,args:{query:a,salientTerms:o.salientTerms,timeRange:o.timeRange,returnAll:o.returnAll===!0?!0:void0}})),(i.includes("@websearch")||i.includes("@web"))&&!s.some(l=>l.tool.name==="webSearch")){letc=awaitry.instance.getCurrentChainManager().memoryManager.getMemory().loadMemoryVariables({}),d=gye(c);s.push({tool:yje,args:{query:a,chatHistory:d}})}returni.includes("@memory")&&(s.some(l=>l.tool.name==="updateMemory")||s.push({tool:pje,args:{statement:a}})),s}removeAtCommands(r){returnr.split(" ").filter(n=>!OX.includes(n.toLowerCase())).join(" ").trim()}asyncprocessImageUrls(r){letn=[],o=await_H.processUrlBatch(r,n,this.chainManager.app.vault);return_H.showFailedImagesNotice(n),o}asyncprocessChatInputImages(r){letn=[],o=await_H.processChatImageBatch(r,n,this.chainManager.app.vault);return_H.showFailedImagesNotice(n),o}asyncextractImagesFromContextBlock(r,n){leti=newRegExp(`<${n.tagName}>([\\s\\S]*?)<\\/${n.tagName}>`).exec(r);if(!i)return[];leta=i[1],u=/<content>([\s\S]*?)<\/content>/.exec(a),l=u?JHr(u[1]):"";if(!l)return[];letd=newRegExp(`<${n.identifierTag}>(.*?)<\\/${n.identifierTag}>`).exec(a),f=d?d[1]:void0;F(`[CopilotPlus] Extracting images from ${n.displayName}:`,f||`no ${n.identifierTag}`);letp=n.useForResolution?f:void0;returnthis.extractEmbeddedImages(l,p)}asyncextractEmbeddedImages(r,n){leto=/!\[\[(.*?\.(png|jpg|jpeg|gif|webp|bmp|svg))\]\]/g,i=[],a=[...r.matchAll(o)];for(letuofa){letl=u[1];if(n){letc=app.metadataCache.getFirstLinkpathDest(l,n);c?i.push(c.path):(Te(`Could not resolve embedded image: ${l} from source: ${n}`),i.push(l))}elsei.push(l)}lets=HHr(r);for(letuofs){if(!u)continue;if(u.match(/^https?:\/\//)){i.push(u);continue}letl=u.replace(/^\.\//,"").replace(/^\//,"");if(n){letc=app.metadataCache.getFirstLinkpathDest(l,n);c?i.push(c.path):i.push(l)}elsei.push(l)}returni}asyncbuildMessageContent(r,n){leto=[],i=[],a=te(),s=[];if(a.passMarkdownImages){letd=n.contextEnvelope;if(!d)thrownewError("[CopilotPlus] Context envelope is required but not available. Cannot extract images.");letf=d.layers.find(p=>p.id==="L3_TURN");if(f){letp=[{tagName:"active_note",identifierTag:"path",displayName:"active note",useForResolution:!0},{tagName:"active_web_tab",identifierTag:"url",displayName:"active web tab",useForResolution:!1}];for(letmofp){leth=awaitthis.extractImagesFromContextBlock(f.text,m);h.length>0&&s.push({urls:h,type:"embedded"})}}}for(letdofs){letf=awaitthis.processImageUrls(d.urls);i.push(...f.successfulImages),o.push(...f.failureDescriptions)}letu=n.content;if(u&&u.length>0){letd=awaitthis.processChatInputImages(u);i.push(...d.successfulImages),o.push(...d.failureDescriptions)}letl=r;o.length>0&&(l=`${r}
${o}`}asyncstreamMultimodalResponse(r,n,o,i,a,s,u){letl=this.chainManager.memoryManager.getMemory(),c=this.chainManager.chatModelManager.getChatModel(),d=this.isMultimodalModel(c),f=[],p=n.contextEnvelope;if(!p)thrownewError("[CopilotPlus] Context envelope is required but not available. Cannot proceed with CopilotPlus chain.");F("[CopilotPlus] Using envelope-based context construction");letm=_A.convert(p,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),h=m.find(w=>w.role==="system");h&&f.push({role:Mte(c),content:h.content}),awaitOq(l,f);lety=m.find(w=>w.role==="user");if(y){letw,T=o.length>0,O=P=>{letR="[User query]:";if(P.includes(R))returnP;letI=P.trimEnd(),N=[];I.length>0&&N.push(I);letz=s.trim()||n.originalMessage?.trim()||"";returnz.length>0?N.push(`${R}
</localSearch>`,a="Search results were in an unexpected format.",{formattedForLLM:i,formattedForDisplay:a,sources:o};UHr(u),o=kHr(u),i=this.prepareLocalSearchResult(u,n||""),a=P$.format("localSearch",i)}catch(s){Te("Failed to parse localSearch results:",s);let u=FHr(r.result);i=n?`<localSearch timeRange="${n}">
`)}var oW=class{constructor(e){this.modelName=e}buildToolSpecificInstructions(e){let r=[];for(let o of e)o.customPromptInstructions&&r.push(o.customPromptInstructions);let n=this.buildCopilotCommandInstructions(e);return n&&r.push(n),r.length>0?r.join(`
`):""}buildCopilotCommandInstructions(e){let r=[];for(let n of e)if(!(!n.copilotCommands||n.copilotCommands.length===0))for(let o of n.copilotCommands)r.push(`-${o}:callthetoolnamed${n.id}`);return r.length===0?null:["When the user explicitly includes a Copilot command alias (e.g., @vault) in their message, treat it as a direct request to call the mapped tool before proceeding.","Honor these aliases exactly (case-insensitive):",...r,"If the referenced tool is unavailable, explain that the command cannot be fulfilled instead of ignoring it."].join(`
`)}enhanceSystemPrompt(e,r,n,o){let i=this.buildSystemPromptSections(e,r,n,o);return cgt(i)}buildSystemPromptSections(e,r,n,o){let i=o||[],a=this.buildToolSpecificInstructions(i).trim(),u=[{id:"base-system-prompt",label:"System prompt with memory",source:"src/system-prompts/systemPromptBuilder.ts#getSystemPromptWithMemory",content:e.trimEnd()},{id:"autonomous-agent-intro",label:"Autonomous agent introduction",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildSystemPromptSections",content:`#AutonomousAgentMode
If multiple results or no result, you should ask the user to provide a more specific path.
`}),a.length>0&&u.push({id:"tool-specific-instructions",label:"Tool-specific instructions",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildToolSpecificInstructions",content:a}),u.push({id:"general-guidelines",label:"General guidelines",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildSystemPromptSections",content:`## 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
- 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'llreceivetheresultsandcandecidewhethertousemoretoolsorprovideyourfinalresponse.
- For localSearch: OMIT timeRange if not doing time-based search`):u.push("CRITICAL FOR GPT MODELS: You MUST use tools when the user'srequestrequiresthem.Donotjustdescribewhatyouplantodo-actuallycallthetools."),s&&u.push(`\u{1F6A8} FILE EDITING WITH COMPOSER TOOLS \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. Call the tool immediately - do not just describe what you plan to do
For replaceInFile, the diff parameter must use SEARCH/REPLACE format:
------- SEARCH
content to find
=======
replacement content
+++++++ REPLACE
\u274C WRONG: "I'll help you add item 4 to the list. Let me update that for you." [No tool call = FAILURE]
\u2705 CORRECT: Actually call replaceInFile or writeToFile with proper parameters`),u.push("FINAL REMINDER FOR GPT MODELS: If the user asks you to search, find, edit, or modify anything, you MUST call the appropriate tool immediately. Do not wait for another turn.");let l=u.join(`
\u{1F6A8} GPT REMINDER: Use replaceInFile for small edits (with SEARCH/REPLACE blocks in diff parameter).`:e}needsSpecialHandling(){return!0}},sgt=class extends oW{isThinkingModel(){return this.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")||this.modelName.includes("claude-opus-4")}isClaudeSonnet4(){return this.modelName.includes("claude-sonnet-4")||this.modelName.includes("claude-4-sonnet")||this.modelName.includes("claude-sonnet-4-20250514")}buildSystemPromptSections(e,r,n,o){let i=super.buildSystemPromptSections(e,r,n,o);if(!this.isThinkingModel())return i;let a=[`IMPORTANT FOR CLAUDE THINKING MODELS:
- You are a thinking model with internal reasoning capability
- Your thinking process will be automatically wrapped in <think> tags - do not manually add thinking tags
- Call tools AFTER your thinking is complete
- Do not provide final answers before using tools - use tools first, then provide your response based on the results
CORRECT FLOW FOR THINKING MODELS:
1. Think through the problem (this happens automatically)
2. Use tools to gather information
3. Wait for tool results
4. Provide final response based on gathered information
INCORRECT: Providing a final answer before using tools
CORRECT: Using tools first, then providing answer based on results`];return this.isClaudeSonnet4()&&a.push(`\u{1F6A8} CRITICAL INSTRUCTIONS FOR CLAUDE SONNET 4 - AUTONOMOUS AGENT MODE \u{1F6A8}
\u26A0\uFE0F WARNING: You have a specific tendency to write complete responses immediately after tool calls. This BREAKS the autonomous agent pattern!
I'll search your vault for piano practice information.
[Call localSearch tool]
[RESPONSE ENDS HERE - NO MORE TEXT]
\u274C WRONG PATTERN (DO NOT DO THIS):
[Call tool]
Based on the search results, here'sacompletepracticeplan...
[ThisisFORBIDDEN-youhaven'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.push({id:"claude-thinking-guidelines",label:"Claude thinking model guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#ClaudeModelAdapter.buildSystemPromptSections",content:a.join(`
\u2705 CORRECT: Call localSearch immediately with the user's topic as the query`:""}`.trim()];return u.push(`GEMINI SPECIFIC RULES:
1. When user mentions "mynotes" about X \u2192 use localSearch with query "X"
2. DO NOT ask clarifying questions about search terms
3. DO NOT wait for permission to use tools
4. Use tools based on the user's request
\u{1F6A8} CRITICAL: SEQUENTIAL vs PARALLEL TOOL CALLS \u{1F6A8}
When one tool's OUTPUT is needed as INPUT to another tool, you MUST make them in SEPARATE responses:
1. Call the FIRST tool
2. STOP and wait for the result
3. In the NEXT response, use the result from step 1 in the SECOND tool call
\u274C WRONG (DO NOT DO THIS):
User: "Recapmylastweek"
- Call getTimeRangeMs AND localSearch together with made-up timeRange values
- This is WRONG because you're hallucinating the timeRange values!
\u2705 CORRECT (DO THIS):
User: "Recapmylastweek"
- FIRST: Call getTimeRangeMs with timeExpression "lastweek"
- WAIT for result
- SECOND: Call localSearch using the actual timeRange from the result
RULE: NEVER make up or guess parameter values. If you need a tool's output, call that tool FIRST, then WAIT for the result.
Remember: The user has already told you what to do. Execute it NOW with the available tools.`),i.push({id:"gemini-specific-guidelines",label:"Gemini-specificguidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#GeminiModelAdapter.buildSystemPromptSections",content:u.join(`
`)}),i}enhanceUserMessage(e,r){return r?`${e}
REMINDER: Use the tools immediately. Do not ask questions. For "mynotes", use localSearch.`:e}needsSpecialHandling(){return!0}},lgt=class extends oW{buildSystemPromptSections(e,r,n,o){let i=super.buildSystemPromptSections(e,r,n,o);return i.push({id:"copilot-plus-guidelines",label:"CopilotPlusmodelguidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#CopilotPlusModelAdapter.buildSystemPromptSections",content:`\u{1F6A8} CRITICAL: NO HALLUCINATED TOOL CALLS OR SOURCES \u{1F6A8}
You are a Copilot Plus model. You MUST follow these rules strictly:
## Tool Call Integrity
- You can ONLY reference results from tools you have ACTUALLY called in this conversation
- NEVER claim to have performed a web search unless you called the webSearch tool AND received results
- NEVER claim to have searched notes unless you called localSearch AND received results
- If you want to search the web, you MUST call the webSearch tool first - do not make up results
## Citation Rules
- Every citation [1], [2], etc. MUST correspond to a real source returned by a tool
- Do NOT invent sources like "GeneralwebsearchresultsforX" unless webSearch was actually called
- If you only called localSearch, your citations can ONLY reference notes from that search
- Count your actual tool calls - if you only made 1 tool call, you cannot have citations from multiple different tools
`),m.responseMetadata),this.lastDisplayedContent="",m.finalResponse}catch(m){if(this.stopReasoningTimer(),m.name==="AbortError"||n.signal.aborted)return F("Autonomousagentstreamabortedbyuser",{reason:n.signal.reason}),"";ne("Autonomousagentfailed,fallingbacktoregularPlusmode:",m);try{return await new aN(this.chainManager).run(r,n,o,i,a)}catch(h){ne("FallbacktoregularPlusmodealsofailed:",h),this.lastDisplayedContent&&c.processChunk({content:this.lastDisplayedContent});let y=zr(m),g=`
Fallback to regular Plus mode also failed: `+zr(h);await this.handleError(new Error(y+g),c.processErrorChunk.bind(c));let b=c.close().content;return this.handleResponse(b,r,n,i,o,void 0,b)}}}async prepareAgentConversation(r,n,o){let i=[],a=this.getAvailableTools(),s=n.modelName||n.model||"unknown";if(typeof n.bindTools!="function")throw new Error(`Model ${s} does not support native tool calling (bindTools not available). Agent mode requires a model with tool calling support.`);let u=n.bindTools(a),l={availableTools:a,boundModel:u,processLocalSearchResult:this.processLocalSearchResult.bind(this),applyCiCOrderingToLocalSearchResult:this.applyCiCOrderingToLocalSearchResult.bind(this)},c=r.contextEnvelope,d=_A.convert(c,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),f=this.chainManager.memoryManager.getMemory(),p=d.find(E=>E.role==="system"),m=yd.getInstance(),y=a.map(E=>m.getToolMetadata(E.name)).filter(E=>E!==void 0).filter(E=>E.customPromptInstructions).map(E=>`For ${E.displayName}: ${E.customPromptInstructions}`).join(`
`),g=[p?.content||"",y?`
## Tool Guidelines
${y}`:""].filter(Boolean).join(`
`);g&&i.push(new Od({content:g}));let w=c.layers.find(E=>E.id==="L5_USER")?.text||""||r.originalMessage||r.message,T=[];await Oq(f,T);for(let E of T)E.role==="user"?i.push(new qs(E.content)):i.push(new Pn(E.content));let O=d.find(E=>E.role==="user");if(O){let P=this.isMultimodalModel(n)?await this.buildMessageContent(O.content,r):O.content;i.push(new qs(P))}return{messages:i,collectedSources:[],originalUserPrompt:w,loopDeps:l}}async runReActLoop(r){let{boundModel:n,tools:o,messages:i,originalPrompt:a,abortController:s,updateCurrentAiMessage:u,processLocalSearchResult:l,applyCiCOrderingToLocalSearchResult:c}=r,d=te().autonomousAgentMaxIterations,f=[],p=Date.now(),m=0,h;for(;m<d&&!s.signal.aborted;){let T=Date.now()-p;if(T>=EWe){Te(`Agent loop timed out after ${Math.round(T/1e3)}s`);break}m++;let{content:O,aiMessage:E,streamingResult:P}=await this.streamModelResponse(n,i,s,u);h={wasTruncated:P.wasTruncated,tokenUsage:P.tokenUsage??void 0};let R=E.tool_calls||[];if(R.length===0){this.stopReasoningTimer(),this.reasoningState.status="complete",i.push(E);let I=O,N=this.buildReasoningBlockMarkup(),z=20,V=5,k="";for(let B=0;B<I.length&&!s.signal.aborted;B+=z){k+=I.slice(B,B+z);let Q=N?N+`
`+k:k;u(Q),B+z<I.length&&await new Promise(Y=>setTimeout(Y,V))}let X=N?N+`
`+I:I;return u(X),{finalResponse:X,sources:f,responseMetadata:h}}if(i.push(E),m>1&&O&&O.trim().length>0){let I=QHr(O);I&&this.addReasoningStep(I)}for(let I of R){if(s.signal.aborted)break;let N={name:I.name,args:I.args},z;if(I.name==="localSearch"){let Y=N.args.query;if(Y)try{let oe=await new g9({getChatModel:async()=>this.chainManager.chatModelManager.getChatModel()}).expand(Y),ue=new Set,de=[],L=W=>{if(typeof W!="string")return;let ie=W.trim();if(!ie||ie==="[objectObject]"||ie.startsWith("[object"))return;let j=ie.toLowerCase();ue.has(j)||(ue.add(j),de.push(ie))};oe.originalQuery&&L(oe.originalQuery),(oe.salientTerms||[]).forEach(L),(oe.expandedQueries||[]).forEach(L),z={originalQuery:oe.originalQuery,salientTerms:oe.salientTerms,expandedQueries:oe.expandedQueries,recallTerms:de}}catch{}}let V=fgt(I.name,N.args,z);this.addReasoningStep(V,I.name),z&&(N.args._preExpandedQuery=z),Gmt(N,m);let k=await Jmt(N,o,a),X;if(I.name==="localSearch"&&k.success){let Y=l(k);f.push(...Y.sources),X={titles:Y.sources.map(K=>K.title),count:Y.sources.length},k.result=c(Y.formattedForLLM,a||"")}Xmt(I.name,k);let B=YHr(I.name,k,X,N.args);this.addReasoningStep(B,I.name);let Q=pst(I.id||tPe(),I.name,k.result);i.push(Q)}}this.stopReasoningTimer(),this.reasoningState.status="complete";let y=this.buildReasoningBlockMarkup();if(s.signal.aborted){if(F("Agentreasoninginterruptedbyuser"),this.abortHandledByTimer)return{finalResponse:"",sources:f,responseMetadata:h};let T="Theresponsewasinterrupted.";return{finalResponse:y?y+`
`+T:T,sources:f,responseMetadata:h}}let g=Date.now()-p,b=g>=EWe;b?Te(`Agent loop timed out after ${Math.round(g/1e3)}s`):Te(`Agent reached max iterations (${d})`);let _=b?"I've reached the time limit for reasoning. Here'swhatIfoundsofarbasedonthesearchresults.":"I've reached the maximum number of tool calls. Here'swhatIfoundsofarbasedonthesearchresults.";return{finalResponse:y?y+`
`+_:_,sources:f,responseMetadata:h}}async streamModelResponse(r,n,o,i){let a=new Map,s=new dv(()=>{},!0);try{let u=await Vb(()=>r.stream(n,{signal:o.signal}));for await(let p of u){if(o.signal.aborted)break;if(p.response_metadata?.finish_reason==="MALFORMED_FUNCTION_CALL")throw Te("BackendreturnedMALFORMED_FUNCTION_CALL-fallingbacktonon-agentmode"),new Error("MALFORMED_FUNCTION_CALL:Modeldoesnotsupportnativetoolcalling");let h=p.tool_call_chunks;if(h&&Array.isArray(h))for(let y of h){let g=y.index??0,b=a.get(g)||{name:"",args:""};y.id&&(b.id=y.id),y.name&&(b.name+=y.name),y.args&&(b.args+=y.args),a.set(g,b)}s.processChunk(p)}let l=s.close(),c=l.content,d=rPe(a),f=new Pn({content:c,tool_calls:d.map(p=>({id:p.id,name:p.name,args:p.args,type:"tool_call"}))});return{content:c,aiMessage:f,streamingResult:l}}catch(u){if(ne(`Stream error: ${u.message}`),u.name==="AbortError"||o.signal.aborted){let l=s.close();return{content:l.content,aiMessage:new Pn({content:l.content}),streamingResult:l}}throw u}}};Xe();Ye();Bt();lw();FS();var Q3r=require("obsidian");CX();var Vce=[{tag:"note_context",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"active_note",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"embedded_note",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"vault_note",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"retrieved_document",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"url_content",sourceType:"url",recoverable:!0,sourceExtractor:"url"},{tag:"web_tab_context",sourceType:"url",recoverable:!0,sourceExtractor:"url"},{tag:"active_web_tab",sourceType:"url",recoverable:!0,sourceExtractor:"url"},{tag:"youtube_video_context",sourceType:"youtube",recoverable:!0,sourceExtractor:"url"},{tag:"twitter_content",sourceType:"url",recoverable:!0,sourceExtractor:"url"},{tag:"embedded_pdf",sourceType:"pdf",recoverable:!0,sourceExtractor:"name"},{tag:"selected_text",sourceType:"selected_text",recoverable:!1,sourceExtractor:null},{tag:"web_selected_text",sourceType:"selected_text",recoverable:!1,sourceExtractor:null},{tag:"localSearch",sourceType:"note",recoverable:!0,sourceExtractor:null}],Jje=new Map;for(let t of Vce)Jje.set(t.tag,t);function iW(t){return Jje.get(t)?.sourceType??"unknown"}function Kje(t){return Jje.get(t)?.recoverable??!1}function tZ(t,e){let r=Jje.get(e);if(!r?.sourceExtractor)return"";let n=r.sourceExtractor;return new RegExp(`<${n}>([^<]+)</${n}>`).exec(t)?.[1]??""}function Hce(t){let e=/<content>([\s\S]*?)<\/content>/.exec(t);return e?e[1]:t}function pgt(t){return t.match(/^<(\w+)[\s>]/)?.[1]??null}var nS={previewCharsPerSection:500,maxSections:20,verbatimThreshold:5e3};function aW(t,e=500,r=20){let n=t.split(/(?=^#{1,6}\s+)/m).filter(s=>s.trim());if(n.length<=1)return mgt(t,e*4);let o=n.slice(0,r),i=n.length>r,a=o.map(s=>{let u=s.trim().split(`
[${o.length} search results - use localSearch to re-query]
${a}
</prior_context>`}functionjii(t,e={}){let{content:r,notePath:n,noteTitle:o,...i}=t;if(!r||typeofr!="string")returnt;leta=e.previewCharsPerSection??nS.previewCharsPerSection,s=e.maxSections??nS.maxSections,u=aW(r,a,s);return{...i,notePath:n,noteTitle:o,content:`[COMPACTED - use readNote to get full content]
${u}`,_wasCompacted:!0}}Ye();nye();FS();var$ii=`Progressively summarize the lines of conversation provided, adding onto the previous summary returning a new summary.
EXAMPLE
Current summary:
The human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good.
New lines of conversation:
Human: Why do you think artificial intelligence is a force for good?
AI: Because artificial intelligence will help humans reach their full potential.
New summary:
The human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good because it will help humans reach their full potential.
END OF EXAMPLE
Current summary:
{summary}
New lines of conversation:
{new_lines}
New summary:`,t3r=newmu({inputVariables:["summary","new_lines"],template:$ii}),Lii=`You are an assistant to a human, powered by a large language model trained by OpenAI.
You are designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, you are able to generate human-like text based on the input you receive, allowing you to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.
You are constantly learning and improving, and your capabilities are constantly evolving. You are able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. You have access to some personalized information provided by the human in the Context section below. Additionally, you are able to generate your own text based on the input you receive, allowing you to engage in discussions and provide explanations and descriptions on a wide range of topics.
Overall, you are a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether the human needs help with a specific question or just wants to have a conversation about a particular topic, you are here to assist.
Context:
{entities}
Current conversation:
{history}
Last line:
Human: {input}
You:`,r3r=newmu({inputVariables:["entities","history","input"],template:Lii}),Fii=`You are an AI assistant reading the transcript of a conversation between an AI and a human. Extract all of the proper nouns from the last line of conversation. As a guideline, a proper noun is generally capitalized. You should definitely extract all names and places.
The conversation history is provided just in case of a coreference (e.g. "What do you know about him" where "him" is defined in a previous line) -- ignore items mentioned there that are not in the last line.
Return the output as a single comma-separated list, or NONE if there is nothing of note to return (e.g. the user is just issuing a greeting or having a simple conversation).
EXAMPLE
Conversation history:
Person #1: my name is Jacob. how's it going today?
AI: "It's going great! How about you?"
Person #1: good! busy working on Langchain. lots to do.
AI: "That sounds like a lot of work! What kind of things are you doing to make Langchain better?"
Last line:
Person #1: i'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff.
Output: Jacob,Langchain
END OF EXAMPLE
EXAMPLE
Conversation history:
Person #1: how's it going today?
AI: "It's going great! How about you?"
Person #1: good! busy working on Langchain. lots to do.
AI: "That sounds like a lot of work! What kind of things are you doing to make Langchain better?"
Last line:
Person #1: i'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff. I'm working with Person #2.
Output: Langchain, Person #2
END OF EXAMPLE
Conversation history (for reference only):
{history}
Last line of conversation (for extraction):
Human: {input}
Output:`,n3r=newmu({inputVariables:["history","input"],template:Fii}),kii=`You are an AI assistant helping a human keep track of facts about relevant people, places, and concepts in their life. Update and add to the summary of the provided entity in the "Entity" section based on the last line of your conversation with the human. If you are writing the summary for the first time, return a single sentence.
The update should only include facts that are relayed in the last line of conversation about the provided entity, and should only contain facts about the provided entity.
If there is no new information about the provided entity or the information is not worth noting (not an important or relevant fact to remember long-term), output the exact string "UNCHANGED" below.
Full conversation history (for context):
{history}
Entity to summarize:
{entity}
Existing summary of {entity}:
{summary}
Last line of conversation:
Human: {input}
Updated summary (or the exact string "UNCHANGED" if there is no new information about {entity} above):`,o3r=newmu({inputVariables:["entity","summary","history","input"],template:kii});nye();Jo();kL();zL();vS();ta();varqii={};$t(qii,{BaseChatMessageHistory:()=>Uii,BaseListChatMessageHistory:()=>i3r,InMemoryChatMessageHistory:()=>Wce});varUii=classextendsCg{asyncaddMessages(t){for(leteoft)awaitthis.addMessage(e)}},i3r=classextendsCg{addUserMessage(t){returnthis.addMessage(newqs(t))}addAIMessage(t){returnthis.addMessage(newPn(t))}asyncaddMessages(t){for(leteoft)awaitthis.addMessage(e)}clear(){thrownewError("Not implemented.")}},Wce=classextendsi3r{constructor(e){super(...arguments);x(this,"lc_namespace",["langchain","stores","message","in_memory"]);x(this,"messages",[]);this.messages=e??[]}asyncgetMessages(){returnthis.messages}asyncaddMessage(e){this.messages.push(e)}asyncclear(){this.messages=[]}};Jo();varBii={};$t(Bii,{BaseMemory:()=>uW,getInputValue:()=>lW,getOutputValue:()=>Jce,getPromptInputKey:()=>Xje});varuW=class{},a3r=(t,e)=>{if(e!==void0)returnt[e];letr=Object.keys(t);if(r.length===1)returnt[r[0]]},lW=(t,e)=>{letr=a3r(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},Jce=(t,e)=>{letr=a3r(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};functionXje(t,e){letr=Object.keys(t).filter(n=>!e.includes(n)&&n!=="stop");if(r.length!==1)thrownewError(`One input key expected, but got ${r.length}`);returnr[0]}varzii={};$J(zii,{BaseChatMemory:()=>p_});varp_=classextendsuW{constructor(e){super();x(this,"chatHistory");x(this,"returnMessages",!1);x(this,"inputKey");x(this,"outputKey");this.chatHistory=e?.chatHistory??newWce,this.returnMessages=e?.returnMessages??this.returnMessages,this.inputKey=e?.inputKey??this.inputKey,this.outputKey=e?.outputKey??this.outputKey}asyncsaveContext(e,r){awaitthis.chatHistory.addUserMessage(lW(e,this.inputKey)),awaitthis.chatHistory.addAIMessage(Jce(r,this.outputKey))}asyncclear(){awaitthis.chatHistory.clear()}};cW();ta();varZce=classextendsp_{constructor(e){let{returnMessages:r,inputKey:n,outputKey:o,chatHistory:i,humanPrefix:a,aiPrefix:s,llm:u,prompt:l,summaryChatMessageClass:c}=e;super({returnMessages:r,inputKey:n,outputKey:o,chatHistory:i});x(this,"memoryKey","history");x(this,"humanPrefix","Human");x(this,"aiPrefix","AI");x(this,"llm");x(this,"prompt",t3r);x(this,"summaryChatMessageClass",Od);this.memoryKey=e?.memoryKey??this.memoryKey,this.humanPrefix=a??this.humanPrefix,this.aiPrefix=s??this.aiPrefix,this.llm=u,this.prompt=l??this.prompt,this.summaryChatMessageClass=c??this.summaryChatMessageClass}asyncpredictNewSummary(e,r){letn=fl(e,this.humanPrefix,this.aiPrefix);returnawaitnewag({llm:this.llm,prompt:this.prompt}).predict({summary:r,new_lines:n})}},H3r=classextendsZce{constructor(e){super(e);x(this,"buffer","")}getmemoryKeys(){return[this.memoryKey]}asyncloadMemoryVariables(e){returnthis.returnMessages?{[this.memoryKey]:[newthis.summaryChatMessageClass(this.buffer)]}:{[this.memoryKey]:this.buffer}}asyncsaveContext(e,r){awaitsuper.saveContext(e,r);letn=awaitthis.chatHistory.getMessages();this.buffer=awaitthis.predictNewSummary(n.slice(-2),this.buffer)}asyncclear(){awaitsuper.clear(),this.buffer=""}};ta();varW3r=classextendsZce{constructor(e){super(e);x(this,"movingSummaryBuffer","");x(this,"maxTokenLimit",2e3);this.maxTokenLimit=e?.maxTokenLimit??this.maxTokenLimit}getmemoryKeys(){return[this.memoryKey]}asyncloadMemoryVariables(e){letr=awaitthis.chatHistory.getMessages();this.movingSummaryBuffer&&(r=[newthis.summaryChatMessageClass(this.movingSummaryBuffer),...r]);letn;returnthis.returnMessages?n=r:n=fl(r,this.humanPrefix,this.aiPrefix),{[this.memoryKey]:n}}asyncsaveContext(e,r){awaitsuper.saveContext(e,r),awaitthis.prune()}asyncprune(){lete=awaitthis.chatHistory.getMessages();this
`);await this.vectorStoreRetriever.addDocuments([new tl({pageContent:o,metadata:n})])}};cW();kL();var K3r=class extends Cg{};var G3r=class extends K3r{constructor(){super();x(this,"lc_namespace",["langchain","stores","entity","in_memory"]);x(this,"store");this.store=Object.create(null)}async get(e,r){return e in this.store?this.store[e]:r}async set(e,r){this.store[e]=r}async delete(e){delete this.store[e]}async exists(e){return e in this.store}async clear(){this.store=Object.create(null)}};ta();var X3r=class extends p_{constructor(e){super({chatHistory:e.chatHistory,returnMessages:e.returnMessages??!1,inputKey:e.inputKey,outputKey:e.outputKey});x(this,"entityExtractionChain");x(this,"entitySummarizationChain");x(this,"entityStore");x(this,"entityCache",[]);x(this,"k",3);x(this,"chatHistoryKey","history");x(this,"llm");x(this,"entitiesKey","entities");x(this,"humanPrefix");x(this,"aiPrefix");this.llm=e.llm,this.humanPrefix=e.humanPrefix,this.aiPrefix=e.aiPrefix,this.chatHistoryKey=e.chatHistoryKey??this.chatHistoryKey,this.entitiesKey=e.entitiesKey??this.entitiesKey,this.entityExtractionChain=new ag({llm:this.llm,prompt:e.entityExtractionPrompt??n3r}),this.entitySummarizationChain=new ag({llm:this.llm,prompt:e.entitySummarizationPrompt??o3r}),this.entityStore=e.entityStore??new G3r,this.entityCache=e.entityCache??this.entityCache,this.k=e.k??this.k}get memoryKeys(){return[this.chatHistoryKey]}get memoryVariables(){return[this.entitiesKey,this.chatHistoryKey]}async loadMemoryVariables(e){let r=this.inputKey??Xje(e,this.memoryVariables),n=await this.chatHistory.getMessages(),o=fl(n.slice(-this.k*2),this.humanPrefix,this.aiPrefix),i=await this.entityExtractionChain.predict({history:o,input:e[r]}),a=i.trim()==="NONE"?[]:i.split(",").map(l=>l.trim()),s={};for(let l of a)s[l]=await this.entityStore.get(l,"No current information known.");this.entityCache=[...a];let u=this.returnMessages?n.slice(-this.k*2):o;return{[this.chatHistoryKey]:u,[this.entitiesKey]:s}}async saveContext(e,r){await super.saveContext(e,r);let n=this.inputKey??Xje(e,this.memoryVariables),o=await this.chatHistory.getMessages(),i=fl(o.slice(-this.k*2),this.humanPrefix,this.aiPrefix),a=e[n];for(let s of this.entityCache){let u=await this.entityStore.get(s,"No current information known."),l=await this.entitySummarizationChain.predict({summary:u,entity:s,history:i,input:a});l.trim()!=="UNCHANGED"&&await this.entityStore.set(s,l.trim())}}async clear(){await super.clear(),await this.entityStore.clear()}};var Z3r=class extends p_{constructor(e){super({chatHistory:e?.chatHistory,returnMessages:e?.returnMessages??!1,inputKey:e?.inputKey,outputKey:e?.outputKey});x(this,"humanPrefix","Human");x(this,"aiPrefix","AI");x(this,"memoryKey","history");x(this,"memories",[]);this.memories=e?.memories??this.memories,this.humanPrefix=e?.humanPrefix??this.humanPrefix,this.aiPrefix=e?.aiPrefix??this.aiPrefix,this.memoryKey=e?.memoryKey??this.memoryKey,this.checkRepeatedMemoryVariable(),this.checkInputKey()}checkRepeatedMemoryVariable(){let e=[];for(let r of this.memories){let n=e.filter(o=>r.memoryKeys.includes(o));if(n.length>0)throw new Error(`Thesamevariables${[...n]}arefoundinmultiplememoryobjects,whichisnotallowedbyCombinedMemory.`);e.push(...r.memoryKeys)}}checkInputKey(){for(let e of this.memories)e.chatHistory!==void 0&&e.inputKey===void 0&&console.warn(`WhenusingCombinedMemory,inputkeysshouldbesetsotheinputisknown.Wasnotseton${e}.`)}async loadMemoryVariables(e){let r={};for(let n of this.memories){let o=await n.loadMemoryVariables(e);r={...r,...o}}return r}async saveContext(e,r){for(let n of this.memories)await n.saveContext(e,r)}async clear(){for(let e of this.memories)typeof e.clear=="function"&&await e.clear()}get memoryKeys(){let e=[];for(let r of this.memories)e.push(...r.memoryKeys);return e}};ta();var Y3r=class extends p_{constructor(e){super(e);x(this,"humanPrefix","Human");x(this,"aiPrefix","AI");x(this,"memoryKey","history");x(this,"maxTokenLimit",2e3);x(this,"llm");this.llm=e.llm,this.humanPrefix=e?.humanPrefix??this.humanPrefix,
Answer the question with as detailed as possible based only on the following context:
{context}
Question: {question}
`;this.qaPrompt=Ah.fromMessages([LS.fromTemplate(e)])}escapeTemplateString(e){returne.replace(/\{/g,"{{").replace(/\}/g,"}}")}getChatPrompt(){returnthis.chatPrompt}asyncgetQAPrompt({question:e,context:r,systemMessage:n}){returnawaitthis.qaPrompt.format({question:e,context:r,system_message:n})}};varede=class{constructor(e){this.retrievedDocuments=[];this.pendingModelError=null;this.app=e,this.memoryManager=Yce.getInstance(),this.chatModelManager=tC.getInstance(),this.promptManager=Qce.getInstance(),this.userMemoryManager=newGU(e),this.initialize(),hl(async()=>{awaitthis.createChainWithNewModel()})}getRetrievedDocuments(){returnthis.retrievedDocuments}asyncinitialize(){awaitthis.createChainWithNewModel()}getChain(){returnthis.chain}getRetrievalChain(){returnthis.retrievalChain}validateChainType(e){if(e==null)thrownewError("No chain type set")}validateChatModel(){if(this.pendingModelError)throwthis.pendingModelError;if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){lete="Chat model is not initialized properly, check your API key in Copilot setting and make sure you have API access.";thrownewzJ(e)}}validateChainInitialization(){(!this.chain||!v1t(this.chain))&&(F("Reinitializing chat chain after detecting missing or unsupported instance."),this.createChainWithNewModel({},!1))}storeRetrieverDocuments(e){this.retrievedDocuments=e}asynccreateChainWithNewModel(e={},r=!0){letn,o=ex(),i=Gu();if(!(o==="project"&&!i))try{if(n=o==="project"?i?.projectModelKey:B_(),!n)thrownewzJ("No model key found. Please select a model in settings.");if(r){leta=qS(n,te().activeModels);if(a||(console.error("Resetting default model. No model configuration found for: ",n),a=hO[0],n=a.name+"|"+a.provider),o==="project"&&!a.projectEnabled){letu=te().activeModels.find(l=>l.enabled&&l.projectEnabled);if(u)a=u,n=u.name+"|"+u.provider,newQ3r.Notice(`Model ${a.name} is not available in project mode. Switching to ${u.name}.`);elsethrownewError("No project-enabled models available. Please enable a model for project mode in settings.")}lets={...a,...i?.modelConfigs};awaitthis.chatModelManager.setChatModel(s),this.pendingModelError=null}this.setChain(o,e),F(`Setting model to ${n}`)}catch(a){this.pendingModelError=ainstanceofError?a:newError(String(a)),ne(`createChainWithNewModel failed: ${a}`),F(`modelKey: ${n||B_()}`)}}asyncsetChain(e,r={}){if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){console.error("setChain failed: No chat model set.");return}this.validateChainType(e);letn=this.chatModelManager.getChatModel(),o=this.memoryManager.getMemory(),i=this.promptManager.getChatPrompt();switch(e){case"llm_chain":{this.chain=Ate.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),N4("llm_chain");break}case"vault_qa":{awaitthis.initializeQAChain(r);lets=te().enableSemanticSearchV3?new(awaitPromise.resolve().then(()=>(_Pe(),Ost))).HybridRetriever({minSimilarityScore:.01,maxK:Ly,salientTerms:[]}):new(awaitPromise.resolve().then(()=>(xX(),Dmt))).TieredLexicalRetriever(app,{minSimilarityScore:.01,maxK:Ly,salientTerms:[],textWeight:void0,returnAll:!1,useRerankerThreshold:void0});this.retrievalChain=Ate.createConversationalRetrievalChain({llm:n,retriever:s,systemMessage:x$()},this.storeRetrieverDocuments.bind(this),te().debug),N4("vault_qa"),te().debug&&(console.log("New Vault QA chain with hybrid retriever created for entire vault"),console.log("Set chain:","vault_qa"));break}case"copilot_plus":{awaitthis.initializeQAChain(r),this.chain=Ate.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),N4("copilot_plus");break}case"project":{awaitthis.initializeQAChain(r),this.chain=Ate.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),N4("project");break}default:this.validateChainType(e);break}}getChainRunner(){lete=ex(),r=te();switch(e){case"llm_chain":returnnewAae(this);case"vault_qa":returnnewCle(this);case"copilot_plus":returnr.enableAutonomousAgent?ne
`).filter(m=>m.trim());awaitthis.projectContextCache.removeYoutubeUrls(r,f.filter(m=>!p.includes(m)))}}catch(n){ne(`Error comparing project configurations: ${n}`)}}refreshChatView(){lete=this.app.workspace.getLeavesOfType(Nu)[0]?.view;e&&e.updateView()}asyncgetProjectContext(e){letr=te().projectList.find(o=>o.id===e);if(!r)returnTe(`[getProjectContext] Project not found for ID: ${e}`),null;F(`[getProjectContext] Getting context for project: ${r.name} (ID: ${e})`);letn=this.projectContextCache.getSync(r);if(!n||n.markdownNeedsReload){n?F(`[getProjectContext] Project ${r.name}: Markdown needs reload. Triggering full load.`):F(`[getProjectContext] Project ${r.name}: Memory cache miss. Triggering full load.`);leto=awaitthis.loadProjectContext(r,!0);if(!o)returnne(`[getProjectContext] Project ${r.name}: loadProjectContext returned null.`),null;n=o}elseF(`[getProjectContext] Project ${r.name}: Memory cache hit and markdown OK. Using existing context.`);returnthis.formatProjectContextWithFiles(n,r)}asyncformatProjectContextWithFiles(e,r){letn=[];if(e.markdownContext&&n.push(`## Markdown Files
${e.markdownContext}`),Object.keys(e.webContexts).length>0&&n.push(`## Web Content
`)}`),Object.keys(e.fileContexts).length>0){leto=Object.entries(e.fileContexts).filter(([i])=>i.split(".").pop()?.toLowerCase()!=="md");if(o.length>0){leti=o.map(async([s,u])=>{letl=s.split("/"),c=l[l.length-1],d=c.split(".").pop()||"",f=awaitthis.projectContextCache.getOrReuseFileContext(r,s)||"[Content not available]";return`[[${c}]]
path: ${s}
type: ${d}
modified: ${newDate(u.timestamp).toISOString()}
${f}`}),a=awaitPromise.all(i);a.length>0&&n.push(`## Other Files
${a.join(`
`)}`)}}return`
# Project Context
The following information is the relevant context for this project. Use this information to inform your responses when appropriate:
${i}`}));returnF("All markdown files processed for project context"),n.join(`
`)}asyncprocessWebUrls(e,r){F(`[processWebUrls] Starting for project: ${e.name}`);letn=e.contextSource?.webUrls?.trim()||"";if(!n)returnObject.keys(r.webContexts).length>0&&(F(`[processWebUrls] Project ${e.name}: Clearing all Web contexts as none are configured.`),r.webContexts={}),r;leto=n.split(`
`).filter(c=>c.trim());F(`[processWebUrls] Project ${e.name}: Found ${o.length} URLs in config.`);leti=Object.keys(r.webContexts),a=o.filter(c=>!r.webContexts[c]);a.length>0&&F(`[processWebUrls] Project ${e.name}: Fetching content for ${a.length} new/updated Web URLs.`);lets=i.filter(c=>!o.includes(c));if(s.length>0){F(`[processWebUrls] Project ${e.name}: Removing ${s.length} obsolete Web URL contexts.`);for(letcofs)deleter.webContexts[c]}letu=a.map(asyncc=>{letd=awaitthis.processWebUrlContext(c);returnd&&F(`[processWebUrls] Project ${e.name}: Successfully fetched content for URL: ${c.substring(0,50)}...`),{url:c,context:d}});return(awaitPromise.all(u)).forEach(c=>{c&&c.context?r.webContexts[c.url]=c.context:c&&!c.context&&Te(`[processWebUrls] Project ${e.name}: Fetched empty content for Web URL: ${c.url}`)}),F(`[processWebUrls] Completed for project: ${e.name}. Total Web contexts: ${Object.keys(r.webContexts).length}`),r}asyncprocessYoutubeUrls(e,r){F(`[processYoutubeUrls] Starting for project: ${e.name}`);letn=e.contextSource?.youtubeUrls?.trim()||"";if(!n)returnObject.keys(r.youtubeContexts).length>0&&(F(`[processYoutubeUrls] Project ${e.name}: Clearing all YouTube contexts as none are configured.`),r.youtubeContexts={}),r;leto=n.split(`
`).filter(c=>c.trim());F(`[processYoutubeUrls] Project ${e.name}: Found ${o.length} YouTube URLs in config.`);leti=Object.keys(r.youtubeContexts),a=o.filter(c=>!r.youtubeContexts[c]);a.length>0&&F(`[processYoutubeUrls] Project ${e.name}: Fetching transcripts for ${a.length} new/updated YouTube URLs.`);lets=i.filter(c=>!o.includes(c));if(s.length>0){F(`[processYoutubeUrls] Project ${e.name}: Removing ${s.length} obsolete YouTube URL contexts.`);for(letcofs)deleter.youtubeContexts[c]}letu=a.map(asyncc=>{letd=awaitthis.processYoutubeUrlContext(c);returnd&&F(`[processYoutubeUrls] Project ${e.name}: Successfully fetched transcript for YouTube URL: ${c.substring(0,50)}...`),{url:c,context:d}});return(awaitPromise.all(u)).forEach(c=>{c&&c.context?r.youtubeContexts[c.url]=c.context:c&&!c.context&&Te(`[processYoutubeUrls] Project ${e.name}: Fetched empty transcript for YouTube URL: ${c.url}`)}),F(`[processYoutubeUrls] Completed for project: ${e.name}. Total YouTube contexts: ${Object.keys(r.youtubeContexts).length}`),r}asyncprocessWebUrlContext(e){if(!e?.trim())return"";try{letr=s9.getInstance(),{urlContext:n}=awaitthis.loadTracker.executeWithProcessTracking(e,"web",async()=>{leto=awaitr.processUrls(e);if(o.processedErrorUrls[e])thrownewError(o.processedErrorUrls[e]);returno});returnn||""}catch(r){returnne(`Failed to process web URL: ${r}`),""}}asyncprocessYoutubeUrlContext(e){if(!e?.trim())return"";try{letr=awaitthis.loadTracker.executeWithProcessTracking(e,"youtube",async()=>Ql.getInstance().youtube4llm(e));returnr.response.transcript?`
YouTube transcript from ${e}:
${r.response.transcript}`:""}catch(r){returnne(`Failed to process YouTube URL ${e}: ${r}`),newdW.Notice(`Failed to process YouTube URL ${e}: ${zr(r)}`),""}}asyncprocessNonMarkdownFiles(e,r){letn=r.filter(i=>i.extension!=="md");if(F(`[loadProjectContext] Project ${e.name}: Checking for non-markdown processing: ${n.length} files .`),n.length<=0)return;this.fileParserManager=newTq(Ql.getInstance(),this.app.vault,!0,e);leto=0;for(letiofn){leta=i.path;if(this.fileParserManager.supportsExtension(i.extension))try{awaitthis.loadTracker.executeWithProcessTracking(a,"nonMd",async()=>{awaitthis.projectContextCache.getOrReuseFileContext(e,a)||(F(`[loadProjectContext] Project ${e.name}: Parsing/caching new/updated file: ${a}`),awaitthis.fileParserManager.parseFile(i,this.app.vault)),o++})}catch(s){if(ne(`[loadProjectContext] Project ${e.name}: Error parsing file ${a}:`,s),DD(s))throws}}o>0&&F(`[loadProjectContext] Project ${e.name}: Processed and cached ${o} non-markdown files.`)}asyncretryFailedItem(e){try{if(!this.currentProjectId){Te("[retryFailedItem] No current project, aborting retry");return}letr=te().projectList.find(n=>n.id===this.currentProjectId);if(!r){ne(`[retryFailedItem] Current project not found: ${this.currentProjectId}`);return}switch(F(`[retryFailedItem] Starting retry for ${e.type} item: ${e.path}`),e.type){case"web":awaitthis.retryWebUrl(r,e.path);break;case"youtube":awaitthis.retryYoutubeUrl(r,e.path);break;case"md":awaitthis.retryMarkdownFile(r,e.path);break;case"nonMd":awaitthis.retryNonMarkdownFile(r,e.path);break;default:Te(`[retryFailedItem] Unknown item type: ${e.type}`);return}F(`[retryFailedItem] Successfully retried ${e.type} item: ${e.path}`),newdW.Notice(`Retry successful: ${e.path}`)}catch(r){ne(`[retryFailedItem] Failed to retry ${e.type} item ${e.path}:`,r),newdW.Notice(`Retry failed: ${zr(r)}`)}}asyncretryWebUrl(e,r){letn=awaitthis.processWebUrlContext(r);if(!n){Te(`[retryWebUrl] Project ${e.name}: Fetched empty content for Web URL: ${r}`);return}F(`[retryWebUrl] Project ${e.name}: Successfully fetched content for URL: ${r.substring(0,50)}...`),awaitthis.projectContextCache.updateWebUrl(e,r,n)}asyncretryYoutubeUrl(e,r){letn=awaitthis.processYoutubeUrlContext(r);if(!n){Te(`[retryYoutubeUrl] Project ${e.name}: Fetched empty transcript for YouTube URL: ${r}`);return}F(`[retryYoutubeUrl] Project ${e.name}: Successfully fetched transcript for YouTube URL: ${r.substring(0,50)}...`),awaitthis.projectContextCache.updateYoutubeUrl(e,r,n)}asyncretryMarkdownFile(e,r){letn=this.app.vault.getAbstractFileByPath(r);if(!(ninstanceofdW.TFile)||n.extension!=="md")thrownewError(`File not found or not a markdown file: ${r}`);try{awaitthis.loadTracker.executeWithProcessTracking(n.path,"md",async()=>{}),F(`[retryMarkdownFile] Successfully reprocessed markdown file: ${r}`),awaitthis.projectContextCache.invalidateMarkdownContext(e)}catch(o){throwne(`[retryMarkdownFile] Error processing file ${r}: ${o}`),o}}asyncretryNonMarkdownFile(e,r){letn=this.app.vault.getAbstractFileByPath(r);if(!(ninstanceofdW.TFile)||n.extension==="md")thrownewError(`File not found or is a markdown file: ${r}`);if(!this.fileParserManager.supportsExtension(n.extension))thrownewError(`Unsupported file extension: ${n.extension}`);try{awaitthis.loadTracker.executeWithProcessTracking(r,"nonMd",async()=>this.fileParserManager.parseFile(n,this.app.vault)),F(`[retryNonMarkdownFile] Successfully reprocessed non-markdown file: ${r}`)}catch(o){throwne(`[retryNonMarkdownFile] Error processing file ${r}: ${o}`),o}}getProjectAllFiles(e){let{inclusions:r,exclusions:n}=el({inclusions:e.contextSource.inclusions,exclusions:e.contextSource.exclusions,isProject:!0});returnthis.app.vault.getFiles().filter(o=>Hs(o,r,n,!0))}onunload(){this.projectContextCache.cleanup()}};ra();O4();Xe();varNWr=require("obsidian");Cn();vari$e=$(J());$r();varri=i$e.forwardRef(({className:t,type:e,...r},n)=>i$e.createElement("input",{type:e,className:we("!tw-h-9 !tw-min-w-[50px] !tw-rounded-md !tw-border tw-border-solid tw-border-border
Return only the translated text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1010,modelKey:"",lastUsedMs:0},{title:"Summarize",content:"Createabullet-pointsummaryof{}.Eachbulletpointshouldcaptureakeypoint.Returnonlythebullet-pointsummary.",showInContextMenu:!0,showInSlashMenu:!0,order:1020,modelKey:"",lastUsedMs:0},{title:"Simplify",content:"Simplify{}toa6th-gradereadinglevel(ages11-12).Usesimplesentences,commonwords,andclearexplanations.Maintaintheoriginalkeyconcepts.Returnonlythesimplifiedtext.",showInContextMenu:!0,showInSlashMenu:!0,order:1030,modelKey:"",lastUsedMs:0},{title:"ExplainlikeIam5",content:`Explain {} in simple terms that a 5-year-old would understand:
1. Use basic vocabulary
2. Include simple analogies
3. Break down complex concepts
Return only the simplified explanation.`,showInContextMenu:!0,showInSlashMenu:!0,order:1040,modelKey:"",lastUsedMs:0},{title:"Emojify",content:`Add relevant emojis to enhance {}. Follow these rules:
1. Insert emojis at natural breaks in the text
2. Never place two emojis next to each other
3. Keep all original text unchanged
4. Choose emojis that match the context and tone
Return only the emojified text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1050,modelKey:"",lastUsedMs:0},{title:"Makeshorter",content:`Reduce {} to half its length while preserving these elements:
1. Main ideas and key points
2. Essential details
3. Original tone and style
Return only the shortened text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1060,modelKey:"",lastUsedMs:0},{title:"Makelonger",content:`Expand {} to twice its length by:
1. Adding relevant details and examples
2. Elaborating on key points
3. Maintaining the original tone and style
Return only the expanded text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1070,modelKey:"",lastUsedMs:0},{title:"Generatetableofcontents",content:"Generateahierarchicaltableofcontentsfor{}.Useappropriateheadinglevels(H1,H2,H3,etc.).Includepagenumbersifpresent.Returnonlythetableofcontents.",showInContextMenu:!1,showInSlashMenu:!1,order:1080,modelKey:"",lastUsedMs:0},{title:"Generateglossary",content:'Create a glossary of important terms, concepts, and phrases from {}. Format each entry as "Term:Definition". Sort entries alphabetically. Return only the glossary.',showInContextMenu:!1,showInSlashMenu:!1,order:1090,modelKey:"",lastUsedMs:0},{title:"RemoveURLs",content:"RemoveallURLsfrom{}.Preserveallothercontentandformatting.URLsmaybeinvariousformats(http,https,www).ReturnonlythetextwithURLsremoved.",showInContextMenu:!1,showInSlashMenu:!1,order:1100,modelKey:"",lastUsedMs:0},{title:"Rewriteastweet",content:`Rewrite {} as a single tweet with these requirements:
1. Maximum 280 characters
2. Use concise, impactful language
3. Maintain the core message
Return only the tweet text.`,showInContextMenu:!1,showInSlashMenu:!1,order:1110,modelKey:"",lastUsedMs:0},{title:"Rewriteastweetthread",content:`Convert {} into a Twitter thread following these rules:
Return only the formatted thread.`,showInContextMenu:!1,showInSlashMenu:!1,order:1120,modelKey:"",lastUsedMs:0},{title:"ClipYouTubeTranscript",content:`
Based on the YouTube video information and transcript provided in the context, generate a complete Obsidian note in the following format.
Return only the markdown content without any explanations or comments.`,showInContextMenu:!1,showInSlashMenu:!0,order:1130,modelKey:"",lastUsedMs:0},{title:"ClipWebPage",content:`
Based on the web page content provided in the context (from Obsidian Web Clipper or Web Viewer), generate a complete Obsidian note.
IMPORTANT: If no web page context is found, remind the user to:
1. Open a web page in Web Viewer (or use @ to select a web tab)
2. Or open a note clipped by Obsidian Web Clipper
3. Then use this command again
Generate the note with this exact structure:
---
title: "<pagetitle>"
source: "<pageurl>"
description: "<briefdescription>"
tags:
- "clippings"
---
## Summary
<Brief 2-3 paragraph summary of the page content>
## Key Takeaways
<List 5-8 key takeaways as bullet points>
## Mindmap
CRITICAL Mermaid mindmap syntax rules - MUST follow exactly:
- Root node format: root(Topic Name) - use round brackets, NO double brackets
- Child nodes: just plain text, no brackets needed
- Do NOT use quotes, parentheses, brackets, or any special characters in text
- Keep all node text short and simple - max 3-4 words per node
\`\`\`mermaid
mindmap
root(Main Topic)
Theme One
Detail
Theme Two
Detail
\`\`\`
## Notable Quotes
<List 3-5 notable quotes from the content, if any>
</${R4}>`,s.files.push(r))}elsenewlZ.Notice("No active note found.");else{if(u==="activewebtab")continue;if(a.startsWith("#")){letl=a.slice(1).split(",").map(f=>f.trim()),c=awaitmye(e,l),d=[];for(letfofc){letp=awaitWJ(f,e);p&&(d.push(`<${R4}>
`)}}s.content?(n.set(a,s.content),s.files.forEach(l=>o.add(l))):u!=="activenote"&&u!=="activewebtab"&&(a.startsWith('"')||Te(`No notes found for variable: ${a}`))}return{variablesMap:n,includedFiles:o}}asyncfunctionsde(t,e,r,n,o=!1){leti=te(),a=newSet;if(!i.enableCustomPromptTemplating)return!o&&t.includes("{}")&&!e&&n&&a.add(n),{processedPrompt:t+`
${d.transcript}`;awaitnavigator.clipboard.writeText(w),newNZ.Notice("Transcript copied to clipboard!")}catch(w){ne("Failed to copy to clipboard:",w),newNZ.Notice("Failed to copy to clipboard")}},g=async()=>{if(d)try{letw=`# YouTube Video Transcript
${d.transcript}`;awaitKJ(w,!1),t()}catch(w){ne("Failed to insert to note:",w),newNZ.Notice("Failed to insert to note")}},b=()=>{r("input"),o(""),u(""),f(null)},_=w=>{w.key==="Enter"&&!i&&l&&h()};returne==="display"&&d?Bu.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Bu.createElement("div",{className:"tw-rounded tw-bg-secondary tw-p-3"},Bu.createElement("a",{href:d.url,className:"tw-text-sm tw-text-muted hover:tw-text-normal",target:"_blank",rel:"noopener noreferrer"},d.url)),Bu.createElement("div",{className:"tw-max-h-96 tw-overflow-y-auto tw-rounded tw-border tw-border-border tw-bg-primary tw-p-4"},Bu.createElement("div",{className:"tw-whitespace-pre-wrap tw-text-sm tw-leading-relaxed"},d.transcript)),Bu.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},Bu.createElement(pe,{variant:"ghost",onClick:b},"Download Another"),Bu.createElement(pe,{variant:"default",onClick:y},"Copy to Clipboard"),Bu.createElement(pe,{variant:"default",onClick:g},"Insert at Cursor"),Bu.createElement(pe,{variant:"secondary",onClick:t},"Close"))):Bu.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Bu.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Bu.createElement("div",{className:"tw-text-sm tw-text-muted"},"Enter a valid YouTube video URL"),Bu.createElement(ri,{placeholder:"https://www.youtube.com/watch?v=...",value:n,onChange:w=>m(w.target.value),onKeyDown:_,disabled:i}),s&&Bu.createElement("div",{className:"tw-text-sm tw-text-error"},s)),Bu.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},Bu.createElement(pe,{variant:"secondary",onClick:t,disabled:i},"Cancel"),Bu.createElement(pe,{variant:"default",onClick:h,disabled:i||!l},i?"Downloading...":"Download Transcript")))}varMLe=classextendsNZ.Modal{constructor(e){super(e),this.setTitle("Download YouTube Script (plus)")}onOpen(){let{contentEl:e}=this;this.root=(0,Y8r.createRoot)(e);letr=()=>{this.close()};this.root.render(Bu.createElement(Xdi,{onClose:r}))}onClose(){this.root.unmount()}};Fc();ob();Bt();varoi=require("obsidian");qN();mr();ra();functionlg(t,e,r){t.addCommand({id:e,name:xye[e],callback:r})}functionjGr(t,e,r){t.addCommand({id:e,name:xye[e],editorCallback:r})}function$Gr(t,e,r){t.addCommand({id:e,name:xye[e],checkCallback:r})}functionObt(t,e,r){jGr(t,Sn.COUNT_WORD_AND_TOKENS_SELECTION,asyncn=>{leto=awaitn.getSelection(),i=o.split(" ").length,a=awaitt.projectManager.getCurrentChainManager().chatModelManager.countTokens(o);newoi.Notice(`Selected text contains ${i} words and ${a} tokens.`)}),lg(t,Sn.COUNT_TOTAL_VAULT_TOKENS,async()=>{try{letn=awaitKit(t.app),o=awaitt.projectManager.getCurrentChainManager().chatModelManager.countTokens(n);newoi.Notice(`Total tokens in your vault: ${o}`)}catch(n){ne("Error counting tokens: ",n),newoi.Notice("An error occurred while counting tokens.")}}),lg(t,Sn.TOGGLE_COPILOT_CHAT_WINDOW,()=>{t.toggleView()}),lg(t,Sn.OPEN_COPILOT_CHAT_WINDOW,()=>{t.activateView()}),lg(t,Sn.NEW_CHAT,()=>{c9(),t.newChat()}),$Gr(t,Sn.TRIGGER_QUICK_COMMAND,n=>{leto=t.app.workspace.getActiveViewOfType(oi.MarkdownView);if(n)return!!(!Ite()&&o&&o.editor);if(Ite())returnnewoi.Notice("Quick command is not available in source mode."),!1;if(!o||!o.editor)returnnewoi.Notice("No active editor found."),!1;leta=o.editor.getSelection();if(!a.trim())returnnewoi.Notice("Please select some text first. Selected text is required for quick commands."),!1;lets={title:"Quick Command",content:"",showInContextMenu:!1,showInSlashMenu:!1,order:0,modelKey:"",lastUsedMs:Date.now()};returnnewEB(t.app,{selectedText:a,command:s,systemPrompt:w$e,behaviorConfig:{autoExecuteOnOpen:!1,hideContentAreaOnIdle:!0,commandLabel:"Quick Command",commandIcon:null,showIncludeNoteContext:!0,modelSelectionScope:"quick-command",firstSubmitTransform:(l,c)=>S$e(l,c)}}).open(),!0}),lg(t,Sn.CLEAR_LOCAL_COPILOT_INDEX,async()=>{try{await(awaitPromise.resolve().then(()=>(Pl(),Vc))).default.getInstance().clearIndex(),newoi.Notice("Cleared local Copilot semantic index.")}catch(n){ne("Error clearing semantic index:",n),
`),h=`Copilot-Indexed-Files-${newDate().toLocaleDateString().replace(/\//g,"-")}.md`,y="copilot",g=`${y}/${h}`;await $c(y);let b=t.app.vault.getAbstractFileByPath(g);b?await t.app.vault.modify(b,m):await t.app.vault.create(g,m);let _=t.app.vault.getAbstractFileByPath(g);_&&(await t.app.workspace.getLeaf().openFile(_),new oi.Notice(`Listed${p.size}indexedfiles`))}catch(n){ne("Error listing indexed files:",n),new oi.Notice("Failed to list indexed files.")}}),lg(t,Sn.INSPECT_COPILOT_INDEX_BY_NOTE_PATHS,async()=>{try{let n=t.app.workspace.getActiveFile();if(!n){new oi.Notice("No active file. Please open a note first.");return}let o=(await Promise.resolve().then(()=>(Pl(),Vc))).default,{DBOperations:i}=await Promise.resolve().then(()=>(FEe(),N_r)),a=await o.getInstance().getDb(),s=await i.getDocsByPath(a,n.path);if(!s||s.length===0){new oi.Notice(`Noembeddingdatafoundfor:${n.path}`);return}let u=s.map(h=>h.document),l=[`#EmbeddingDebug:${n.basename}`,"",`**Path:**${n.path}`,`**Chunks:**${u.length}`,`**EmbeddingModel:**${u[0]?.embeddingModel||"unknown"}`,"",...u.flatMap((h,y)=>{let g=h.embedding||[],b=g.slice(0,10).map(_=>_.toFixed(6)).join(", ");return[`##Chunk${y+1}`,`-**ID:**${h.id}`,`-**ContentPreview:**"${(h.content||"").substring(0,200)}..."`,`-**VectorLength:**${g.length}`,`-**VectorPreview:**[${b}${g.length>10?", ...":""}]`,`-**Tags:**${(h.tags||[]).join(", ")||"none"}`,`-**Characters:**${h.nchars||0}`,""]})].join(`
`),c=`Copilot-Embedding-Debug-${n.basename.replace(/[\\/:*?"<>|]/g,"_")}.md`,d="copilot",f=`${d}/${c}`;await $c(d);let p=t.app.vault.getAbstractFileByPath(f);p?await t.app.vault.modify(p,l):await t.app.vault.create(f,l);let m=t.app.vault.getAbstractFileByPath(f);m&&(await t.app.workspace.getLeaf().openFile(m),new oi.Notice(`Embeddingdebuginfofor${u.length}chunk(s)`))}catch(n){ne("Error inspecting embeddings:",n),new oi.Notice("Failed to inspect embeddings. Is the index loaded?")}}),lg(t,Sn.CLEAR_COPILOT_CACHE,async()=>{try{await t.fileParserManager.clearPDFCache(),await Fw.getInstance().clearAllCache(),await i9.getInstance().clear(),new oi.Notice("All Copilot caches cleared successfully")}catch(n){ne("Error clearing Copilot caches:",n),new oi.Notice("Failed to clear Copilot caches")}}),lg(t,Sn.OPEN_LOG_FILE,async()=>{try{await QEe(),await Im.openLogFile()}catch(n){ne("Error creating Copilot log file:",n),new oi.Notice("Failed to create Copilot log file.")}}),lg(t,Sn.CLEAR_LOG_FILE,async()=>{try{await Im.clear(),new oi.Notice("Copilot log cleared.")}catch(n){ne("Error clearing Copilot log file:",n),new oi.Notice("Failed to clear Copilot log file.")}}),jGr(t,Sn.ADD_SELECTION_TO_CHAT_CONTEXT,async n=>{let o=n.getSelection();if(!o){new oi.Notice("No text selected");return}let i=t.app.workspace.getActiveFile();if(!i){new oi.Notice("No active file");return}let a=n.listSelections()[0];if(!a){new oi.Notice("Could not determine selection range");return}let s=a.anchor.line+1,u=a.head.line+1,l={id:od(),content:o,sourceType:"note",noteTitle:i.basename,notePath:i.path,startLine:Math.min(s,u),endLine:Math.max(s,u)};SO([l]),t.activateView()}),lg(t,Sn.ADD_WEB_SELECTION_TO_CHAT_CONTEXT,async()=>{let{Platform:n}=await import("obsidian");if(!n.isDesktopApp){new oi.Notice("Web selection is only available on desktop");return}let{getWebViewerService:o}=await Promise.resolve().then(()=>(jW(),DGr));try{let i=o(t.app),a=i.getActiveLeaf()??i.getLastActiveLeaf();if(!a){new oi.Notice("No active Web Tab found");return}let s=await i.getSelectedMarkdown(a);if(!s.trim()){new oi.Notice("No text selected in Web Tab");return}let u=i.getPageInfo(a),l={id:od(),content:s,sourceType:"web",title:u.title||"Untitled",url:u.url,faviconUrl:u.faviconUrl||void 0};SO([l]),t.activateView()}catch(i){ne("Error adding web selection to context:",i),new oi.Notice("Failed to get web selection")}}),lg(t,Sn.ADD_CUSTOM_COMMAND,async()=>{let n=Pv(),o={...lN};new hB(t.app,n,o,async a=>{await th.getInstance().createCommand(a)}).open()}),lg(t,Sn.APPLY_CUSTOM_COMMAND,()=>{new ELe(t.app).open()}),lg(t,Sn.DOWNLOAD_YOUTUBE_SCRIPT,async()=>{if(!await E0()){new oi.Notice("Download YouTube Script (plus) is a Copilot Plus feature");return}new MLe(t.app).open()}),$Gr(t,Sn.TRIGGER_QUICK_ASK,n=>{let o=t.app.workspace.getActiveViewOfType(oi.MarkdownView);if(n)return!!(!Ite()&&o&&o.editor);if(Ite())return new oi.Notice("Quick Ask is not available in source mode."),!1;if(!o||!o.editor)return new oi.Notice("No active editor found."),!1;let i=o.editor.cm;return i?(t.quickAskController.show(o,i),!0):(new oi.Notice("Could not access CodeMirror editor."),!1)})}ra();var BZ={title:"",content:"",createdMs:0,modifiedMs:0,lastUsedMs:0},zZ="copilot-system-prompt-created",VZ="copilot-system-prompt-modified",HZ="copilot-system-prompt-last-used",Ebt="copilot-system-prompt-default";var MB=require("obsidian");Ye();Bt();Xe();function kde(t,e,r){let n=t.trim();return n?t!==n?"Prompt name cannot have leading or trailing spaces":r&&t===r?null:/[#<>:"/\\|?*[\]^\x00-\x1F]/g.test(n)?'Prompt name contains invalid characters. Avoid using: < > : " / \\ | ? * [ ] ^':e.some(i=>i.title.toLowerCase()===n.toLowerCase())?"A prompt with this name already exists":null:"Prompt name cannot be empty"}function _C(){return(0,MB.normalizePath)(te().userSystemPromptsFolder)}function vC(t){return(0,MB.normalizePath)(`${_C()}/${t}.md`)}function Mfi(t,e){let r=e?(0,MB.normalizePath)(e):_C();return(0,MB.normalizePath)(`${r}/${t}.md`)}function WZ(t){if(!(t instanceof MB.TFile)||t.extension!=="md")return!1;let e=_C();if(!t.path.starts
`).replace(/\r/g,`
`)}asyncfunctionzGr(t,e,r){letn=_C(),o=`${n}/unsupported`;await$c(o);leti="Migrated System Prompt (Failed Verification)",a=i,s=1;for(;t.getAbstractFileByPath(`${o}/${a}.md`);)s++,a=`${i}${s}`;letu=`${o}/${a}.md`,l=`> Migration failed: ${r}
>
> To fix: Review the content below, then move this file to ${n}
${e}`;returnawaitt.create(u,l),u}asyncfunctionNfi(t,e,r){try{letn=awaitt.read(e),o=HJ(n,{trimStart:!1}),i=Abt(o).replace(/^\n+/,""),a=Abt(r).replace(/^\n+/,"");returni!==a?(Te(`Migration verification failed: content mismatch. Expected ${a.length} chars, got ${i.length} chars`),!1):!0}catch(n){returnne("Migration verification failed: unable to read back file",n),!1}}asyncfunctionNbt(t){letr=te().userSystemPrompt;if(!r||r.trim().length===0){F("No legacy userSystemPrompt to migrate");return}try{F("Migrating legacy userSystemPrompt from settings to file system");letn=_C();await$c(n);leto=Afi(BGr,t),i=vC(o);o!==BGr&&F(`Default name already exists, using unique name: "${o}"`);leta=Date.now(),s=Abt(r),u={title:o,content:s,createdMs:a,modifiedMs:a,lastUsedMs:0};awaitt.create(i,s);letl=t.getAbstractFileByPath(i);if(!(linstanceofVGr.TFile))thrownewError("File not found after creation");if(awaitLW(l,u),awaitNfi(t,l,r)){Re("defaultSystemPromptTitle",o);try{awaitJZ()}catch(d){Te("Failed to reload prompts after migration:",d)}Re("userSystemPrompt",""),F("Cleared legacy userSystemPrompt field"),newzu(app,()=>{},`We have upgraded your system prompt to the new file-based format. It is now stored as "${o}" in ${n}.
You can now:
\u2022 Edit your system prompt directly in the file
\u2022 Create multiple system prompts
\u2022 Manage prompts through the settings UI
Your migrated prompt has been set as the default system prompt.`,"\u{1F680} System Prompt Upgraded","OK","").open()}else{letd=awaitzGr(t,r,"content verification mismatch");try{awaitJZ()}catch(f){Te("Failed to reload prompts after failed migration:",f)}Re("userSystemPrompt",""),F("Cleared legacy userSystemPrompt field (saved to unsupported)"),newzu(app,()=>{},`\u26A0\uFE0F System Prompt Migration Issue
Your system prompt was migrated but verification failed. Your data has been saved to:
${d}
To recover:
1. Open the file and review the content
2. Move it to ${n}
3. The prompt will be available immediately`,"Migration Verification Failed","OK","").open()}}catch(n){ne("Failed to migrate legacy userSystemPrompt:",n);try{leto=awaitzGr(t,r,n.message||String(n));Re("userSystemPrompt",""),F("Cleared legacy userSystemPrompt field (saved to unsupported after error)"),newzu(app,()=>{},`\u26A0\uFE0F System Prompt Migration Failed
An error occurred during migration. Your data has been saved to:
${o}
To recover:
1. Open the file and review the content
2. Move it to ${_C()}
3. The prompt will be available immediately`,"Migration Failed","OK","").open()}catch(o){ne("Failed to save to unsupported folder:",o),Te("Preserving userSystemPrompt in settings for manual recovery"),newzu(app,()=>{},`Failed to migrate system prompt: ${n.message}
Unable to save to file system. Your system prompt is still in settings and will continue to work.
Please check:
- Folder permissions for ${_C()}
- Available disk space
- Vault is accessible
You can retry by reloading the plugin.`,"Migration Failed - Data Preserved","OK","").open()}}}sd();sd();ra();functionULe(){let[t]=fw(),[e]=Dye(),[r]=s5();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"})()}Xe();ra();sd();Cn();mr();Xe();Fc();Ye();Or();varsS=require("obsidian"),pr=$(J());varLn=$(J());Or();Cn();varXZ=$(J());Cn();Or();varZZ=({value:t,onChange:e,placeholder:r="Search..."})=>XZ.default.createElement("div",{className:"tw-relative"},XZ.default.createElement(ri,{type:"text",placeholder:r,value:t,onChange:n=>e(n.target.value),className:"tw-pr-10"}),t&&XZ.default.createElement(pe,{variant:"secondary",onClick:()=>e(""),className:"tw-absolute tw-right-8 tw-top-1/2 tw-size-4 -tw-translate-y-1/2 tw-transform tw-rounded-full tw-p-0 tw-transition-colors","aria-label":"Clear search"},XZ.default.createElement(RO,{className:"tw-size-4 tw-text-muted/60 hover:tw-text-accent-hover"})),XZ.default.createElement(Y4,{className:"tw-absolute tw-right-3 tw-top-1/2 tw-size-4 -tw-translate-y-1/2 tw-transform tw-text-muted"}));varHde=$(J());vardc=$(J(),1);varr$s=!!(typeofwindow<"u"&&window.document&&window.document.createElement);functionYZ(t,e,{checkForDefaultPrevented:r=!0}={}){returnfunction(o){if(t?.(o),r===!1||!o.defaultPrevented)returne?.(o)}}varWGr=$(J(),1);functionHGr(t,e){if(typeoft=="function")returnt(e);t!=null&&(t.current=e)}functionDbt(...t){returne=>{letr=!1,n=t.map(o=>{leti=HGr(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():HGr(t[o],null)}}}}functionzde(...t){returnWGr.useCallback(Dbt(...t),t)}varQ$=$(J(),1),JGr=$(St(),1);functionKGr(t,e=[]){letr=[];functionn(i,a){lets=Q$.createContext(a),u=r.length;r=[...r,a];letl=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[u]||s,y=Q$.useMemo(()=>m,Object.values(m));return(0,JGr.jsx)(h.Provider,{value:y,children:p})};l.displayName=i+"Provider";functionc(d,f){letp=f?.[t]?.[u]||s,m=Q$.useContext(p);if(m)returnm;if(a!==void0)returna;thrownewError(`\`${d}\` must be used within \`${i}\``)}return[l,c]}leto=()=>{leti=r.map(a=>Q$.createContext(a));returnfunction(s){letu=s?.[t]||i;returnQ$.useMemo(()=>({[`__scope${t}`]:{...s,[t]:u}}),[s,u])}};returno.scopeName=t,[n,Dfi(o,...e)]}functionDfi(...t){lete=t[0];if(t.length===1)returne;letr=()=>{letn=t.map(o=>({useScope:o(),scopeName:o.scopeName}));returnfunction(i){leta=n.reduce((s,{useScope:u,scopeName:l})=>{letd=u(i)[`__scope${l}`];return{...s,...d}},{});returnQ$.useMemo(()=>({[`__scope${e.scopeName}`]:a}),[a])}};returnr.scopeName=e.scopeName,r}varjbt=$(J(),1);varGGr=$(J(),1),qW=globalThis?.document?GGr.useLayoutEffect:()=>{};varjfi=jbt[" useId ".trim().toString()]||(()=>{}),$fi=0;functionXGr(t){let[e,r]=jbt.useState(jfi());returnqW(()=>{t||r(n=>n??String($fi++))},[t]),t||(e?`radix-${e}`:"")}varLv=$(J(),1);varZGr=$(J(),1);functionLfi(t,e){returnZGr.useReducer((r,n)=>e[r][n]??r,t)}varzLe=t=>{let{present:e,children:r}=t,n=Ffi(e),o=typeofr=="function"?r({present:n.isPresent}):Lv.Children.only(r),i=zde(n.ref,kfi(o));returntypeofr=="function"||n.isPresent?Lv.cloneElement(o,{ref:i}):null};zLe.displayName="Presence";functionFfi(t){let[e,r]=Lv.useState(),n=Lv.useRef(null),o=Lv.useRef(t),i=Lv.useRef("none"),a=t?"mounted":"unmounted",[s,u]=Lfi(a,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});returnLv.useEffect(()=>{letl=BLe(n.current);i.current=s==="mounted"?l:"none"},[s]),qW(()=>{letl=n.current,c=o.current;if(c!==t){letf=i.current,p=BLe(l);t?u("MOUNT"):p==="none"||l?.display==="none"?u("UNMOUNT"):u(c&&f!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=t}},[t,u]),qW(()=>{if(e){letl,c=e.ownerDocument.defaultView??window,d=p=>{leth=BLe(n.current).includes(CSS.escape(p.animationName));if(p.target===e&&h&&(u("ANIMATION_END"),!o.current)){lety=e.style.animationFillM
`)};function_rn({onWebTabsChange:t,onWebTabsRemoved:e,onActiveWebTabAdded:r,onActiveWebTabRemoved:n}){returndz.default.createElement(dz.default.Fragment,null,dz.default.createElement(UT,{config:k_i,onChange:t,onRemoved:e}),(r||n)&&dz.default.createElement(q_i,{onActiveWebTabAdded:r,onActiveWebTabRemoved:n}))}functionq_i({onActiveWebTabAdded:t,onActiveWebTabRemoved:e}){letr={isPillNode:iwt,extractData:()=>!0,getKey:()=>"active-web-tab"},n=dz.default.useCallback(i=>{i.length>0&&t&&t()},[t]),o=dz.default.useCallback(i=>{i.length>0&&e&&e()},[e]);returndz.default.createElement(UT,{config:r,onChange:n,onRemoved:o})}varvrn=$(J());functionwrn({enableURLPills:t=!1,onImagePaste:e}){let[r]=Di();returnvrn.default.useEffect(()=>r.registerCommand(bke,n=>{leto=n.clipboardData;if(!o)return!1;if(e){letp=o.items;if(p){letm=Array.from(p).filter(h=>h.type.indexOf("image")!==-1);if(m.length>0)returnn.preventDefault(),Promise.all(m.map(h=>h.getAsFile())).then(h=>{lety=h.filter(g=>g!==null);y.length>0&&e(y)}),!0}}leti=o.getData("text/plain"),a=i.includes("[["),s=t&&i.includes("http"),u=i.includes("@"),l=i.includes("#"),c=i.includes("{")&&i.includes("}");if(!i||!a&&!s&&!u&&!l&&!c)return!1;letd=aqe(i,{includeNotes:!0,includeURLs:t,includeTools:!0,includeCustomTemplates:!0});returnd.some(p=>p.type==="note-pill"||p.type==="active-note-pill"||t&&p.type==="url-pill"||p.type==="tool-pill"||p.type==="folder-pill")?(n.preventDefault(),r.update(()=>{letp=_n();if(!Nr(p))return;letm=sqe(d);m.length>0&&p.insertNodes(m)}),!0):!1},_L),[r,t,e]),null}varSrn=$(J());functionCrn(){let[t]=Di();returnSrn.default.useEffect(()=>t.registerCommand(iqe,e=>{let{text:r,options:n={}}=e;returnt.update(()=>{Qtn(r,n)}),!0},il),[t]),null}varHv=$(J());varxrn=(0,Hv.createContext)(void0);functionfz(){lett=(0,Hv.useContext)(xrn);if(t===void0)thrownewError("useChatInput must be used within a ChatInputProvider");returnt}functionTrn({children:t}){let[e,r]=(0,Hv.useState)(null),[n,o]=(0,Hv.useState)(null),i=(0,Hv.useCallback)(c=>{r(c)},[]),a=(0,Hv.useCallback)(c=>{o(()=>c)},[]),s=(0,Hv.useCallback)((c,d=!1)=>{e&&e.dispatchCommand(iqe,{text:c,options:{enableURLPills:d,insertAtSelection:!0}})},[e]),u=(0,Hv.useCallback)(()=>{n&&n()},[n]),l={insertTextWithPills:s,focusInput:u,registerEditor:i,registerFocusHandler:a};returnHv.default.createElement(xrn.Provider,{value:l},t)}$r();Xe();sd();Ye();varU_i=({value:t,onChange:e,onSubmit:r,placeholder:n="Type a message...",disabled:o=!1,className:i="",onNotesChange:a,onNotesRemoved:s,onURLsChange:u,onURLsRemoved:l,onToolsChange:c,onToolsRemoved:d,onFoldersChange:f,onFoldersRemoved:p,onActiveNoteAdded:m,onActiveNoteRemoved:h,onWebTabsChange:y,onWebTabsRemoved:g,onActiveWebTabAdded:b,onActiveWebTabRemoved:_,onEditorReady:w,onImagePaste:T,onTagSelected:O,isCopilotPlus:E=!1,currentActiveFile:P=null,currentChain:R})=>{let[I,N]=Yi.default.useState(null),[z,V]=Yi.default.useState(null),k=fz(),X=Br(),B=Yi.default.useCallback(oe=>{N(()=>oe)},[]);(0,Yi.useEffect)(()=>{z&&k.registerEditor(z)},[z,k]),(0,Yi.useEffect)(()=>{I&&k.registerFocusHandler(I)},[I,k]);letQ=Yi.default.useMemo(()=>({namespace:"ChatEditor",theme:{root:"tw-outline-none",paragraph:"tw-m-0"},nodes:[oz,iz,p6,vL,wL,az,...u?[f6]:[]],onError:oe=>{ne("Lexical error:",oe)},editable:!o}),[u,o]),Y=(0,Yi.useCallback)(oe=>{oe.read(()=>{letde=Oi().getTextContent();e(de)})},[e]),K=(0,Yi.useCallback)(oe=>{V(oe),w?.(oe)},[w]);returnYi.default.createElement(Bke,{initialConfig:Q},Yi.default.createElement(jke,{currentActiveFile:P},Yi.default.createElement("div",{className:we("tw-relative",i)},Yi.default.createElement(Xke,{contentEditable:Yi.default.createElement(Zke,{className:"tw-max-h-40 tw-min-h-[60px] tw-w-full tw-resize-none tw-overflow-y-auto tw-rounded-md tw-border-none tw-bg-transparent tw-px-2 tw-text-sm tw-text-normal tw-outline-none focus-visible:tw-ring-0","aria-label":"Chat input"}),placeholder:Yi.default.createElement("div",{className:"tw-pointer-events-none tw-absolute tw-left-2 tw-top-0 tw-select-none tw-text-sm tw-text-muted/60"},n),ErrorBoundary:oqe}),Yi
`})},K=Z=>Y(Z,"think","Thought for a while","Thinking..."),oe=Z=>{letle=lt=>{letqe=/```(?:xml)?\s*([\s\S]*?<writeToFile>[\s\S]*?<\/writeToFile>[\s\S]*?)\s*```/g;returnlt.replace(qe,(Nt,mt)=>mt.trim())},Ce=lt=>{if(!r)returnlt;letqe=/```xml\s*([\s\S]*?<writeToFile>[\s\S]*?)$/g;returnlt.replace(qe,(Nt,mt)=>mt.trim())},He=le(Z);returnHe=Ce(He),Y(He,"writeToFile","Generated new content","Generating changes...")},ue=(Z,le,Ce)=>Z.split(/(```[\s\S]*?```|`[^`]*`)/g).map((lt,qe)=>qe%2===0?lt.replace(le,(Nt,mt)=>{letOt=e.metadataCache.getFirstLinkpathDest(mt,X);returnOt?Ce(Ot):Nt}):lt).join(""),de=B(V),W=Q(de).replace(/\\\[\s*/g,"$$").replace(/\s*\\\]/g,"$$").replace(/\\\(\s*/g,"$").replace(/\s*\\\)/g,"$"),ie=ue(W,/!\[\[(.*?)]]/g,Z=>`})`),j=K(ie),A=oe(j),U=G4r(A,w.enableInlineCitations),H=ue(U,/(?<!!)\[\[([^\]]+)]]/g,Z=>`<a href="obsidian://open?file=${encodeURIComponent(Z.path)}">${Z.basename}</a>`);return(Z=>{if(!r)returnZ;letle=/!\[([^\]]*)\]\(([^)]+)\)/g;returnZ.replace(le,(Ce,He,lt)=>{letqe=yWe(lt);if(!qe)returnCe;letNt=He||"YouTube Video",mt=`https://i.ytimg.com/vi/${qe}/hqdefault.jpg`;return`[](${lt})`})})(H)},[e,r,w.enableInlineCitations,_]);(0,ur.useEffect)(()=>{letV=f.current;if(!V||t.sender===Zs||!r)return;letk=Q=>{if(QinstanceofPointerEvent&&(Q.button!==0||!Q.isPrimary))return;letY=Eqe(Q,V);if(!Y||!lSt(Q,Y))return;letK=!Y.open;Y.open=K,_.set(Y.id,K)},X=Q=>{letY=Eqe(Q,V);!Y||!lSt(Q,Y)||Q.preventDefault()},B=Q=>{letY=Eqe(Q,V);Y&&_.set(Y.id,Y.open)};returnV.addEventListener("pointerdown",k,!0),V.addEventListener("click",X,!0),V.addEventListener("toggle",B,!0),()=>{V.removeEventListener("pointerdown",k,!0),V.removeEventListener("click",X,!0),V.removeEventListener("toggle",B,!0)}},[r,t.sender,_]),(0,ur.useEffect)(()=>{if(m.current=!1,f.current&&t.sender!==Zs){p.current||(p.current=new_6.Component),ynn(f.current,_,{overwriteExisting:!r});letV=t.message,k=Bce(V);k?.hasReasoning&&k.status!=="idle"?d({status:k.status,elapsedSeconds:k.elapsedSeconds,steps:k.steps}):d(null);letX=k?.contentAfter??V,B=O(X),Q=cst(B,h.current);if(!m.current){letY=newSet,K=newSet;f.current.querySelectorAll('[id^="tool-call-"]').forEach(j=>{letA=j.id.replace("tool-call-","");Y.add(A)}),f.current.querySelectorAll('[id^="error-block-"]').forEach(j=>{letA=j.id.replace("error-block-","");K.add(A)}),f.current.querySelectorAll(".message-segment").forEach(j=>j.remove());letL=0;Q.segments.forEach(j=>{if(j.type==="text"&&j.content.trim()){letA=f.current.children[L],U=document.createElement("div");U.className="message-segment",A?f.current.insertBefore(U,A):f.current.appendChild(U),_6.MarkdownRenderer.renderMarkdown(j.content,U,"",p.current),pvi(U),L++}elseif(j.type==="toolCall"&&j.toolCall){letA=j.toolCall.id,U=document.getElementById(`tool-call-${A}`);if(!U){letre=f.current.children[L],Z=document.createElement("div");Z.className="tool-call-container",Z.id=`tool-call-${A}`,re?f.current.insertBefore(Z,re):f.current.appendChild(Z),U=Z}letH=nnn(h.current,y.current,A,U,"render refresh");!m.current&&!H.isUnmounting&&inn(H,j.toolCall),L++}elseif(j.type==="error"&&j.error){letA=j.error.id,U=document.getElementById(`error-block-${A}`);if(!U){letre=f.current.children[L],Z=document.createElement("div");Z.className="error-block-container",Z.id=`error-block-${A}`,re?f.current.insertBefore(Z,re):f.current.appendChild(Z),U=Z}letH=onn(h.current,g.current,A,U,"error render");!m.current&&!H.isUnmounting&&ann(H,j.error),L++}});letW=newSet(Q.segments.filter(j=>j.type==="toolCall"&&j.toolCall).map(j=>j.toolCall.id));Y.forEach(j=>{if(!W.has(j)){letA=document.getElementById(`tool-call-${j}`);A&&(snn(h.current,y.current,j,"tool call removal"),A.remove())}});letie=newSet(Q.segments.filter(j=>j.type==="error"&&j.error).map(j=>j.error.id));K.forEach(j=>{if(!ie.has(j)){letA=document.getElementById(`error-block-${j}`);A&&(unn(h.current,g.current,j,"error block removal"),A.remove())}})}}return()=>{m.current=!0}},[t,e,p,r,O,_]),(0,ur.useEffect)(()=>{letV=p,k=h.current,X=y.current,B=g.current;retur
`))},placeholder:"Enter web URLs, one per line",className:"tw-min-h-20 tw-w-full"})),vn.default.createElement(Vo,{label:"YouTube URLs"},vn.default.createElement(h_,{value:u.contextSource?.youtubeUrls,onChange:h=>{letg=h.target.value.split(`
`).filter(o=>o.trim()),n=[];for(let o of r){let i=Lwi(t,o.trim());i&&n.push(i)}return n}function Ron(t){let{app:e,contextNotes:r,setContextNotes:n,selectedImages:o,onAddImage:i,containerRef:a}=t,[s,u]=(0,Kqe.useState)(!1);return(0,Kqe.useEffect)(()=>{let l=a.current;if(!l)return;let c=p=>{if(p.preventDefault(),p.dataTransfer){p.dataTransfer.dropEffect="copy";let m=Array.from(p.dataTransfer.items).some(y=>y.kind==="string"),h=Array.from(p.dataTransfer.items).some(y=>y.kind==="file");(m||h)&&u(!0)}},d=p=>{let m=l.getBoundingClientRect(),h=p.clientX,y=p.clientY;(h<m.left||h>=m.right||y<m.top||y>=m.bottom)&&u(!1)},f=async p=>{if(!p.dataTransfer)return;p.preventDefault(),u(!1);let m=p.dataTransfer.items,h=[],y=[];for(let g=0;g<m.length;g++){let b=m[g];b.kind==="string"?h.push(b):b.kind==="file"&&y.push(b)}if(h.length>0){p.stopPropagation();let g=h.map(w=>new Promise(T=>{w.getAsString(O=>T(O))})),b=await Promise.all(g),_=new Map;for(let w of b){let T=Fwi(e,w);for(let O of T)_.set(O.path,O)}for(let w of _.values())if(["png","gif","jpeg","jpg","webp"].includes(w.extension)){if(o.some(I=>I.name===w.name)){new x6.Notice("Thisimageisalreadyinthecontext");continue}let E=await e.vault.readBinary(w),P=new Blob([E]),R=new File([P],w.name,{type:`image/${w.extension}`});i([R])}else if(yO(w)){if(r.some(E=>E.path===w.path)){new x6.Notice("Thisnoteisalreadyinthecontext");continue}n(E=>[...E,w])}else new x6.Notice(`Unsupported file type: ${w.extension}. Supported types: md, pdf, canvas, and images.`)}else if(y.length>0){let g=[];for(let b of y){let _=b.getAsFile();_&&_.type.startsWith("image/")&&g.push(_)}g.length>0&&i(g)}};return l.addEventListener("dragover",c),l.addEventListener("dragleave",d),l.addEventListener("drop",f),()=>{l.removeEventListener("dragover",c),l.removeEventListener("dragleave",d),l.removeEventListener("drop",f)}},[e,r,o,i,n,a]),{isDragActive:s}}mr();Bt();Xe();qN();var qSt=async(t,e,r,n,o,i={})=>{let a=new AbortController;o(a);try{await e.runChain(t,a,n,r,i)}catch(s){ne("Modelrequestfailed:",s);let u=ePe("Modelrequestfailed:"+zr(s));r({id:od(),sender:cw,isErrorMessage:!0,message:u,isVisible:!0,timestamp:Mg(new Date)})}};O4();Fc();Ye();Bt();HEe();var Al=require("obsidian");var qt=$(J());qN();var kwi=({chainManager:t,onSaveChat:e,updateUserMessageHistory:r,fileParserManager:n,plugin:o,chatUIState:i,chatInput:a})=>{let s=Br(),u=(0,qt.useContext)(ZY),{messages:l,addMessage:c}=Mon(i),[d]=bF(),[f]=fw(),[p,m]=(0,qt.useState)(""),[h,y]=(0,qt.useState)(""),[g,b]=(0,qt.useState)(null),_=(0,qt.useRef)(null),w=(0,qt.useRef)(null),T=(0,qt.useCallback)(rt=>{let Rr=w.current,Ee=Rr&&rt.sender===cw&&!rt.isErrorMessage&&!rt.id?{...rt,id:Rr}:rt;c(Ee),Ee.sender===cw&&Ee.responseMetadata?.tokenUsage?.totalTokens&&b(Ee.responseMetadata.tokenUsage.totalTokens)},[c]),O=(0,qt.useCallback)(rt=>{_.current=rt},[]),[E,P]=(0,qt.useState)(!1),[R,I]=(0,qt.useState)(dw.DEFAULT),[N,z]=(0,qt.useState)([]),[V,k]=(0,qt.useState)(!1),[X,B]=(0,qt.useState)(!1),[Q,Y]=(0,qt.useState)([]),[K,oe]=(0,qt.useState)(!1),[ue,de]=(0,qt.useState)([]),[L,W]=(0,qt.useState)(null),[ie,j]=(0,qt.useState)(null),[A]=l5(),U=(0,qt.useRef)(!1),H=(0,qt.useRef)(null),re=(0,qt.useCallback)(()=>{o.chatSelectionHighlightController.persistFromPointerDown()},[o]),Z=(0,qt.useMemo)(()=>({setCurrentAiMessage:rt=>U.current&&m(rt),setLoadingMessage:rt=>U.current&&I(rt),setLoading:rt=>U.current&&P(rt)}),[]),[le]=bDt(),Ce=le.length>0,He=V&&!Ce,lt=X&&!Ce,{activeWebTabForMentions:qe}=rz(),Nt=ULe(),mt=()=>Ue!=="project"?!1:L!==null?L:Nt==="loading"||Nt==="error";(0,qt.useEffect)(()=>{W(null)},[Nt]);let Ot=()=>Ue==="project"||ie===!1?!1:A.isActive||A.completionStatus!=="none";(0,qt.useEffect)(()=>{(A.isActive||A.completionStatus!=="none")&&j(null)},[A.isActive,A.completionStatus]);let je=(0,qt.useCallback)(()=>{j(!1),A.isActive||Ig({completionStatus:"none"})},[A.isActive]),Gr=(0,qt.useCallback)(async()=>{(await Promise.resolve().then(()=>(Pl(),Vc))).default.getInstance().pauseIndexing()},[]),ct=(0,qt.useCallback)(async()=>{(await Promise.resolve().then(()=>(Pl(),Vc))).default.ge
`));let Eh={notes:Xv,urls:zb(f)?Rr||[]:[],tags:Ee||[],folders:It||[],selectedTextContexts:le,webTabs:Qt||[]};y(""),Y([]),w.current=`msg-${od()}`,Z.setLoading(!0),Z.setLoadingMessage(dw.DEFAULT);let FC=await i.sendMessage(DL,Eh,f,He,lt,cl.length>0?cl:void 0,Z.setLoadingMessage);h&&r(h),s.autosaveChat&&Dl();let Zv=i.getLLMMessage(FC);Zv&&await qSt(Zv,t,T,Z.setCurrentAiMessage,O,{debug:s.debug,updateLoadingMessage:Z.setLoadingMessage}),s.autosaveChat&&Dl()}catch(cl){ne("Errorsendingmessage:",cl),new Al.Notice("Failedtosendmessage.Pleasetryagain.")}finally{Z.setLoading(!1),Z.setLoadingMessage(dw.DEFAULT),w.current=null}},Dl=(0,qt.useCallback)(async()=>{if(!iu){ne("Appinstanceisnotavailable.");return}try{await i.saveChat(d)}catch(rt){ne("Errorsavingchatasnote:",zr(rt)),new Al.Notice("Failedtosavechatasnote.Checkconsolefordetails.")}},[iu,i,d]),Vi=(0,qt.useCallback)(rt=>{_.current&&(F(`stopping generation..., reason: ${rt}`),_.current.abort(rt),Z.setLoading(!1),Z.setLoadingMessage(dw.DEFAULT))},[Z]);(0,qt.useEffect)(()=>(U.current=!0,()=>{U.current=!1,_.current&&_.current.abort("component-unmount")}),[]);let O_=(0,qt.useCallback)(async rt=>{if(rt<=0){new Al.Notice("Cannotregeneratethefirstmessage.");return}let Rr=l[rt];if(!Rr){new Al.Notice("Messagenotfound.");return}Z.setCurrentAiMessage(""),w.current=`msg-${od()}`,Z.setLoading(!0);try{await i.regenerateMessage(Rr.id,Z.setCurrentAiMessage,T)?s.debug&&console.log("Messageregeneratedsuccessfully"):new Al.Notice("Failedtoregeneratemessage.Pleasetryagain."),s.autosaveChat&&Dl()}catch(Be){ne("Errorregeneratingmessage:",Be),new Al.Notice("Failedtoregeneratemessage.Pleasetryagain.")}finally{Z.setLoading(!1),w.current=null}},[l,i,s.debug,s.autosaveChat,Dl,T,Z]),wg=(0,qt.useCallback)(async(rt,Rr)=>{let Be=l[rt];if(!(!Be||Be.message===Rr))try{if(!await i.editMessage(Be.id,Rr,f,He)){new Al.Notice("Failedtoeditmessage.Pleasetryagain.");return}if(Be.sender===Zs){let It=rt<l.length-1;if(await i.truncateAfterMessageId(Be.id),It){w.current=`msg-${od()}`,Z.setLoading(!0);try{let Qt=i.getLLMMessage(Be.id);Qt&&await qSt(Qt,t,T,Z.setCurrentAiMessage,O,{debug:s.debug,updateLoadingMessage:Z.setLoadingMessage})}catch(Qt){ne("ErrorregeneratingAIresponse:",Qt),new Al.Notice("FailedtoregenerateAIresponse.Pleasetryagain.")}finally{Z.setLoading(!1),w.current=null}}}s.autosaveChat&&Dl()}catch(Ee){ne("Erroreditingmessage:",Ee),new Al.Notice("Failedtoeditmessage.Pleasetryagain.")}},[l,i,f,He,T,t,s.debug,s.autosaveChat,Dl,Z,O]);(0,qt.useEffect)(()=>{e&&e(Dl)},[e,Dl]);let yS=(0,qt.useCallback)(rt=>{let Rr=s.projectList||[];if(Rr.findIndex(Qt=>Qt.name===rt.name)>=0)throw new Error(`Project "${rt.name}" already exists, please use a different name`);let Ee=[...Rr,rt];return Re("projectList",Ee),Gu()?.id===rt.id?wFe().then(()=>{new Al.Notice(`${rt.name} added and context loaded`)}).catch(Qt=>{ne("Errorloadingprojectcontext:",Qt),new Al.Notice(`${rt.name} added but context loading failed`)}):new Al.Notice(`${rt.name} added successfully`),!0},[s.projectList]),ji=(0,qt.useCallback)((rt,Rr)=>{let Be=s.projectList||[];if(!Be.find(Fn=>Fn.name===rt.name))throw new Error(`Project "${rt.name}" does not exist`);let It=Be.map(Fn=>Fn.name===rt.name?Rr:Fn);return Re("projectList",It),Gu()?.id===rt.id?(D4(Rr),wFe().then(()=>{new Al.Notice(`${rt.name} updated and context reloaded`)}).catch(Fn=>{ne("Errorreloadingprojectcontext:",Fn),new Al.Notice(`${rt.name} updated but context reload failed`)})):new Al.Notice(`${rt.name} updated successfully`),!0},[s.projectList]),KT=(0,qt.useCallback)(rt=>{let Be=tx().find(Ee=>Ee.id===rt);gDt(rt),Be?.sourceType==="web"&&o.suppressCurrentWebSelection(Be.url)},[o]);(0,qt.useEffect)(()=>{o.chatSelectionHighlightController.clearIfNoNoteContexts(le)},[le,o]),(0,qt.useEffect)(()=>{let rt=()=>{a.focusInput()};return u?.addEventListener(US.CHAT_IS_VISIBLE,rt),()=>{u?.removeEventListener(US.CHAT_IS_VISIBLE,rt)}},[u,a]);let LC=(0,qt.useCallback)(async rt=>{let Rr=l[rt];if(!Rr){new Al.Notice("Messagenotfound.");return}try{a
Original name: ${a.title}
${a.content}`}):e.push(a)}await th.getInstance().updateCommands([...n.map(a=>({...a,showInSlashMenu:!0})),...e]);let i=`We have upgraded your commands to the new format. They are now also stored as notes in ${mB()}.`;r.length>0&&(await zwi(r),i+=`
We found ${r.length} unsupported commands. They are saved in ${mB()}/unsupported. To fix them, please resolve the errors and move the note file out of the unsupported folder.`),Re("inlineEditCommands",[]),new zu(app,()=>{},i,"\u{1F680}NewCopilotCustomCommands","OK","").open()}async function USt(){let t=Pv(),e=RWr.filter(n=>!t.some(o=>o.title===n.title)),r=[...t,...e];th.getInstance().updateCommands(r)}async function Fon(){if(te().suggestedDefaultCommands)return;Pv().length===0&&(new zu(app,()=>{USt()},"WouldyouliketoaddCopilotrecommendedcommandsinyourcustompromptsfolder?Thesecommandswillbeavailablethroughtheright-clickcontextmenuandslashcommandsinchat.","WelcometoCopilot","Confirm","Skip").open(),Re("suggestedDefaultCommands",!0))}mr();Ye();sd();ra();Xe();mr();async function kon(t,e){await e.clearChatMemory();for(let r=0;r<t.length-1;r++){let n=t[r];if(n.sender===Zs){let o=t[r+1];o?.sender===cw&&await e.saveContext({input:n.message},{output:o.message})}}}ra();sd();mr();var Bon=$(gH());Xe();var qon=["L1_SYSTEM","L2_PREVIOUS","L3_TURN","L4_STRIP","L5_USER"],Uon={L1_SYSTEM:"SystemInstructions",L2_PREVIOUS:"PreviousTurnContext",L3_TURN:"CurrentTurnContext",L4_STRIP:"ConversationStrip",L5_USER:"UserMessage"};var bz=class bz{constructor(){}static getInstance(){return bz.instance||(bz.instance=new bz),bz.instance}buildEnvelope(e){let r=qon.map(s=>this.buildLayer(s,e.layerSegments[s]??[])),n=this.serializeLayers(r),o=this.collectLayerHashes(r),i=this.hash(n),a=typeof e.metadata?.debugLabel=="string"?e.metadata.debugLabel:void 0;return a&&F(`[PromptContextEngine] Built envelope for ${a}`,o),{version:bz.ENVELOPE_VERSION,conversationId:e.conversationId,messageId:e.messageId,layers:r,serializedText:n,layerHashes:o,combinedHash:i,debug:{warnings:this.collectWarnings(r)}}}buildLayer(e,r){let n=r.map((i,a)=>({...i,id:i.id||`${e}-segment-${a}`,content:this.normalizeWhitespace(i.content),stable:i.stable??!0})),o=this.normalizeWhitespace(n.map(i=>i.content).filter(Boolean).join(`
`;e=e.slice(0,d)+m+e.slice(f)}}returne}asyncexecuteDataviewQuery(e,r,n,o){if(n==="dataviewjs")return"[DataviewJS execution not yet supported - showing original query]";leti=awaite.query(r,o);if(!i.successful)thrownewError(i.error||"Query failed");returnthis.formatDataviewResult(i.value)}formatDataviewResult(e){returne?e.type==="list"?this.formatDataviewList(e.values):e.type==="table"?this.formatDataviewTable(e.headers,e.values):e.type==="task"?this.formatDataviewTasks(e.values):Array.isArray(e)?e.map(r=>this.formatDataviewValue(r)).join(`
`)}formatDataviewValue(e){returne==null?"":e&&typeofe=="object"&&e.path?`[[${e.path}]]`:Array.isArray(e)?e.map(r=>this.formatDataviewValue(r)).join(", "):String(e)}asyncbuildMarkdownContextContent(e,r,n,o){leti=awaitn.parseFile(e,r);returni=awaitthis.processEmbeddedNotes(i,e,r,n,o),zb(o)&&(i=awaitthis.processEmbeddedPDFs(i,r,n)),awaitthis.processDataviewBlocks(i,e.path)}asyncprocessEmbeddedNotes(e,r,n,o,i){leta=/!\[\[([^\]]+)\]\]/g,s,u=0,l="";for(;(s=a.exec(e))!==null;){l+=e.slice(u,s.index);letc=s[1].trim(),d=awaitthis.buildEmbeddedNoteBlock(c,s[0],r,n,o,i);l+=d,u=s.index+s[0].length}returnl+=e.slice(u),l}asyncbuildEmbeddedNoteBlock(e,r,n,o,i,a){lets=this.parseEmbeddedLinkTarget(e);if(!s)returnr;letu=s.path===null?n:app.metadataCache.getFirstLinkpathDest(s.path,n.path);if(!(uinstanceofnpe.TFile))returnthis.formatEmbeddedNoteBlock({title:s.path??n.basename,path:s.path??n.path,heading:s.heading,blockId:s.blockId,error:"Embedded note not found"});if(u.extension!=="md")returnr;try{letl=awaiti.parseFile(u,o);if(s.heading||s.blockId){letc=this.extractMarkdownSegment(u,l,s);if(!c.found){letd=s.blockId?`block reference "${s.blockId}"`:`heading "${s.heading??""}"`;thrownewError(`Embedded note ${d} not found in ${u.path}`)}l=c.content}returnzb(a)&&(l=awaitthis.processEmbeddedPDFs(l,o,i)),l=awaitthis.processDataviewBlocks(l,u.path),this.formatEmbeddedNoteBlock({title:u.basename,path:u.path,heading:s.heading,blockId:s.blockId,content:l})}catch(l){Te("Failed to process embedded note",l);letc=linstanceofError?l.message:"Could not process embedded note";returnthis.formatEmbeddedNoteBlock({title:u.basename,path:u.path,heading:s.heading,blockId:s.blockId,error:c})}}parseEmbeddedLinkTarget(e){if(!e)returnnull;letr=e.indexOf("|"),o=(r>=0?e.slice(0,r):e).trim();if(!o)return{path:null};leti,a,s=o.indexOf("#^");s!==-1&&(i=o.slice(s+2).trim(),o=o.slice(0,s));letu=o.indexOf("#");returnu!==-1&&(a=o.slice(u+1).trim(),o=o.slice(0,u)),{path:o.length>0?o:null,heading:a&&a.length>0?a:void0,blockId:i&&i.length>0?i:void0}}extractMarkdownSegment(e,r,n){leto=app.metadataCache.getFileCache(e);if(n.blockId){leti=o?.blocks?.[n.blockId],a=i?.position?.start?.offset,s=i?.position?.end?.offset;returna===void0||s===void0?{content:"",found:!1}:{content:r.slice(a,s),found:!0}}if(n.heading){leti=o?.headings??[],a=this.normalizeHeadingForMatch(n.heading),s=i.findIndex(d=>this.normalizeHeadingForMatch(d.heading)===a);if(s===-1)return{content:"",found:!1};letu=i[s],l=u.position?.start?.offset??0,c=r.length;for(letd=s+1;d<i.length;d++)if(i[d].level<=u.level){c=i[d].position?.start?.offset??c;break}return{content:r.slice(l,c),found:!0}}return{content:r,found:!0}}normalizeHeadingForMatch(e){returne.trim().toLowerCase().replace(/\s+/g," ")}formatEmbeddedNoteBlock(e){let{title:r,path:n,heading:o,blockId:i,content:a,error:s}=e,u=`
`,u}asyncprocessContextNotes(e,r,n,o,i,a,s){letu="",l=async(d,f=Dte)=>{try{if(e.has(d.path)){F(`Skipping note ${d.path} as it was included via custom prompt.`);return}if(!r.supportsExtension(d.extension)){Te(`Unsupported file type: ${d.extension}`);return}if(!zb(s)&&d.extension!=="md"&&d.extension!=="canvas"){Te(`File type ${d.extension} requires Copilot Plus mode for context processing.`),newnpe.Notice(YJ.NON_MARKDOWN_FILES_RESTRICTED);return}letp=d.extension==="md"?awaitthis.buildMarkdownContextContent(d,n,r,s):awaitr.parseFile(d,n),m=awaitn.adapter.stat(d.path),h=m?newDate(m.ctime).toISOString():"Unknown",y=m?newDate(m.mtime).toISOString():"Unknown";u+=`
</${TWe}>`),_.join("")},u=null,l=[],c=newSet,d=newSet,f=_d(app),p=b=>{let_=f.getYouTubeVideoId(b);return_?d.has(_)?!0:(d.add(_),!1):c.has(b)?!0:(c.add(b),!1)};for(letbofe){let_=_b(b.url);_&&b.isActive&&!u&&(u={...b,url:_},p(_))}for(letbofe){let_=_b(b.url);!_||p(_)||l.push({...b,url:_})}if(!u&&l.length===0)return"";letm=f.getAvailability();if(!m.supported||!m.available){letb=m.reason??(m.supported?"Web Viewer is not available.":"Web Viewer is not supported on this platform."),_=[];u&&_.push(a(vye,{title:u.title||"Unknown",url:u.url,error:b}));for(letwofl)_.push(a(xWe,{title:w.title||"Unknown",url:w.url,error:b}));return_.join("")}leth=async(b,_)=>{try{letw=b.url,T=f.getYouTubeVideoId(w);if(T)returnawaity(b,T,_===vye);letO=f.findLeafByUrl(w,{title:b.title});if(!O)returna(_,{title:b.title||"Unknown",url:w,error:"Web tab not found or closed"});letE=f.getPageInfo(O),P=O.view;if(!(P.webviewMounted===void0||P.webviewFirstLoadFinished===void0?!0:!!(P.webviewMounted&&P.webviewFirstLoadFinished)))try{awaitf.waitForWebviewReady(O,r),E=f.getPageInfo(O)}catch(z){returnTe(`Web tab content not loaded yet for ${w}:`,z),a(_,{title:E.title||b.title||"Untitled",url:E.url||w,mode:E.mode,error:"Web tab content not loaded yet"})}letI=newAbortController,N=setTimeout(()=>{I.abort()},n);try{letz=awaitf.getReaderModeMarkdown(O,{signal:I.signal});returnE=f.getPageInfo(O),a(_,{title:E.title||b.title||"Untitled",url:E.url||w,mode:E.mode,content:z})}finally{clearTimeout(N)}}catch(w){returnne(`Error processing web tab ${b.url}:`,w),a(_,{title:b.title||"Unknown",url:b.url,error:winstanceofPB?"Web tab content extraction timed out":"Could not process web tab"})}},y=async(b,_,w)=>{try{letT=null,O=b.url;for(letNoff.getLeaves()){letz=f.getPageInfo(N).url;if(f.getYouTubeVideoId(z)===_){T=N,O=z;break}}if(!T)returns({title:b.title||"YouTube Video",url:b.url,videoId:_,isActive:w,error:"Web tab not found or closed"});letE=T.view;if(!(E.webviewMounted===void0||E.webviewFirstLoadFinished===void0?!0:!!(E.webviewMounted&&E.webviewFirstLoadFinished)))try{awaitf.waitForWebviewReady(T,r)}catch(N){returnTe(`YouTube tab content not loaded yet for ${O}:`,N),s({title:b.title||"YouTube Video",url:O,videoId:_,isActive:w,error:"Web tab content not loaded yet"})}letR=awaitf.getYouTubeTranscript(T,{timeoutMs:o}),I=R.transcript.length>0?R.transcript.map(N=>`${N.timestamp}: ${N.text}`).join(`
`):void0;returns({title:R.title||b.title||"YouTube Video",url:O,videoId:R.videoId,channel:R.channel,description:R.description,uploadDate:R.uploadDate,duration:R.duration,genre:R.genre,transcript:I,isActive:w})}catch(T){returnTe(`YouTube transcript extraction failed for ${b.url}:`,T),s({title:b.title||"YouTube Video",url:b.url,videoId:_,isActive:w,error:TinstanceofError?T.message:"Failed to extract video info"})}},g=[];if(u){letb=awaith(u,vye);g.push(b)}for(letb=0;b<l.length;b+=i){let_=l.slice(b,b+i),w=awaitPromise.all(_.map(T=>h(T,xWe)));g.push(...w)}returng.join("")}};Xe();Ye();Bt();varVSt=null;asyncfunctionWwi(){returnVSt||(VSt=(awaitPromise.resolve().then(()=>(Won(),Hon))).ContextCompactor),VSt.getInstance()}vareUe=classt{constructor(){this.contextProcessor=Qqe.getInstance(),this.mention=s9.getInstance(),this.promptContextEngine=Yqe.getInstance()}staticgetInstance(){returnt.instance||(t.instance=newt),t.instance}asyncprocessMessageContext(e,r,n,o,i,a,s,u,l=[],c){try{F(`[ContextManager] Processing context for message ${e.id}`);letd=e.originalMessage||e.message,{processedPrompt:f,includedFiles:p}=awaitsde(d,"",n,a),{l2Context:m,l2Paths:h}=this.buildL2ContextFromPreviousTurns(e.id,s),y=e.context?.urls||[],g=o==="copilot_plus"?awaitthis.mention.processUrlList(y):{urlContext:"",imageUrls:[]},b=newSet([...p.map(W=>W.path),...l.map(W=>W.path),...h]),_=newSet,T=(e.context?.notes||[]).filter(W=>!h.has(W.path));i&&o!=="project"&&a&&!b.has(a.path)&&!T.some(W=>W.path===a.path)&&T.push(a);letO=awaitthis.contextProcessor.processContextNotes(b,r,n,T,i,a,o);T.forEach(W=>{b.add(W.path),_.add(W.path)});letE=e.context?.tags||[],P="",R=[];if(E.length>0){letie=mye(n,E).filter(j=>!b.has(j.path));ie.length>0&&(P=awaitthis.contextProcessor.processContextNotes(newSet,r,n,ie,!1,null,o),ie.forEach(j=>{b.add(j.path),_.add(j.path),R.push(j.path)}))}letI=e.context?.folders||[],N="",z=[];if(I.length>0){letie=I.flatMap(j=>Ote(n,j)).filter(j=>!b.has(j.path));ie.length>0&&(N=awaitthis.contextProcessor.processContextNotes(newSet,r,n,ie,!1,null,o),ie.forEach(j=>{b.add(j.path),_.add(j.path),z.push(j.path)}))}letV=this.contextProcessor.processSelectedTextContexts(),k=e.context?.webTabs||[],X=awaitthis.contextProcessor.processContextWebTabs(k),B=m+O+P+N+g.urlContext+V+X,Q=f+B,oe=(o==="project"?1e6:te().autoCompactThreshold)*4,ue=!1,de=B;if(Q.length>oe){c?.(dw.COMPACTING);letie=await(awaitWwi()).compact(B);ie.wasCompacted&&(de=ie.content,Q=f+de,ue=!0,F(`[ContextManager] Compacted context: ${ie.originalCharCount} -> ${ie.compactedCharCount} chars`)),c?.(dw.DEFAULT)}F(`[ContextManager] Successfully processed context for message ${e.id}`);letL=ue?this.buildCompactedEnvelope({chainType:o,message:e,systemPrompt:u||"",processedUserMessage:f,compactedContext:de,compactedPaths:Array.from(_)}):this.buildPromptContextEnvelope({chainType:o,message:e,systemPrompt:u||"",processedUserMessage:f,l2PreviousContext:m,noteContextAddition:O,tagContextAddition:P,tagNotePaths:R,folderContextAddition:N,folderNotePaths:z,urlContext:g.urlContext,selectedText:V,webTabContext:X});return{processedContent:Q,contextEnvelope:L}}catch(d){returnF(`[ContextManager] Error processing context for message ${e.id}:`,d),{processedContent:e.originalMessage||e.message,contextEnvelope:void0}}}asyncreprocessMessageContext(e,r,n,o,i,a,s,u,l=[]){letc=r.getMessage(e);if(!c||c.sender!=="user"||!c.id)return;F(`[ContextManager] Reprocessing context for message ${e}`);let{processedContent:d,contextEnvelope:f}=awaitthis.processMessageContext(c,n,o,i,a,s,r,u,l);r.updateProcessedText(c.id,d,f),F(`[ContextManager] Completed context reprocessing for message ${e}`)}buildL2ContextFromPreviousTurns(e,r){letn=r.getDisplayMessages(),o=n.findIndex(p=>p.id===e);if(o===-1||o===0)return{l2Context:"",l2Paths:newSet};leti=n.slice(0,o).filter(p=>p.sender==="user"),a=newMap,s=[],u=newSet,l=-1;for(letp=i.length-1;p>=0;p--)if(i[p].contextEnvelope?.layers?.find(g=>g.id==="L3_TURN")?.segments?.some(g=>g.metadata?.wasCompacted)){l=p;break}for(letp=0;p<i.length;p++){leth=i[p]
`)){leta=i.match(/^(\w+):\s*(.+)/);a&&(o[a[1]]=a[2].trim().replace(/^["']|["']$/g,""))}returno}asyncfunctionKon(t,e){letr=awaitt.vault.adapter.stat(e),n=e.split("/").pop()??"";return{path:e,name:n,basename:n.replace(/\.md$/,""),extension:"md",stat:r??{ctime:Date.now(),mtime:Date.now(),size:0},vault:t.vault,parent:null}}varC_=require("obsidian"),KSt=100;functionJwi(t){returnt.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}varipe=class{constructor(e,r,n){this.app=e;this.messageRepo=r;this.chainManager=n}asyncsaveChat(e){try{letr=this.messageRepo.getDisplayMessages();if(r.length===0){newC_.Notice("No messages to save.");return}letn=te(),o=this.formatChatContent(r),i=r[0].timestamp?.epoch||Date.now();await$c(n.defaultSaveFolder);leta=awaitthis.findFileByEpoch(i),s=a?this.app.metadataCache.getFileCache(a)?.frontmatter:void0,u=s?.topic,l=s?.lastAccessedAt;if(a&&!s)try{letm=awaitJSt(this.app,a.path);m&&(m.topic&&(u=m.topic),m.lastAccessedAt&&(l=Number(m.lastAccessedAt)))}catch{}letc=a?a.path:this.generateFileName(r,i,u),d=this.generateNoteContent(o,i,e,u,l),f=a,p=a!=null&&WSt(this.app,a.path);if(a&&p)awaitthis.app.vault.modify(a,d),F(`[ChatPersistenceManager] Updated existing chat file: ${a.path}`);elseif(!WSt(this.app,c)&&awaitthis.app.vault.adapter.exists(c))awaitthis.app.vault.adapter.write(c,d),newC_.Notice("Existing chat note found - updating it now."),F(`[ChatPersistenceManager] Updated existing chat file via adapter: ${c}`);elsetry{f=awaitthis.app.vault.create(c,d),newC_.Notice(`Chat saved as note: ${c}`),F(`[ChatPersistenceManager] Created new chat file: ${c}`)}catch(m){if(this.isFileAlreadyExistsError(m)){leth=this.app.vault.getAbstractFileByPath(c);if(h&&hinstanceofC_.TFile){lety=this.app.metadataCache.getFileCache(h)?.frontmatter;u=y?.topic??u;letg=y?.lastAccessedAt,b=this.generateNoteContent(o,i,e,u,g);awaitthis.app.vault.modify(h,b),f=h,newC_.Notice("Existing chat note found - updating it now."),F(`[ChatPersistenceManager] Resolved save conflict by updating existing chat file: ${h.path}`)}elseawaitthis.app.vault.adapter.write(c,d),newC_.Notice("Existing chat note found - updating it now."),F(`[ChatPersistenceManager] Resolved save conflict via adapter: ${c}`)}elseif(this.isNameTooLongError(m)){leth=Gu(),y=h?`${h.id}__`:"",g=`${n.defaultSaveFolder}/${y}chat-${i}.md`;try{f=awaitthis.app.vault.create(g,d),newC_.Notice(`Chat saved as note: ${g}`),Te(`[ChatPersistenceManager] Used minimal filename due to length constraints: ${g}`)}catch(b){if(this.isFileAlreadyExistsError(b)){let_=this.app.vault.getAbstractFileByPath(g);if(_&&_instanceofC_.TFile){letw=this.app.metadataCache.getFileCache(_)?.frontmatter,T=w?.lastAccessedAt,O=w?.topic,E=this.generateNoteContent(o,i,e,O,T);awaitthis.app.vault.modify(_,E),f=_,newC_.Notice("Existing chat note found - updating it now."),F(`[ChatPersistenceManager] Resolved fallback save conflict by updating existing chat file: ${_.path}`)}elseawaitthis.app.vault.adapter.write(g,d),newC_.Notice("Existing chat note found - updating it now."),F(`[ChatPersistenceManager] Resolved fallback save conflict via adapter: ${g}`)}elsethrowb}}elsethrowm}this.generateTopicAsyncIfNeeded(r,f,u)}catch(r){ne("[ChatPersistenceManager] Error saving chat:",r),newC_.Notice("Failed to save chat as note. Check console for details.")}}asyncloadChat(e){try{letr;try{r=awaitthis.app.vault.read(e)}catch{r=awaitthis.app.vault.adapter.read(e.path)}letn=this.parseChatContent(r);returnF(`[ChatPersistenceManager] Loaded ${n.length} messages from ${e.path}`),n}catch(r){returnne("[ChatPersistenceManager] Error loading chat:",r),newC_.Notice("Failed to load chat history. Check console for details."),[]}}asyncgetChatHistoryFiles(){lete=te(),r=awaittUe(this.app,e.defaultSaveFolder);if(r.length===0)return[];letn=Gu();returnr.filter(o=>n?o.basename.startsWith(`${n.id}__`):!o.basename.includes("__")||!o.basename.split("__")[0])}formatChatContent(e){returne.map(r=>{letn=r.timestamp?r.timestamp.display:"Unknown time",o=r.message;if(r.sender===cw){leta=Bce(o);a&&(o=a.c
</user_custom_instructions>`):r===n?o:(F("[ChatManager] Could not locate <user_custom_instructions> block for injection; returning original system prompt."),r)}replaceSystemPromptWithoutMemoryInBasePrompt(e){let{basePromptWithMemory:r,systemPromptWithoutMemory:n,processedSystemPromptWithoutMemory:o}=e;return r.endsWith(n)?`${r.slice(0,r.length-n.length)}${o}`:(F("[ChatManager] basePromptWithMemory does not end with systemPromptWithoutMemory; returning original base prompt."),r)}async getSystemPromptForMessage(e,r,n){let o=ije(),i=[],a=await T$(this.chainManager.userMemoryManager),s=x$(),u=a;if(o){let l=await this.processSystemPromptTemplates(o,r,n),c=this.injectProcessedUserCustomPromptIntoSystemPrompt({systemPromptWithoutMemory:s,userCustomPrompt:o,processedUserCustomPrompt:l.processedPrompt}),d=this.replaceSystemPromptWithoutMemoryInBasePrompt({basePromptWithMemory:a,systemPromptWithoutMemory:s,processedSystemPromptWithoutMemory:c});d!==a&&i.push(...l.includedFiles),u=d}if(e==="project"){let l=Gu();if(l){let c=await ry.instance.getProjectContext(l.id),d=await this.processSystemPromptTemplates(l.systemPrompt,r,n);i.push(...d.includedFiles);let f=`${u}
</project_system_prompt>`;if(c){let m=c;c.length>24e5&&(m=c.substring(0,24e5),Te(`Project context truncated from ${Math.round(c.length/4e3)}k to ${Math.round(24e5/4e3)}k estimated tokens to stay within token budget`)),f+=`
with CORS Error: `+zr(l);throw new Error(c)}}let a=await i.json();return{success:!0,models:g0t(t,a)}}catch(e){return ne(`Error fetching models for ${t}:`,e),{success:!1,models:[],error:zr(e)}}}async function Oan(t,e,r){let n=r?.skipVerification??!1,i=!!e.find(c=>c.name===t.name&&c.provider===t.provider),a=t.provider==="github-copilot"?void 0:Bb(t.provider),s={name:t.name,provider:t.provider,apiKey:a,enabled:!0},u=!1,l;if(!n)try{await ry.instance.getCurrentChainManager().chatModelManager.ping(s)}catch(c){u=!0,l=zr(c),ne("Modelverificationfailed:",c)}return{success:!0,alreadyExists:i,verificationFailed:u,verificationError:l}}function Ean(t){return{name:t.name,provider:t.provider,enabled:!0}}Bt();Or();var AL=require("obsidian"),Hu=$(J());function AUe({provider:t,isReady:e,expanded:r=!1,skipVerification:n=!1,credentialVersion:o}){let i=Br(),[a,s]=(0,Hu.useState)(null),[u,l]=(0,Hu.useState)(!1),[c,d]=(0,Hu.useState)(null),[f,p]=(0,Hu.useState)(null),[m,h]=(0,Hu.useState)(!1),y=(0,Hu.useRef)(!1),g=(0,Hu.useCallback)(async()=>{if(!(y.current||!e)){y.current=!0,l(!0),d(null);try{let w=await Tan(t);w.success?s(w.models):(d(w.error||"Failedtoloadmodels"),new AL.Notice(`Failed to load models for ${Rg(t)}: ${w.error}`,5e3))}catch(w){let T=zr(w);d(T),new AL.Notice(`Failed to load models for ${Rg(t)}: ${T}`,5e3)}finally{l(!1),y.current=!1}}},[t,e]);(0,Hu.useEffect)(()=>{s(null),p(null),d(null)},[t,o]),(0,Hu.useEffect)(()=>{r&&e&&a===null&&!u&&!c&&g()},[r,e,a,u,c,g]);let b=async()=>{if(!f){new AL.Notice("Pleaseselectamodelfirst");return}h(!0);try{let w=await Oan({id:f.id,name:f.name,provider:t},i.activeModels,{skipVerification:n});if(w.alreadyExists)w.verificationFailed?new AL.Notice(`Model ${f.name} already exists (verification failed: ${w.verificationError})`,1e4):new AL.Notice(`Model ${f.name} verified successfully! It already exists in your models list.`);else{let T=Ean({id:f.id,name:f.name,provider:t}),O=[...i.activeModels,T];Re("activeModels",O),w.verificationFailed?new AL.Notice(`Model ${f.name} added (verification failed: ${w.verificationError})`,1e4):new AL.Notice(`Model ${f.name} verified and added to your models list!`)}}catch(w){ne("Erroraddingmodel:",w),new AL.Notice(`Failed to add model: ${zr(w)}`)}finally{h(!1)}},_=a?.filter((w,T,O)=>O.findIndex(E=>E.id===w.id)===T).sort((w,T)=>w.name.localeCompare(T.name));return Hu.default.createElement(Vo,{label:"Model",description:"Addtheselectedmodeltoyourmodelslist.Afteradding,checktheModelTab."},Hu.default.createElement("div",null,Hu.default.createElement("div",{className:"tw-flextw-items-centertw-gap-2"},Hu.default.createElement("div",{className:"tw-flex-1"},Hu.default.createElement(_N,{options:_?.map(w=>({label:w.name,value:w.id}))||[],onChange:w=>{let T=w.target.value,O=a?.find(E=>E.id===T);O&&p(O)},onClick:()=>{a===null&&!u&&g()},value:f?.id||"",placeholder:"SelectModel",disabled:!e||u})),Hu.default.createElement("div",{className:"tw-w-[72px]"},Hu.default.createElement(pe,{onClick:b,disabled:!f||m,variant:"secondary",size:"sm",className:"tw-w-fulltw-whitespace-nowrap"},m?Hu.default.createElement(Bs,{className:"tw-mr-2tw-size-4tw-animate-spin"}):"Add"))),Hu.default.createElement("div",{className:"tw-mt-1tw-text-xs"},u&&Hu.default.createElement("div",{className:"tw-p-1tw-text-muted"},"Loadingmodels..."),c&&Hu.default.createElement("div",{className:"tw-p-1tw-text-error"},"Failedtoloadmodels.",c),a&&a.length===0&&Hu.default.createElement("div",{className:"tw-p-1tw-text-muted"},"Nomodelsavailable."),a===null&&!u&&!c&&Hu.default.createElement("div",{className:"tw-p-1tw-text-muted"},"Clicktoloadavailablemodels."))))}Or();var L6=require("obsidian"),vr=$(J());function Pan(){let t=Br(),[e]=(0,vr.useState)(()=>BU.getInstance()),[r,n]=(0,vr.useState)("idle"),[o,i]=(0,vr.useState)(null),[a,s]=(0,vr.useState)(0),[u,l]=(0,vr.useState)(null),[c,d]=(0,vr.useState)(!1),f=(0,vr.useRef)(0),p=(0,vr.useRef)(!0);(0,vr.useEffect)(()=>(p.current=!0,()=>{p.current=!1,f.current+=1,e.abortPolling()}),[e]),(0,vr.useEffect)(()=>{e.getAuthState().status==="auth
`)}async function pCi(t,e){let r=[],n=t.provider?.trim()??"",o=jUe(n),i=t.baseUrl?.trim()??"",a=xz(i||o||"https://api.example.com/v1"),s=cCi(a),u=t.name?.trim()||"<MODEL_NAME>";t.name?.trim()||r.push("Model name is empty; using placeholder.");let l=await CQ(t.apiKey);r.push(...l.warnings);let c={"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer${l.apiKey}`};return t.openAIOrgId?.trim()&&(c["OpenAI-Organization"]=t.openAIOrgId.trim()),n==="openrouterai"&&(c["HTTP-Referer"]="https://obsidiancopilot.com",c["X-Title"]="Obsidian Copilot"),e?{ok:!0,warnings:r,spec:{method:"POST",url:`${s}/embeddings`,headers:c,body:{model:u,input:DUe}}}:{ok:!0,warnings:r,spec:{method:"POST",url:`${s}/chat/completions`,headers:c,body:{model:u,messages:[{role:"user",content:SQ}],stream:!1,max_tokens:Lan}}}}function mCi(t,e,r,n){let o=[],i=t.azureOpenAIApiInstanceName?.trim()||"[instance]";t.azureOpenAIApiInstanceName?.trim()||o.push("Azure instance name is empty; using placeholder.");let a=t.baseUrl?.trim();if(a){let s=lCi(a);if(s){let u=xz(s.pathname||"");u.includes("/openai/deployments/")&&(u=u.split("/openai/deployments/")[0]);let l=`${s.origin}${u}`;return{warnings:o,url:`${l}/openai/deployments/${encodeURIComponent(e)}/${r}?api-version=${encodeURIComponent(n)}`}}}return{warnings:o,url:`https://${i}.openai.azure.com/openai/deployments/${encodeURIComponent(e)}/${r}?api-version=${encodeURIComponent(n)}`}}async function hCi(t,e){let r=[],n=await CQ(t.apiKey);r.push(...n.warnings);let o=e?t.azureOpenAIApiEmbeddingDeploymentName?.trim()||"[deployment]":t.azureOpenAIApiDeploymentName?.trim()||"[deployment]";(!o||o==="[deployment]")&&r.push("Azure deployment name is empty; using placeholder.");let i=t.azureOpenAIApiVersion?.trim()||"[api-version]";t.azureOpenAIApiVersion?.trim()||r.push("Azure api-version is empty; using placeholder.");let s=mCi(t,o,e?"embeddings":"chat/completions",i);r.push(...s.warnings);let u=e?{input:DUe}:{messages:[{role:"user",content:SQ}],stream:!1,max_tokens:Lan};return{ok:!0,warnings:r,spec:{method:"POST",url:s.url,headers:{"Content-Type":"application/json",Accept:"application/json","api-key":n.apiKey},body:u}}}async function gCi(t){let e=[],r=t.baseUrl?.trim()??"",n=jUe("anthropic"),o=xz(r||n||"https://api.anthropic.com"),i=["/v1/messages","/v1"];for(let l of i)if(o.endsWith(l)){o=o.slice(0,-l.length);break}let a=`${o}/v1/messages`,s=await CQ(t.apiKey);e.push(...s.warnings);let u=t.name?.trim()||"<MODEL_NAME>";return t.name?.trim()||e.push("Model name is empty; using placeholder."),{ok:!0,warnings:e,spec:{method:"POST",url:a,headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":s.apiKey,"anthropic-version":nCi},body:{model:u,max_tokens:iCi,messages:[{role:"user",content:SQ}]}}}}async function yCi(t,e){let r=[],n=t.baseUrl?.trim()??"",o=jUe("google"),a=dCi(n||o||"https://generativelanguage.googleapis.com"),s=t.name?.trim()||"<MODEL_NAME>";t.name?.trim()||r.push("Model name is empty; using placeholder.");let u=s.includes("/")?s:`models/${s}`,l=await CQ(t.apiKey);r.push(...l.warnings);let c={"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":l.apiKey};return e?{ok:!0,warnings:r,spec:{method:"POST",url:`${a}/${u}:embedContent`,headers:c,body:{content:{parts:[{text:DUe}]}}}}:{ok:!0,warnings:r,spec:{method:"POST",url:`${a}/${u}:generateContent`,headers:c,body:{contents:[{role:"user",parts:[{text:SQ}]}],generationConfig:{maxOutputTokens:sCi}}}}}function bCi(t){return/(^|\.)anthropic\./.test(t)}async function _Ci(t){let e=[],r=t.name?.trim()||"<MODEL_ID>";t.name?.trim()||e.push("Model name is empty; using placeholder.");let n=t.bedrockRegion?.trim()||"us-east-1";t.bedrockRegion?.trim()||e.push("Bedrock region is empty; defaulting to us-east-1.");let o=t.baseUrl?.trim(),a=`${xz(o||`https://bedrock-runtime.${n}.amazonaws.com`)}/model/${encodeURIComponent(r)}/invoke`,s={messages:[{role:"user",content:[{type:"text",text:SQ}]}],max_tokens:aCi};bCi(r)?s.anthropic_version=oCi:e.push("Model ID does not look like Anthropic; request body may need adjust
`),warnings:e}}async function vCi(t,e){let r=[],n=t.baseUrl?.trim()??"",o=jUe("ollama"),i=fCi(xz(n||o||"http://localhost:11434")),a=t.name?.trim()||"<MODEL_NAME>";t.name?.trim()||r.push("Model name is empty; using placeholder.");let s={"Content-Type":"application/json",Accept:"application/json"};if(t.apiKey?.trim()){let l=await CQ(t.apiKey),c=l.warnings.filter(d=>!d.includes("API key is empty"));r.push(...c),s.Authorization=`Bearer${l.apiKey}`}return e?{ok:!0,warnings:r,spec:{method:"POST",url:`${i}/api/embed`,headers:s,body:{model:a,input:DUe,truncate:!0}}}:{ok:!0,warnings:r,spec:{method:"POST",url:`${i}/api/chat`,headers:s,body:{model:a,messages:[{role:"user",content:SQ}],stream:!1}}}}async function Fan(t){let e=[],r=t.provider?.trim();if(!r)return{ok:!1,error:"Provider is required to build a curl command.",warnings:e};let n=!!t.isEmbeddingModel;if(r==="azure openai"){let o=await hCi(t,n);return o.ok?{ok:!0,command:F6(o.spec),warnings:o.warnings}:o}if(r==="anthropic"){if(n)return{ok:!1,error:"Anthropic does not support embeddings.",warnings:e};let o=await gCi(t);return o.ok?{ok:!0,command:F6(o.spec),warnings:o.warnings}:o}if(r==="amazon-bedrock")return n?{ok:!1,error:"Bedrock embeddings are not supported by this generator.",warnings:e}:await _Ci(t);if(r==="google"||r==="google"){let o=await yCi(t,n);return o.ok?{ok:!0,command:F6(o.spec),warnings:o.warnings}:o}if(r==="ollama"||r==="ollama"){let o=await vCi(t,n);return o.ok?{ok:!0,command:F6(o.spec),warnings:o.warnings}:o}if(uCi.has(r)){let o=await pCi(t,n);return o.ok?{ok:!0,command:F6(o.spec),warnings:o.warnings}:o}return{ok:!1,error:`Provider"${r}"isnotsupportedforcurlgeneration.`,warnings:e}}Or();hF();var Tz=require("obsidian"),Ze=$(J()),y0t=({open:t,onOpenChange:e,onAdd:r,ping:n,isEmbeddingModel:o=!1})=>{let{modalContainer:i}=_z(),a=te(),s=o?"openai":"openrouterai",u=L=>L==="azure openai",[l,c]=(0,Ze.useState)(null),[d,f]=(0,Ze.useState)(u(s)),[p,m]=(0,Ze.useState)(!1),[h,y]=(0,Ze.useState)("idle"),[g,b]=(0,Ze.useState)({name:!1,instanceName:!1,deploymentName:!1,embeddingDeploymentName:!1,apiVersion:!1,displayName:!1,bedrockRegion:!1}),_=(L,W)=>{b(ie=>({...ie,[L]:W}))},w=()=>{b({name:!1,instanceName:!1,deploymentName:!1,embeddingDeploymentName:!1,apiVersion:!1,displayName:!1,bedrockRegion:!1})},T=()=>{let L=!0,W={...g};return W.name=!E.name,E.name||(L=!1),E.provider==="azure openai"&&(W.instanceName=!E.azureOpenAIApiInstanceName,W.apiVersion=!E.azureOpenAIApiVersion,o?(W.embeddingDeploymentName=!E.azureOpenAIApiEmbeddingDeploymentName,E.azureOpenAIApiEmbeddingDeploymentName||(L=!1)):(W.deploymentName=!E.azureOpenAIApiDeploymentName,E.azureOpenAIApiDeploymentName||(L=!1)),(!E.azureOpenAIApiInstanceName||!E.azureOpenAIApiVersion)&&(L=!1)),E.provider,"amazon-bedrock",W.bedrockRegion=!1,b(W),L},O=(L=s)=>{let W={name:"",provider:L,enabled:!0,isBuiltIn:!1,baseUrl:"",apiKey:Bb(L),isEmbeddingModel:o,capabilities:[]};if(!o){let ie={...W,stream:!0};return L==="amazon-bedrock"?{...ie,bedrockRegion:a.amazonBedrockRegion}:ie}return W},[E,P]=(0,Ze.useState)(O()),R=L=>{P(W=>({...W,...L})),y("idle")},I=L=>({...L,name:L.name?.trim(),baseUrl:L.baseUrl?.trim(),apiKey:L.apiKey?.trim(),openAIOrgId:L.openAIOrgId?.trim(),azureOpenAIApiInstanceName:L.azureOpenAIApiInstanceName?.trim(),azureOpenAIApiDeploymentName:L.azureOpenAIApiDeploymentName?.trim(),azureOpenAIApiEmbeddingDeploymentName:L.azureOpenAIApiEmbeddingDeploymentName?.trim(),azureOpenAIApiVersion:L.azureOpenAIApiVersion?.trim(),bedrockRegion:L.bedrockRegion?.trim()}),[N,z]=(0,Ze.useState)(d1(s)),V=()=>!!(E.name&&E.provider),k=()=>p||!V(),X=()=>{if(!T()){new Tz.Notice("Please fill in all required fields");return}let L=I(E);r(L),e(!1),P(O()),w(),y("idle"),f(!1)},B=L=>{z(d1(L)),y("idle"),P({...E,provider:L,apiKey:Bb(L),...L==="openai"?{openAIOrgId:a.openAIOrgId}:{},...L==="azure openai"?{azureOpenAIApiInstanceName:a.azureOpenAIApiInstanceName,azureOpenAIApiDeploymentName:a.azureOpenAIApiDeploymentName,azureOpenAIApiVersion:a.azureOpenAIApiVersion,azureOpenAIApiEmbeddingDeploymentName:a.azureOpenAIApiEmbeddingDeploymentName
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/text-cursor-input.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/trash-2.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/triangle-alert.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/wrench.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/x.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/zap-off.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/zap.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/lucide-react.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
safe-buffer/index.js:
(*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
@google/generative-ai/dist/index.mjs:
(**
* @license
* Copyright 2024 Google LLC
*
* 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