varUsn=Object.create;varMY=Object.defineProperty;varBsn=Object.getOwnPropertyDescriptor;varzsn=Object.getOwnPropertyNames;varVsn=Object.getPrototypeOf,Hsn=Object.prototype.hasOwnProperty;varIwt=t=>{throwTypeError(t)};varJsn=(t,e,r)=>eint?MY(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),Rn=(t,e)=>{for(varrine)MY(t,r,{get:e[r],enumerable:!0})},Rwt=(t,e,r,n)=>{if(e&&typeofe=="object"||typeofe=="function")for(letoofzsn(e))!Hsn.call(t,o)&&o!==r&&MY(t,o,{get:()=>e[o],enumerable:!(n=Bsn(e,o))||n.enumerable});returnt};varL=(t,e,r)=>(r=t!=null?Usn(Vsn(t)):{},Rwt(e||!t||!t.__esModule?MY(r,"default",{value:t,enumerable:!0}):r,t)),zfe=t=>Rwt(MY({},"__esModule",{value:!0}),t);varx=(t,e,r)=>Jsn(t,typeofe!="symbol"?e+"":e,r),Wsn=(t,e,r)=>e.has(t)||Iwt("Cannot "+r);varaqe=(t,e,r)=>e.has(t)?Iwt("Cannot add the same private member more than once"):einstanceofWeakSet?e.add(t):e.set(t,r);varAwt=(t,e,r)=>(Wsn(t,e,"access private method"),r);functionsqe(){if(!Vfe&&(Vfe=typeofcrypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Vfe))thrownewError("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");returnVfe(Ksn)}varVfe,Ksn,Nwt=v(()=>{Ksn=newUint8Array(16)});functionjwt(t,e=0){returnWh[t[e+0]]+Wh[t[e+1]]+Wh[t[e+2]]+Wh[t[e+3]]+"-"+Wh[t[e+4]]+Wh[t[e+5]]+"-"+Wh[t[e+6]]+Wh[t[e+7]]+"-"+Wh[t[e+8]]+Wh[t[e+9]]+"-"+Wh[t[e+10]]+Wh[t[e+11]]+Wh[t[e+12]]+Wh[t[e+13]]+Wh[t[e+14]]+Wh[t[e+15]]}varWh,Dwt=v(()=>{Wh=[];for(lett=0;t<256;++t)Wh.push((t+256).toString(16).slice(1))});varGsn,uqe,$wt=v(()=>{Gsn=typeofcrypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),uqe={randomUUID:Gsn}});functionXsn(t,e,r){if(uqe.randomUUID&&!e&&!t)returnuqe.randomUUID();t=t||{};letn=t.random||(t.rng||sqe)();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}returnjwt(n)}varZm,Lwt=v(()=>{$wt();Nwt();Dwt();Zm=Xsn});varD$=v(()=>{Lwt()});varZsn,Rt,Bo=v(()=>{Zsn=Object.defineProperty,Rt=(t,e)=>{for(varrine)Zsn(t,r,{get:e[r],enumerable:!0})}});functionIY(t,e=AB){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())}functionYsn(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}functionAB(t){try{returntypeoft>"u"?null:Ysn(t)}catch{returnnull}}varRY=v(()=>{});function$$(t,e){returnt.lc_error_code=e,t.message=`${t.message}
`,t}varAY=v(()=>{});varkwt=S((qbi,Fwt)=>{"use strict";Fwt.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()}});varJwt=S((Ubi,lqe)=>{"use strict";varQsn=/[\p{Lu}]/u,eun=/[\p{Ll}]/u,qwt=/^[\p{Lu}](?![\p{Lu}])/gu,zwt=/([\p{Alpha}\p{N}_]|$)/u,Vwt=/[_.\- ]+/,tun=newRegExp("^"+Vwt.source),Uwt=newRegExp(Vwt.source+zwt.source,"gu"),Bwt=newRegExp("\\d+"+zwt.source,"gu"),run=(t,e,r)=>{letn=!1,o=!1,i=!1;for(leta=0;a<t.length;a++){lets=t[a];n&&Qsn.test(s)?(t=t.slice(0,a)+"-"+t.slice(a),n=!1,i=o,o=!0,a++):o&&i&&eun.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},nun=(t,e)=>(qwt.lastIndex=0,t.replace(qwt,r=>e(r))),oun=(t,e)=>(Uwt.lastIndex=0,Bwt.lastIndex=0,t.replace(Uwt,(r,n)=>e(n)).replace(Bwt,r=>e(r))),Hwt=(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=run(t,r,n)),t=t.replace(tun,""),e.preserveConsecutiveUppercase?t=nun(t,r):t=r(t),e.pascalCase&&(t=n(t.charAt(0))+t.slice(1)),oun(t,n))};lqe.exports=Hwt;lqe.exports.default=Hwt});functionKwt(t,e){returne?.[t]||(0,Wwt.default)(t)}functionGwt(t,e,r){letn={};for(letoint)Object.hasOwn(t,o)&&(n[e(o,r)]=t[o]);returnn}varWwt,iun,Xwt=v(()=>{Wwt=L(kwt(),1),iun=L(Jwt(),1)});functionaun(t){return"lc"int||Object.keys(t).length===1&&Zwtint}functionsun(t){return{[Zwt]:t}}functionuun(t){returnt!==null&&typeoft=="object"&&"lc_serializable"int&&typeoft.toJSON=="function"}functionlun(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}}functionHfe(t,e=newWeakSet){if(t!==null&&typeoft=="object"&&!Array.isArray(t)){if(e.has(t))returnlun(t);if(uun(t))returnt;e.add(t);letr=t;if(aun(r))returne.delete(t),sun(r);letn={};for(let[o,i]ofObject.entries(r))n[o]=Hfe(i,e);returne.delete(t),n}returnArray.isArray(t)?t.map(r=>Hfe(r,e)):t}varZwt,Ywt=v(()=>{Zwt="__lc_escaped__"});functionQwt(t){returnArray.isArray(t)?[...t]:{...t}}functiondun(t,e){letr=Qwt(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]=Qwt(s[u]),s=s[u]}s[i]!==void0&&(s[i]={lc:1,type:"secret",id:[o]})}returnr}functionJfe(t){lete=Object.getPrototypeOf(t);returntypeoft.lc_name=="function"&&(typeofe.lc_name!="function"||t.lc_name()!==e.lc_name())?t.lc_name():t.name}varcun,Kh,L$=v(()=>{Bo();Xwt();Ywt();cun={};Rt(cun,{Serializable:()=>Kh,get_lc_unique_name:()=>Jfe});Kh=classeSt{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,Jfe(this.constructor)]}getlc_secrets(){}getlc_attributes(){}getlc_aliases(){}getlc_serializable_keys(){}toJSON(){if(!this.lc_serializable)returnthis.toJSONNotImplemented();if(this.lc_kwargsinstanceofeSt||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 Aw(t){if(typeof t=="string")return new Hs(t);if(Gh(t))return t;if(Array.isArray(t)){let[e,r]=t;return _qe({type:e,content:r})}else if(tpe(t)){let{role:e,...r}=t;return _qe({...r,type:e})}else return _qe(t)}function ol(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 Mun(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 BY(t){let e=Mun(t);switch(e.type){case"human":return new Hs(e.data);case"ai":return new eo(e.data);case"system":return new Qm(e.data);case"function":if(e.data.name===void 0)throw new Error("Name must be defined for function messages");return new jB(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 Wg(e.data);case"generic":if(e.data.role===void 0)throw new Error("Role must be defined for chat messages");return new nd(e.data);default:throw new Error(`Gotunexpectedtype:${e.type}`)}}function ZSt(t){return t.map(BY)}function YSt(t){return t.map(e=>e.toDict())}function $B(t){let e=t._getType();if(e==="human")return new mv({...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 Ir({...r})}else{if(e==="system")return new Wy({...t});if(e==="function")return new pv({...t});if(nd.isInstance(t))return new fv({...t});throw new Error("Unknown message type.")}}function spe(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=AB(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 upe,H0=v(()=>{Jg();G3();AY();Wfe();RY();kY();rpe();U$();npe();qY();Rw();upe=t=>t()});function wqe(){return vqe===void 0&&(vqe={library:"langchain-js",runtime:cpe()}),vqe}function vn(t){try{return typeof process<"u"?process.env?.[t]:lpe()?Deno?.env.get(t):void 0}catch{return}}var Iun,QSt,e0t,t0t,lpe,r0t,cpe,vqe,ku=v(()=>{Bo();Iun={};Rt(Iun,{getEnv:()=>cpe,getEnvironmentVariable:()=>vn,getRuntimeEnvironment:()=>wqe,isBrowser:()=>QSt,isDeno:()=>lpe,isJsDom:()=>t0t,isNode:()=>r0t,isWebWorker:()=>e0t});QSt=()=>typeof window<"u"&&typeof window.document<"u",e0t=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",t0t=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),lpe=()=>typeof Deno<"u",r0t=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!lpe(),cpe=()=>{let t;return QSt()?t="browser":r0t()?t="node":e0t()?t="webworker":t0t()?t="jsdom":lpe()?t="deno":t="other",t}});var n0t,o0t=v(()=>{n0t=/^(?:[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 Run(t){return typeof t=="string"&&n0t.test(t)}var Z3,i0t=v(()=>{o0t();Z3=Run});function fpe(t,e=0){return(Xh[t[e+0]]+Xh[t[e+1]]+Xh[t[e+2]]+Xh[t[e+3]]+"-"+Xh[t[e+4]]+Xh[t[e+5]]+"-"+Xh[t[e+6]]+Xh[t[e+7]]+"-"+Xh[t[e+8]]+Xh[t[e+9]]+"-"+Xh[t[e+10]]+Xh[t[e+11]]+Xh[t[e+12]]+Xh[t[e+13]]+Xh[t[e+14]]+Xh[t[e+15]]).toLowerCase()}var Xh,dpe,Sqe=v(()=>{Xh=[];for(dpe=0;dpe<256;++dpe)Xh.push((dpe+256).toString(16).slice(1))});function zY(){if(!ppe&&(ppe=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!ppe))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ppe(Aun)}var ppe,Aun,Cqe=v(()=>{Aun=new Uint8Array(16)});var Nun,xqe,a0t=v(()=>{Nun=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),xqe={randomUUID:Nun}});function jun(t,e,r){if(xqe.randomUUID&&!e&&!t)return xqe.randomUUID();t=t||{};var n=t.random||(t.rng||zY)();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=Ope(),r=dCt();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=SOt(i,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);r?.apiKey!==void0&&(n["x-api-key"]=r.apiKey),r?.workspaceId!==void0&&(n["x-tenant-id"]=r.workspaceId);lets=Hb(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});returnawaitLr(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(Hb(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});returnawaitLr(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){Po(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=Hb(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 Lr(s,"update run",!0),s})}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){Po(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:od("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 Rfn(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 M=Array.isArray(n)?n:[n],I=await Promise.all(M.map(j=>this.readProject({projectName:j}).then(A=>A.id)));w.push(...I)}let O=["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"],T={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||O,is_root:l,order:_};T.select.includes("child_run_ids")&&XY("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let P=0;for await(let M of this._getCursorPaginatedList("/runs/query",T))if(g){if(P>=g)break;if(M.length+P>g){yield*M.slice(0,g-P);break}P+=M.length,yield*M}else yield*M}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});returnawaitLr(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});returnawaitLr(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)Po(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});returnawaitLr(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)Po(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;Po(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 Lr(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;Po(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 Lr(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)Po(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 Lr(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),Po(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 Lr(u,"indexdataset"),u})).json()}async similarExamples(e,r,n,{filter:o}={}){let i={limit:n,inputs:e};o!==void 0&&(i.filter=o),Po(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 Lr(l,"fetchsimilarexamples"),l})).json()).examples}async createExample(e,r,n){if(OOt(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;OOt(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]??FB())}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]=HA(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 Lr(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]=HA(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 Lr(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=Hb(u,`Serializing body for example with id: ${s}`),c=new Blob([l],{type:"application/json"});if(n.append(s,c),a.inputs){let d=Hb(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=Hb(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=Hb(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 Lr(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??FB()).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=Hb(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=Hb(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=Hb(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 tme(t){return typeof t=="function"&&"langsmith:traceable"in t}var WUe,JUe,Kfn,KUe,Gfn,gCi,zOt=v(()=>{WUe=class{getStore(){}run(e,r){return r()}},JUe=Symbol.for("ls:tracing_async_local_storage"),Kfn=new WUe,KUe=class{getInstance(){return globalThis[JUe]??Kfn}initializeGlobalInstance(e){globalThis[JUe]===void 0&&(globalThis[JUe]=e)}},Gfn=new KUe;gCi=Symbol.for("langsmith:traceable:root")});var GUe=v(()=>{zOt()});function Zfn(t){let e;for(let r of t)for(let n of r)eo.isInstance(n.message)&&n.message.usage_metadata!==void 0&&(e=X3(e,n.message.usage_metadata));return e}var Xfn,lQ,HOt=v(()=>{Bo();ape();Rw();zB();HUe();GUe();Zpe();Qpe();Xfn={};Rt(Xfn,{LangChainTracer:()=>lQ});lQ=class VOt extends G0{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??GY(),this.replicas=a,this.exampleId=n,this.client=i??eme();let s=VOt.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=Zfn(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 K0({...n,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return BOt(!0)}catch{return}}}});var WOt=S((ICi,nme)=>{"usestrict";var Yfn=oUe(),rme=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},JOt=(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 rme(a);typeof t.cancel=="function"&&t.cancel(),o(s)},e);Yfn(t.then(n,o),()=>{clearTimeout(i)})});nme.exports=JOt;nme.exports.default=JOt;nme.exports.TimeoutError=rme});var KOt=S(XUe=>{"usestrict";Object.defineProperty(XUe,"__esModule",{value:!0});function Qfn(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}XUe.default=Qfn});var GOt=S(YUe=>{"usestrict";Object.defineProperty(YUe,"__esModule",{value:!0});var epn=KOt(),ZUe=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=epn.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}};YUe.default=ZUe});var tBe=S(eBe=>{"usestrict";Object.defineProperty(eBe,"__esModule",{value:!0});var tpn=nUe(),XOt=WOt(),rpn=GOt(),ome=()=>{},npn=new XOt.TimeoutError,QUe=class extends tpn{constructor(e){var r,n,o,i;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._reso
`)}var mpn,pme,mme=v(()=>{mpn=Object.prototype.hasOwnProperty;pme=class extends Error{constructor(t,e,r,n,o){super(uTt(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=uTt(t,{name:e,index:r,operation:n,tree:o})}}});function uBe(t){return Object.getOwnPropertyNames(Object.prototype).includes(t)}function hme(t,e){if(e=="")return t;var r={op:"_get",path:e};return KB(t,r),r.value}function KB(t,e,r=!1,n=!0,o=!0,i=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):gme(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=hme(t,e.from),e.op==="move"&&(a.removed=t),a;if(e.op==="test"){if(a.test=fQ(t,e.value),a.test===!1)throw new Sc("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 Sc("Operation`op`propertyisnotoneofoperationsdefinedinRFC-6902","OPERATION_OP_INVALID",i,e,t);return a}}else{n||(t=tb(t));let s=(e.path||"").split("/"),u=t,l=1,c=s.length,d,f,p;for(typeof r=="function"?p=r:p=gme;;){if(f=s[l],f&&f.indexOf("~")!=-1&&(f=fme(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&&!dme(f))throw new Sc("Expectedanunsignedbase-10integervalue,makingthenewreferencedvaluethearrayelementwiththezero-basedindex","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,t);dme(f)&&(f=~~f)}if(l>=c){if(r&&e.op==="add"&&f>u.length)throw new Sc("ThespecifiedindexMUSTNOTbegreaterthanthenumberofelementsinthearray","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);let m=gpn[e.op].call(e,u,f,t);if(m.test===!1)throw new Sc("Testoperationfailed","TEST_OPERATION_FAILED",i,e,t);return m}}else if(l>=c){let m=nW[e.op].call(e,u,f,t);if(m.test===!1)throw new Sc("Testoperationfailed","TEST_OPERATION_FAILED",i,e,t);return m}if(u=u[f],r&&l<c&&(!u||typeof u!="object"))throw new Sc("Cannotperformoperationatthedesiredpath","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function J$(t,e,r,n=!0,o=!0){if(r&&!Array.isArray(e))throw new Sc("Patchsequencemustbeanarray","SEQUENCE_NOT_AN_ARRAY");n||(t=tb(t));let i=new Array(e.length);for(let a=0,s=e.length;a<s;a++)i[a]=KB(t,e[a],r,!0,o,a),t=i[a].newDocument;return i.newDocument=t,i}function ypn(t,e,r){let n=KB(t,e);if(n.test===!1)throw new Sc("Testoperationfailed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function gme(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new Sc("Operationisnotanobject","OPERATION_NOT_AN_OBJECT",e,t,r);if(nW[t.op]){if(typeof t.path!="string")throw new Sc("Operation`path`propertyisnotastring","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new Sc('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 Sc("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 Sc("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")&&ume(t.value))throw new Sc("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.s
`)}var OTt,OQ,uW,IBe=v(()=>{iW();Ln();OTt=(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,_Be,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},OQ=Se("$ZodError",OTt),uW=Se("$ZodError",OTt,{Parent:Error})});var xme,aO,Ome,YB,Tme,RBe,Eme,ABe,Pme=v(()=>{iW();IBe();Ln();xme=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=>gv(u,i,ad())));throw Cme(s,o?.callee),s}return a.value},aO=xme(uW),Ome=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=>gv(u,i,ad())));throw Cme(s,o?.callee),s}return a.value},YB=Ome(uW),Tme=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??OQ)(i.issues.map(a=>gv(a,o,ad())))}:{success:!0,data:i.value}},RBe=Tme(uW),Eme=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=>gv(a,o,ad())))}:{success:!0,data:i.value}},ABe=Eme(uW)});var ez={};Rn(ez,{_emoji:()=>ETt,base64:()=>WBe,base64url:()=>Mme,bigint:()=>eze,boolean:()=>nze,browserEmail:()=>nmn,cidrv4:()=>HBe,cidrv6:()=>JBe,cuid:()=>NBe,cuid2:()=>jBe,date:()=>XBe,datetime:()=>YBe,domain:()=>omn,duration:()=>kBe,e164:()=>GBe,email:()=>UBe,emoji:()=>BBe,extendedDuration:()=>Xpn,guid:()=>qBe,hostname:()=>KBe,html5Email:()=>emn,integer:()=>tze,ipv4:()=>zBe,ipv6:()=>VBe,ksuid:()=>LBe,lowercase:()=>aze,nanoid:()=>FBe,null:()=>oze,number:()=>rze,rfc5322Email:()=>tmn,string:()=>QBe,time:()=>ZBe,ulid:()=>DBe,undefined:()=>ize,unicodeEmail:()=>rmn,uppercase:()=>sze,uuid:()=>QB,uuid4:()=>Zpn,uuid6:()=>Ypn,uuid7:()=>Qpn,xid:()=>$Be});function BBe(){return new RegExp(ETt,"u")}function MTt(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 ZBe(t){return new RegExp(`^${MTt(t)}$`)}function YBe(t){let e=MTt({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(`^${PTt}T(?:${n})$`)}var NBe,jBe,DBe,$Be,LBe,FBe,kBe,Xpn,qBe,QB,Zpn,Ypn,Qpn,UBe,emn,tmn,rmn,nmn,ETt,zBe,VBe,HBe,JBe,WBe,Mme,KBe,omn,GBe,PTt,XBe,QBe,eze,tze,rze,nze,oze,ize,aze,sze,Ime=v(()=>{NBe=/^[cC][^\s-]{8,}$/,jBe=/^[0-9a-z]+$/,DBe=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,$Be=/^[0-9a-vA-V]{20}$/,LBe=/^[A-Za-z0-9]{27}$/,FBe=/^[a-zA-Z0-9_-]{21}$/,kBe=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Xpn=/^[-+]?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)?)??$/,qBe=/^([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})$/,QB=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)$/,Zpn=QB(4),Ypn=QB(6),Qpn=QB(7),UBe=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,emn=/^[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])?)*$/,tmn=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]
`).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[${XB(b)}] = ${_}.value`)}f.write("payload.value=newResult;"),f.write("returnpayload;");let g=f.compile();return(b,_)=>g(d,b,_)},o,i=aW,a=!yQ.jitless,u=a&&SBe.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 O=_[w],T=O._zod.run({value:p[w],issues:[]},f),P=O._zod.optin==="optional"&&O._zod.optout==="optional";T instanceof Promise?m.push(T.then(M=>P?jTt(M,d,w,p):jme(M,d,w))):P?jTt(T,d,w,p):jme(T,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(O=>jme(O,d,_))):jme(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}});Fme=Se("$ZodUnion",(t,e)=>{no.init(t,e),ks(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ks(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ks(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),ks(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=>wQ(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=>DTt(a,r,t,n)):DTt(i,r,t,n)}}),c4e=Se("$ZodDiscriminatedUnion",(t,e)=>{Fme.init(t,e);let r=t._zod.parse;ks(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=vQ(()=>{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(!aW(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)}}),d4e=Se("$ZodIntersection",(t,e)=>{no.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])=>$Tt(r,u,l)):$Tt(r,i,a)}});rz=Se("$ZodTuple",(t,e)=>{no.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=>Dme(d,o,u))):Dme(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=>Dme(f,o,u))):Dme(d,o,u)}}return s.length?Promise.all(s).then(()=>o):o}});f4e=Se("$ZodRecord",(t,e)=>{no.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!sW(o))return r.issues.push
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 _Pt={};var vPt=v(()=>{});var QA={};Rn(QA,{$ZodAny:()=>a4e,$ZodArray:()=>RQ,$ZodAsyncError:()=>iO,$ZodBase64:()=>Xze,$ZodBase64URL:()=>Zze,$ZodBigInt:()=>Lme,$ZodBigIntFormat:()=>r4e,$ZodBoolean:()=>MQ,$ZodCIDRv4:()=>Wze,$ZodCIDRv6:()=>Kze,$ZodCUID:()=>$ze,$ZodCUID2:()=>Lze,$ZodCatch:()=>C4e,$ZodCheck:()=>oc,$ZodCheckBigIntFormat:()=>cze,$ZodCheckEndsWith:()=>Sze,$ZodCheckGreaterThan:()=>Ame,$ZodCheckIncludes:()=>vze,$ZodCheckLengthEquals:()=>gze,$ZodCheckLessThan:()=>Rme,$ZodCheckLowerCase:()=>bze,$ZodCheckMaxLength:()=>mze,$ZodCheckMaxSize:()=>dze,$ZodCheckMimeType:()=>xze,$ZodCheckMinLength:()=>hze,$ZodCheckMinSize:()=>fze,$ZodCheckMultipleOf:()=>uze,$ZodCheckNumberFormat:()=>lze,$ZodCheckOverwrite:()=>Oze,$ZodCheckProperty:()=>Cze,$ZodCheckRegex:()=>yze,$ZodCheckSizeEquals:()=>pze,$ZodCheckStartsWith:()=>wze,$ZodCheckStringFormat:()=>lW,$ZodCheckUpperCase:()=>_ze,$ZodCustom:()=>M4e,$ZodCustomStringFormat:()=>e4e,$ZodDate:()=>u4e,$ZodDefault:()=>_4e,$ZodDiscriminatedUnion:()=>c4e,$ZodE164:()=>Yze,$ZodEmail:()=>Aze,$ZodEmoji:()=>jze,$ZodEnum:()=>h4e,$ZodError:()=>OQ,$ZodFile:()=>y4e,$ZodFunction:()=>uhe,$ZodGUID:()=>Ize,$ZodIPv4:()=>Hze,$ZodIPv6:()=>Jze,$ZodISODate:()=>Bze,$ZodISODateTime:()=>Uze,$ZodISODuration:()=>Vze,$ZodISOTime:()=>zze,$ZodIntersection:()=>d4e,$ZodJWT:()=>Qze,$ZodKSUID:()=>qze,$ZodLazy:()=>P4e,$ZodLiteral:()=>g4e,$ZodMap:()=>p4e,$ZodNaN:()=>x4e,$ZodNanoID:()=>Dze,$ZodNever:()=>IQ,$ZodNonOptional:()=>w4e,$ZodNull:()=>i4e,$ZodNullable:()=>b4e,$ZodNumber:()=>$me,$ZodNumberFormat:()=>t4e,$ZodObject:()=>l4e,$ZodOptional:()=>cW,$ZodPipe:()=>NQ,$ZodPrefault:()=>v4e,$ZodPromise:()=>E4e,$ZodReadonly:()=>O4e,$ZodRealError:()=>uW,$ZodRecord:()=>f4e,$ZodRegistry:()=>dW,$ZodSet:()=>m4e,$ZodString:()=>tz,$ZodStringFormat:()=>Ou,$ZodSuccess:()=>S4e,$ZodSymbol:()=>n4e,$ZodTemplateLiteral:()=>T4e,$ZodTransform:()=>AQ,$ZodTuple:()=>rz,$ZodType:()=>no,$ZodULID:()=>Fze,$ZodURL:()=>Nze,$ZodUUID:()=>Rze,$ZodUndefined:()=>o4e,$ZodUnion:()=>Fme,$ZodUnknown:()=>K$,$ZodVoid:()=>s4e,$ZodXID:()=>kze,$brand:()=>gBe,$constructor:()=>Se,$input:()=>N4e,$output:()=>A4e,Doc:()=>PQ,JSONSchema:()=>_Pt,JSONSchemaGenerator:()=>ZQ,NEVER:()=>hBe,TimePrecision:()=>L4e,_any:()=>o2e,_array:()=>XQ,_base64:()=>ohe,_base64url:()=>ihe,_bigint:()=>Z4e,_boolean:()=>G4e,_catch:()=>uhn,_cidrv4:()=>rhe,_cidrv6:()=>nhe,_coercedBigint:()=>Y4e,_coercedBoolean:()=>X4e,_coercedDate:()=>s2e,_coercedNumber:()=>z4e,_coercedString:()=>$4e,_cuid:()=>Gme,_cuid2:()=>Xme,_custom:()=>g2e,_date:()=>a2e,_default:()=>ihn,_discriminatedUnion:()=>Kmn,_e164:()=>ahe,_email:()=>Ume,_emoji:()=>Wme,_endsWith:()=>VQ,_enum:()=>Qmn,_fil
`}}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:O,conditional:T}=b,P="";if(O!==void 0){let M=O,I=M.split(" ");I.length>u&&(M=Array.from({length:Math.ceil(I.length/u)},(j,A)=>I.slice(A*u,(A+1)*u).join(" ")).join(" <br> ")),P=T?`-. ${M} .->`:`-- ${M} -->`}else P=T?" -.-> ":" --> ";l+=`${T2e(_)}${P}${T2e(w)};
`}h&&!y&&(l+=`end
`)}p(c[""]??[],"");for(let m in c)!m.includes(":")&&m!==""&&p(c[m],m);return a&&(l+=yhn(i??{})),l}async function APt(t,e){let r=e?.backgroundColor??"white",n=e?.imageType??"png",o=xTt(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 ghn,NPt=v(()=>{Sme();ghn=["*","_","`"]});var DPt,jPt,$Pt,mhe=v(()=>{DPt=Symbol("LetzodToJsonSchemadecideonwhichparsertouse"),jPt={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"},$Pt=t=>typeof t=="string"?{...jPt,name:t}:{...jPt,...t}});var LPt,E2e=v(()=>{mhe();LPt=t=>{let e=$Pt(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 hhe,ghe=v(()=>{hhe=(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 Il(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?hhe(e,t.currentPath):e.join("/")}}var Uw=v(()=>{ghe()});function P2e(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function Vi(t,e,r,n,o){t[e]=r,P2e(t,e,n,o)}var tL=v(()=>{});var Mi,M2e,ar,sO,QQ=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})(Mi||(Mi={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(M2e||(M2e={}));ar=Mi.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 ar.undefined;case"string":return ar.string;case"number":return Number.isNaN(t)?ar.nan:ar.number;case"boolean":return ar.boolean;case"function":return ar.function;case"bigint":return ar.bigint;case"symbol":return ar.symbol;case"object":return Array.isArray(t)?ar.array:t===null?ar.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?ar.promise:typeof Map<"u"&&t instanceof Map?ar.map:typeof Set<"u"&&t instanceof Set?ar.set:typeof Date<"u"&&t instanceof Date?ar.date:ar.object;default:return ar.unknown}}});var nt,bhn,Gb,yhe=v(()=>{QQ();nt=Mi.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"]),bhn=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Gb=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.issues=
]`;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 H2e,Z0,Ign,Ehe=v(()=>{tL();Z0={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:()=>(H2e===void 0&&(H2e=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),H2e),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-_]*$/};Ign=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Phe(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===Ie.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:An(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Il(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:An(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===Ie.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=The(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===Ie.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===Ie.ZodBranded&&t.keyType._def.type._def.typeName===Ie.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=xhe(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var Mhe=v(()=>{Uw();Ohe();Ehe();sd();cO()});function uMt(t,e){if(e.mapStrategy==="record")return Phe(t,e);let r=An(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Il(e),n=An(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Il(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var W2e=v(()=>{Uw();Mhe();sd()});function lMt(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(We)}letrt=`${s}/$ref`,Fe=qu(t,Le,r,n,o,i,a,rt,u);if(Fe.valid||Ne.push({instanceLocation:a,keyword:"$ref",keywordLocation:rt,error:"A subschema had errors."},...Fe.errors),r==="4"||r==="7")return{valid:Ne.length===0,errors:Ne}}if(Array.isArray(m)){letst=m.length,Le=!1;for(letrt=0;rt<st;rt++)if(c===m[rt]||m[rt]==="integer"&&c==="number"&&t%1===0&&t===t){Le=!0;break}Le||Ne.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)&&Ne.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m}".`}):m!==void0&&c!==m&&Ne.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)||Ne.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):t!==h&&Ne.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),y!==void0&&(c==="object"||c==="array"?y.some(st=>dO(t,st))||Ne.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`}):y.some(st=>t===st)||Ne.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`})),b!==void0){letst=`${s}/not`;qu(t,b,r,n,o,i,a,st).valid&&Ne.push({instanceLocation:a,keyword:"not",keywordLocation:st,error:'Instance matched "not" schema.'})}letTr=[];if(_!==void0){letst=`${s}/anyOf`,Le=Ne.length,rt=!1;for(letFe=0;Fe<_.length;Fe++){letWe=_[Fe],ke=Object.create(u),Lt=qu(t,We,r,n,o,p===!0?i:null,a,`${st}/${Fe}`,ke);Ne.push(...Lt.errors),rt=rt||Lt.valid,Lt.valid&&Tr.push(ke)}rt?Ne.length=Le:Ne.splice(Le,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:st,error:"Instance does not match any subschemas."})}if(w!==void0){letst=`${s}/allOf`,Le=Ne.length,rt=!0;for(letFe=0;Fe<w.length;Fe++){letWe=w[Fe],ke=Object.create(u),Lt=qu(t,We,r,n,o,p===!0?i:null,a,`${st}/${Fe}`,ke);Ne.push(...Lt.errors),rt=rt&&Lt.valid,Lt.valid&&Tr.push(ke)}rt?Ne.length=Le:Ne.splice(Le,0,{instanceLocation:a,keyword:"allOf",keywordLocation:st,error:"Instance does not match every subschema."})}if(O!==void0){letst=`${s}/oneOf`,Le=Ne.length,rt=O.filter((Fe,We)=>{letke=Object.create(u),Lt=qu(t,Fe,r,n,o,p===!0?i:null,a,`${st}/${We}`,ke);returnNe.push(...Lt.errors),Lt.valid&&Tr.push(ke),Lt.valid}).length;rt===1?Ne.length=Le:Ne.splice(Le,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:st,error:`Instance does not match exactly one subschema (${rt} matches).`})}if((c==="object"||c==="array")&&Object.assign(u,...Tr),T!==void0){letst=`${s}/if`;if(qu(t,T,r,n,o,i,a,st,u).valid){if(P!==void0){letrt=qu(t,P,r,n,o,i,a,`${s}/then`,u);rt.valid||Ne.push({instanceLocation:a,keyword:"if",keywordLocation:st,error:'Instance does not match "then" schema.'},...rt.errors)}}elseif(M!==void0){letrt=qu(t,M,r,n,o,i,a,`${s}/else`,u);rt.valid||Ne.push({instanceLocation:a,keyword:"if",keywordLocation:st,error:'Instance does not match "else" schema.'},...rt.errors)}}if(c==="object"){if(g!==void0)for(letFeofg)Feint||Ne.push({instanceLocation:a,keyword:"required",keywordLocation:`${s}/required`,error:`Instance does not have required property "${Fe}".`});letst=Object.keys(t);if(q!==void0&&st.length<q&&Ne.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${q} properties.`}),J!==void0&&st.length>J&&Ne.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${J} properties.`}),K!==void0){letFe=`${s}/propertyNames`;for(letWeint){letke=`${a}/${yv(We)}`,Lt=qu(We,K,r,n,o,i,ke,Fe);Lt.valid||Ne.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:Fe,error:`Property name "${We}" does not
`)),n.close()}});returnQy.fromReadableStream(r)}varkMt=v(()=>{nO()});functionhVe(t){returntypeoft=="object"&&t!==null&&typeoft[Symbol.iterator]=="function"&&typeoft.next=="function"}function$he(t){returntypeoft=="object"&&t!==null&&typeoft[Symbol.asyncIterator]=="function"}function*gVe(t,e){for(;;){let{value:r,done:n}=eh.runWithConfig(Yy(t),e.next.bind(e),!0);if(n)break;yieldr}}asyncfunction*Lhe(t,e){letr=e[Symbol.asyncIterator]();for(;;){let{value:n,done:o}=awaiteh.runWithConfig(Yy(t),r.next.bind(e),!0);if(o)break;yieldn}}varqMt,UMt=v(()=>{HB();JB();rO();qMt=t=>t!=null&&typeoft=="object"&&"next"int&&typeoft.next=="function"});functionud(t,e){returnt&&!Array.isArray(t)&&!(tinstanceofDate)&&typeoft=="object"?t:{[e]:t}}functionvyn(t){if(tme(t))thrownewError("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}functionbv(t){if(typeoft=="function")returnnewYb({func:t});if(Vo.isRunnable(t))returnt;if(!Array.isArray(t)&&typeoft=="object"){lete={};for(let[r,n]ofObject.entries(t))e[r]=bv(n);returnnewaL({steps:e})}elsethrownewError(`Expected a Runnable, function or object.
Instead got an unsupported type.`)}functionwyn(t,e){letr=e.name??t.getName(),n=e.description??eL(e.schema);returngW(e.schema)?newFhe({name:r,description:n,schema:Ct.object({input:Ct.string()}).transform(o=>o.input),bound:t}):newFhe({name:r,description:n,schema:e.schema,bound:t})}varVo,Hw,zMt,khe,Rl,aL,_yn,Yb,KMt,yVe,aee,bVe,Fhe,Qh=v(()=>{L$();Wfe();HB();JB();rO();rW();nO();pTt();bTt();pBe();GB();STt();Sme();eN();LMt();kMt();UMt();cO();HY();GUe();Vo=classextendsKh{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){returnnewkhe({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){returnnewHw({bound:this,config:e,kwargs:{}})}withFallbacks(e){letr=Array.isArray(e)?e:e.fallbacks;returnnewyVe({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(Qo);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)=>Qo(i===0?e:n))}returnArray.from({length:r},()=>Qo(e))}asyncbatch(e,r,n){leto=this._getOptionsList(r??{},e.length),i=o[0]?.maxConcurrency??n?.maxConcurrency,a=newFw({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=Qo(r),o=newH$({generator:this._streamIterator(e,n),config:n});returnawaito.setup,Qy.fromAsyncGenerator(o)}_separateRunnableConfigFromCallOptions(e){letr;e===void0?r=Qo(e):r=Qo({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=Qo(n),a=await(awaitZg(o))?.handleChainStart(this.toJSON(),ud(r,"input"),o.runId,o?.runType,void0,void0,o?.runName??this.getName());deleteo.runId;lets;try{letu=e.call(this,r,o,a);s=await$w(u,n?.signal)}catch(u){throwawaita?.handleChainError(u),u}returnawaita?.handleChainEnd(ud(s,"output")),s}async_batchWithConfig(e,r,n,o){leti=this._getOptionsList(n??{},r.length),a=awaitPromise.all(i.map(Zg)),s=awaitPromise.all(a.map(async(l,c)=>{letd=awaitl?.handleChainStart(this.toJSON(),ud(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=await$w(l,i?.[0]?.signal)}catch(l){throwawaitPromise.all(s.map(c=>c?.handleChainError(l))),l}returnawaitPromise.all(s.map(l=>l?.handleChainEnd(ud(u,"output")))),u}_concatOutputChunks(e,r){returneb(e,r)}async*_transformStreamWithConfig(e,r,n){leto,i=!0,a,s=!0,u=Qo(n),l=awaitZg(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=awaitsBe(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(gTt),h=p.output;m!==void0&&f!==void0&&(h=m.tapOutputIterable(f.runId,h));lety=f?.handlers.find(fBe);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(Cyn(s))}}return e}function iIt(t,e){if(Array.isArray(t)){let r=t;if(!e)throw new Error("Options parameter is required when providing messages.");return tIt(r,e)}else{let r=t;return Yb.from(n=>tIt(n,r)).withConfig({runName:"trim_messages"})}}async function tIt(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=vVe;if(l&&("splitText"in l?d=l.splitText:d=async f=>l(f)),o==="first")return aIt(t,{maxTokens:r,tokenCounter:c,textSplitter:d,partialStrategy:i?"first":void 0,endOn:a});if(o==="last")return Syn(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 aIt(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=_Ve(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&&!Uhe(s[u-1],l);)u-=1}return s.slice(0,u)}async function Syn(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 _Ve(c.getType(),d,K3(c))});if(o){let c=Array.isArray(o)?o:[o];for(;s.length>0&&!Uhe(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 aIt(l,{...a,partialStrategy:r?"last":void 0,endOn:i}),u?[l[0],...l.slice(1).reverse()]:l.reverse()}function _Ve(t,e,r){let n,o;switch(t){case"human":r?n=new mv(e):o=new Hs(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 Ir(i)}else o=new eo(e);break;case"system":r?n=new Wy(e):o=new Qm(e);break;case"developer":r?n=new Wy({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}}):o=new Qm({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in e)r?n=new Iw(e):o=new Wg(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 pv(e);else{if(!e.name)throw new Error("FunctionMessage must have a 'name' field");o=new jB(e)}break;case"generic":if("role"in e)r?n=new fv(e):o=new nd(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 Cyn(t){let e=t.getType(),r,n=Object.fromEntries(Object.entries(t
`),e[e.length-1]])}varUhe,rIt,sIt=v(()=>{Jg();G3();kY();rpe();U$();npe();qY();H0();Rw();Qh();Uhe=(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)};rIt={human:{message:Hs,messageChunk:mv},ai:{message:eo,messageChunk:Ir},system:{message:Qm,messageChunk:Wy},developer:{message:Qm,messageChunk:Wy},tool:{message:Wg,messageChunk:Iw},function:{message:jB,messageChunk:pv},generic:{message:nd,messageChunk:fv},remove:{message:DB,messageChunk:DB}}});varuIt,lIt=v(()=>{uIt=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"]});varcIt,dIt=v(()=>{cIt=["image","video","audio","text-plain","file"]});varfIt,pIt=v(()=>{lIt();dIt();fIt=["text","reasoning",...uIt,...cIt]});varxyn,Qa=v(()=>{Bo();DY();mqe();Jg();ape();G3();kY();rpe();U$();npe();qY();H0();Rw();sIt();pIt();xyn={};Rt(xyn,{AIMessage:()=>eo,AIMessageChunk:()=>Ir,BaseMessage:()=>Uc,BaseMessageChunk:()=>Jy,ChatMessage:()=>nd,ChatMessageChunk:()=>fv,FunctionMessage:()=>jB,FunctionMessageChunk:()=>pv,HumanMessage:()=>Hs,HumanMessageChunk:()=>mv,KNOWN_BLOCK_TYPES:()=>fIt,RemoveMessage:()=>DB,SystemMessage:()=>Qm,SystemMessageChunk:()=>Wy,ToolMessage:()=>Wg,ToolMessageChunk:()=>Iw,_isMessageFieldWithRole:()=>tpe,_mergeDicts:()=>El,_mergeLists:()=>NB,_mergeObj:()=>epe,_mergeStatus:()=>Qfe,coerceMessageLikeToMessage:()=>Aw,collapseToolCallChunks:()=>spe,convertToChunk:()=>$B,convertToOpenAIImageBlock:()=>Gfe,convertToProviderContentBlock:()=>Zx,defaultTextSplitter:()=>vVe,defaultToolCallParser:()=>LY,filterMessages:()=>nIt,getBufferString:()=>ol,iife:()=>upe,isAIMessage:()=>Pl,isAIMessageChunk:()=>UY,isBase64ContentBlock:()=>W3,isBaseMessage:()=>Gh,isBaseMessageChunk:()=>K3,isChatMessage:()=>vSt,isChatMessageChunk:()=>wSt,isDataContentBlock:()=>Ym,isDirectToolOutput:()=>$Y,isFunctionMessage:()=>SSt,isFunctionMessageChunk:()=>CSt,isHumanMessage:()=>xSt,isHumanMessageChunk:()=>OSt,isIDContentBlock:()=>Kfe,isMessage:()=>Yfe,isOpenAIToolCallArray:()=>ySt,isPlainTextContentBlock:()=>oSt,isSystemMessage:()=>TSt,isSystemMessageChunk:()=>ESt,isToolMessage:()=>FY,isToolMessageChunk:()=>gqe,isURLContentBlock:()=>J3,mapChatMessagesToStoredMessages:()=>YSt,mapStoredMessageToChatMessage:()=>BY,mapStoredMessagesToChatMessages:()=>ZSt,mergeContent:()=>Hg,mergeMessageRuns:()=>oIt,mergeResponseMetadata:()=>ipe,mergeUsageMetadata:()=>X3,parseBase64DataUrl:()=>zg,parseMimeType:()=>jY,trimMessages:()=>iIt})});varmIt,hIt=v(()=>{Jg();U$();Rw();Qh();Qa();qhe();mIt=classextendsHw{constructor(e){letr=Yb.from((a,s)=>this._enterHistory(a,s??{})).withConfig({runName:"loadHistory"}),n=e.historyMessagesKey??e.inputMessagesKey;n&&(r=Eu.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)&&!Gh(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[newHs(r)];if(Array.isArray(r))returnr;if(Gh(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)&&!Gh(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[neweo(r)];if(Array.isArray(r))returnr;if(Gh(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}}});varOyn,_v=v(()=>{Bo();rO();rW();Qh();qhe();XMt();YMt();hIt();Oyn={};Rt(Oyn,{RouterRunnable:()=>GMt,Runnable:()=>Vo,RunnableAssign:()=>aee,RunnableBinding:()=>Hw,RunnableBranch:()=>ZMt,RunnableEach:()=>zMt,RunnableLambda:()=>Yb,RunnableMap:()=>aL,RunnableParallel:()=>KMt,RunnablePassthrough:()=>Eu,RunnablePick:()=>bVe,RunnableRetry:()=>khe,RunnableSequence:()=>Rl,RunnableToolLike:()=>Fhe,RunnableWithFallbacks:()=>yVe,RunnableWithMessageHistory:()=>mIt,_coerceToRunnable:()=>bv,ensureConfig:()=>Qo,getCallbackManagerForConfig:()=>Zg,mergeConfigs:()=>WB,patchConfig:()=>Js,pickRunnableConfigKeys:()=>Yy,raceWithSignal:()=>$w})});varSz,iN,th,TW=v(()=>{AY();Qh();_v();Sz=classextendsVo{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"})}},iN=classextendsSz{parseResult(t,e){returnthis.parse(t[0].text,e)}asyncparseWithPrompt(t,e,r){returnthis.parse(t,r)}_type(){thrownewError("_type not implemented")}},th=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");$$(this,"OUTPUT_PARSING_FAILURE")}}});varaN,sL,uL=v(()=>{Jg();H0();id();TW();jhe();aN=classextendsiN{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"})}},sL=classextendsaN{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(K3(o)){if(typeofo.content!="string")thrownewError("Cannot handle non-string message output.");i=newyi({message:o,text:o.content})}elseif(Gh(o)){if(typeofo.content!="string")thrownewError("Cannot handle non-string message output.");i=newyi({message:$B(o),text:o.content})}elsei=newLw({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""}}});vargIt,yIt=v(()=>{uL();gIt=classextendsaN{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""}}});varEW,bIt,_It,vIt,wIt,SIt=v(()=>{TW();uL();EW=classextendsaN{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]}},bIt=classextendsEW{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{thrownewth(`Could not pa
3. baz`}asyncparse(e){return[...e.matchAll(this.re)??[]].map(r=>r[1])}},wIt=classextendsEW{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])}}});varBhe,CIt=v(()=>{uL();Bhe=classextendsaN{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),"")}}});varJw,wVe,xIt,OIt=v(()=>{eN();nb();TW();cO();Jw=classextendsiN{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=Ct.object(Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Ct.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,"");returnawaitQ$(this.schema,JSON.parse(o))}catch(r){thrownewth(`Failed to parse. Text: "${e}". Error: ${r}`,e)}}},wVe=classextendsJw{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:
`?(R.line++,R.column=0):R.column++);R.textNode+=D.substring(ee,z-1)}U==="<"&&!(R.sawRoot&&R.closedRoot&&!R.strict)?(R.state=M.OPEN_WAKA,R.startTagPosition=R.position):(!_(U)&&(!R.sawRoot||R.closedRoot)&&K(R,"Text data outside of root node."),U==="&"?R.state=M.TEXT_ENTITY:R.textNode+=U);continue;case M.SCRIPT:U==="<"?R.state=M.SCRIPT_ENDING:R.script+=U;continue;case M.SCRIPT_ENDING:U==="/"?R.state=M.CLOSE_TAG:(R.script+="<"+U,R.state=M.SCRIPT);continue;case M.OPEN_WAKA:if(U==="!")R.state=M.SGML_DECL,R.sgmlDecl="";else if(!_(U))if(T(h,U))R.state=M.OPEN_TAG,R.tagName=U;else if(U==="/")R.state=M.CLOSE_TAG,R.tagName="";else if(U==="?")R.state=M.PROC_INST,R.procInstName=R.procInstBody="";else{if(K(R,"Unencoded <"),R.startTagPosition+1<R.position){var ce=R.position-R.startTagPosition;U=new Array(ce).join(" ")+U}R.textNode+="<"+U,R.state=M.TEXT}continue;case M.SGML_DECL:(R.sgmlDecl+U).toUpperCase()===c?(A(R,"onopencdata"),R.state=M.CDATA,R.sgmlDecl="",R.cdata=""):R.sgmlDecl+U==="--"?(R.state=M.COMMENT,R.comment="",R.sgmlDecl=""):(R.sgmlDecl+U).toUpperCase()===d?(R.state=M.DOCTYPE,(R.doctype||R.sawRoot)&&K(R,"Inappropriately located doctype declaration"),R.doctype="",R.sgmlDecl=""):U===">"?(A(R,"onsgmldeclaration",R.sgmlDecl),R.sgmlDecl="",R.state=M.TEXT):(w(U)&&(R.state=M.SGML_DECL_QUOTED),R.sgmlDecl+=U);continue;case M.SGML_DECL_QUOTED:U===R.q&&(R.state=M.SGML_DECL,R.q=""),R.sgmlDecl+=U;continue;case M.DOCTYPE:U===">"?(R.state=M.TEXT,A(R,"ondoctype",R.doctype),R.doctype=!0):(R.doctype+=U,U==="["?R.state=M.DOCTYPE_DTD:w(U)&&(R.state=M.DOCTYPE_QUOTED,R.q=U));continue;case M.DOCTYPE_QUOTED:R.doctype+=U,U===R.q&&(R.q="",R.state=M.DOCTYPE);continue;case M.DOCTYPE_DTD:R.doctype+=U,U==="]"?R.state=M.DOCTYPE:w(U)&&(R.state=M.DOCTYPE_DTD_QUOTED,R.q=U);continue;case M.DOCTYPE_DTD_QUOTED:R.doctype+=U,U===R.q&&(R.state=M.DOCTYPE_DTD,R.q="");continue;case M.COMMENT:U==="-"?R.state=M.COMMENT_ENDING:R.comment+=U;continue;case M.COMMENT_ENDING:U==="-"?(R.state=M.COMMENT_ENDED,R.comment=V(R.opt,R.comment),R.comment&&A(R,"oncomment",R.comment),R.comment=""):(R.comment+="-"+U,R.state=M.COMMENT);continue;case M.COMMENT_ENDED:U!==">"?(K(R,"Malformed comment"),R.comment+="--"+U,R.state=M.COMMENT):R.state=M.TEXT;continue;case M.CDATA:U==="]"?R.state=M.CDATA_ENDING:R.cdata+=U;continue;case M.CDATA_ENDING:U==="]"?R.state=M.CDATA_ENDING_2:(R.cdata+="]"+U,R.state=M.CDATA);continue;case M.CDATA_ENDING_2:U===">"?(R.cdata&&A(R,"oncdata",R.cdata),A(R,"onclosecdata"),R.cdata="",R.state=M.TEXT):U==="]"?R.cdata+="]":(R.cdata+="]]"+U,R.state=M.CDATA);continue;case M.PROC_INST:U==="?"?R.state=M.PROC_INST_ENDING:_(U)?R.state=M.PROC_INST_BODY:R.procInstName+=U;continue;case M.PROC_INST_BODY:if(!R.procInstBody&&_(U))continue;U==="?"?R.state=M.PROC_INST_ENDING:R.procInstBody+=U;continue;case M.PROC_INST_ENDING:U===">"?(A(R,"onprocessinginstruction",{name:R.procInstName,body:R.procInstBody}),R.procInstName=R.procInstBody="",R.state=M.TEXT):(R.procInstBody+="?"+U,R.state=M.PROC_INST_BODY);continue;case M.OPEN_TAG:T(y,U)?R.tagName+=U:(ue(R),U===">"?Y(R):U==="/"?R.state=M.OPEN_TAG_SLASH:(_(U)||K(R,"Invalid character in tag name"),R.state=M.ATTRIB));continue;case M.OPEN_TAG_SLASH:U===">"?(Y(R,!0),se(R)):(K(R,"Forward-slash in opening tag not followed by >"),R.state=M.ATTRIB);continue;case M.ATTRIB:if(_(U))continue;U===">"?Y(R):U==="/"?R.state=M.OPEN_TAG_SLASH:T(h,U)?(R.attribName=U,R.attribValue="",R.state=M.ATTRIB_NAME):K(R,"Invalid attribute name");continue;case M.ATTRIB_NAME:U==="="?R.state=M.ATTRIB_VALUE:U===">"?(K(R,"Attribute without value"),R.attribValue=R.attribName,G(R),Y(R)):_(U)?R.state=M.ATTRIB_NAME_SAW_WHITE:T(y,U)?R.attribName+=U:K(R,"Invalid attribute name");continue;case M.ATTRIB_NAME_SAW_WHITE:if(U==="=")R.state=M.ATTRIB_VALUE;else{if(_(U))continue;K(R,"Attribute without value"),R.tag.attributes[R.attribName]="",R.attribValue="",A(R,"onattribute",{name:R.attribName,value:""}),R.attribName="",U===">"?Y(R):T(h,U)?(R.attribName=U,R.state=M.ATTRIB_NAME):(K(R,"Invalid attribute name"),R.state=M.ATTRIB)}continue;case M.ATTRIB_VALUE:if(_(U))continue;w(U)?(R.q=U
`).trim(),MIt=t=>{if(Object.keys(t).length===0)return{};lete={};returnt.children.length>0?(e[t.name]=t.children.map(MIt),e):(e[t.name]=t.text??void0,e)}});varMyn,fO=v(()=>{Bo();RY();TW();uL();yIt();SIt();CIt();OIt();CVe();IIt();Myn={};Rt(Myn,{AsymmetricStructuredOutputParser:()=>xIt,BaseCumulativeTransformOutputParser:()=>sL,BaseLLMOutputParser:()=>Sz,BaseOutputParser:()=>iN,BaseTransformOutputParser:()=>aN,BytesOutputParser:()=>gIt,CommaSeparatedListOutputParser:()=>bIt,CustomListOutputParser:()=>_It,JsonMarkdownStructuredOutputParser:()=>wVe,JsonOutputParser:()=>vv,ListOutputParser:()=>EW,MarkdownListOutputParser:()=>wIt,NumberedListOutputParser:()=>vIt,OutputParserException:()=>th,StringOutputParser:()=>Bhe,StructuredOutputParser:()=>Jw,XMLOutputParser:()=>PIt,XML_FORMAT_INSTRUCTIONS:()=>zhe,parseJsonMarkdown:()=>IY,parsePartialJson:()=>AB,parseXMLMarkdown:()=>Vhe})});varWw,PW=v(()=>{Qh();Ww=classextendsVo{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"})}}});varIyn,Hhe,see,uee,xVe,lee=v(()=>{Bo();L$();U$();H0();Iyn={};Rt(Iyn,{BasePromptValue:()=>Hhe,ChatPromptValue:()=>uee,ImagePromptValue:()=>xVe,StringPromptValue:()=>see});Hhe=classextendsKh{},see=classextendsHhe{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[newHs(this.value)]}},uee=classextendsHhe{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(){returnol(this.messages)}toChatMessages(){returnthis.messages}},xVe=classextendsHhe{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[newHs({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}}});varsN,cee=v(()=>{lee();PW();sN=classextendsWw{asyncformatPromptValue(t){lete=awaitthis.format(t);returnnewsee(e)}}});functionTVe(t){returntypeoft=="function"}functionAyn(t){returnIW(t)?"array":typeoft}functionOVe(t){returnt.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}functionRIt(t,e){returnt!=null&&typeoft=="object"&&eint}functionNyn(t,e){returnt!=null&&typeoft!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}functionDyn(t,e){returnjyn.call(t,e)}functionLyn(t){return!Dyn($yn,t)}functionkyn(t){returnString(t).replace(/[&<>"'`=\/]/g,function(r){returnFyn[r]})}functionVyn(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(M){if(typeofM=="string"&&(M=M.split(Uyn,2)),!IW(M)||M.length!==2)thrownewError("Invalid tags: "+M);d=newRegExp(OVe(M[0])+"\\s*"),f=newRegExp("\\s*"+OVe(M[1])),p=newRegExp("\\s*"+OVe("}"+M[1]))}m(e||Kw.tags);for(varh=newfee(t),y,g,b,_,w,O;!h.eos();){if(y=h.pos,b=h.scanUntil(d),b)for(varT=0,P=b.length;T<P;++T)_=b.cha
`&&(c(),u="",l=0,r=!1);if(!h.scan(d))break;if(a=!0,g=h.scan(zyn)||"name",h.scan(qyn),g==="="?(b=h.scanUntil(AIt),h.scan(AIt),h.scanUntil(f)):g==="{"?(b=h.scanUntil(p),h.scan(Byn),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(O=n.pop(),!O)throw new Error('Unopened section "'+b+'" at '+y);if(O[1]!==b)throw new Error('Unclosed section "'+O[1]+'" at '+y)}else g==="name"||g==="{"||g==="&"?s=!0:g==="="&&m(b)}if(c(),O=n.pop(),O)throw new Error('Unclosed section "'+O[1]+'" at '+h.pos);return Jyn(Hyn(o))}function Hyn(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 Jyn(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 fee(t){this.string=t,this.tail=t,this.pos=0}function MW(t,e){this.view=t,this.cache={".":this.view},this.parent=e}function ob(){this.templateCache={_cache:{},set:function(e,r){this._cache[e]=r},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}var Ryn,IW,jyn,$yn,Fyn,qyn,Uyn,AIt,Byn,zyn,Kw,dee,Jhe,NIt=v(()=>{Ryn=Object.prototype.toString,IW=Array.isArray||function(e){return Ryn.call(e)==="[object Array]"};jyn=RegExp.prototype.test;$yn=/\S/;Fyn={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};qyn=/\s*/,Uyn=/\s+/,AIt=/\s*=/,Byn=/\s*\}/,zyn=/#|\^|\/|>|\{|&|=|!/;fee.prototype.eos=function(){return this.tail===""};fee.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};fee.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};MW.prototype.push=function(e){return new MW(e,this)};MW.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=RIt(i,a[s])||Nyn(i,a[s])),i=i[a[s++]];else i=o.view[e],u=RIt(o.view,e);if(u){n=i;break}o=o.parent}r[e]=n}return TVe(n)&&(n=n.call(this.view)),n};ob.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};ob.prototype.parse=function(e,r){var n=this.templateCache,o=e+":"+(r||Kw.tags).join(":"),i=typeof n<"u",a=i?n.get(o):void 0;return a==null&&(a=Vyn(e,r),i&&n.set(o,a)),a};ob.prototype.render=function(e,r,n,o){var i=this.getConfigTags(o),a=this.parse(e,i),s=r instanceof MW?r:new MW(r,void 0);return this.renderTokens(a,s,n,e,o)};ob.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};ob.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(IW(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(TVe(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}};ob.prototype.renderInverted=function(e,r,n,o,i){var a=r.lookup(e[1]);if(!a||IW(a)&&a.length===0)return this.renderTokens(e[4],r,n,o,i)};ob.prototype.indentPartial=function(e,r,n){for(var o=r.replace(/[^ \t]/g,""),i=e.split(`
`)};ob.prototype.renderPartial=function(e,r,n,o){if(n){var i=this.getConfigTags(o),a=TVe(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)}}};ob.prototype.unescapedValue=function(e,r){var n=r.lookup(e[1]);if(n!=null)return n};ob.prototype.escapedValue=function(e,r,n){var o=this.getConfigEscape(n)||Kw.escape,i=r.lookup(e[1]);if(i!=null)return typeof i=="number"&&o===Kw.escape?String(i):o(i)};ob.prototype.rawValue=function(e){return e[1]};ob.prototype.getConfigTags=function(e){return IW(e)?e:e&&typeof e=="object"?e.tags:void 0};ob.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!IW(e))return e.escape};Kw={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){dee.templateCache=t},get templateCache(){return dee.templateCache}},dee=new ob;Kw.clearCache=function(){return dee.clearCache()};Kw.parse=function(e,r){return dee.parse(e,r)};Kw.render=function(e,r,n,o){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+Ayn(e)+'" was given as the first argument for mustache#render(template, view, partials)');return dee.render(e,r,n,o)};Kw.escape=kyn;Kw.Scanner=fee;Kw.Context=MW;Kw.Writer=ob;Jhe=Kw});function jIt(){Jhe.escape=t=>t}var Cz,DIt,RW,EVe,PVe,pee,MVe,ey,xz,uN,Oz=v(()=>{AY();NIt();Cz=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},DIt=(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=DIt(n[4],o);r.push(...i)}}else r.push({type:"literal",text:n[1]});return r},RW=t=>{jIt();let e=Jhe.parse(t);return DIt(e)},EVe=(t,e)=>Cz(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},""),PVe=(t,e)=>(jIt(),Jhe.render(t,e)),pee={"f-string":EVe,mustache:PVe},MVe={"f-string":Cz,mustache:RW},ey=(t,e,r)=>{try{return pee[e](t,r)}catch(n){throw $$(n,"INVALID_PROMPT_INPUT")}},xz=(t,e)=>MVe[e](t),uN=(t,e,r)=>{if(!(e in pee)){let n=Object.keys(pee);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")ey(o.text,e,n);else if(o.type==="image_url"){if(typeof o.image_url=="string")ey(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;ey(i,e,n)}}else throw new Error(`Invalid message template received. ${JSON.stringify(o,null,2)}`)}):ey(t,e,n)}catch(n){throw new Error(`Invalid prompt schema: ${n.message}`)}}});var lu,Whe=v(()=>{cee();Oz();lu=class mee extends sN{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))),uN(this.template,this.templateFormat,n)}}static lc_name(){return"PromptTemplate"}_getPromptType(){return"prompt"}async format(r){let n=await this.mergePartialAndUserVariables(r);return ey(this.template,this.templateFormat,n)}static fromExamples(r,n,o,i=`
From:${i}`);s=[l[0]]}else s=[];i={url:i},a=new AW({template:i,inputVariables:s,templateFormat:r?.templateFormat,additionalContentFields:o})}else if(typeof i=="object"){if("url"in i){let u;r?.templateFormat==="mustache"?u=RW(i.url):u=Cz(i.url),s=u.flatMap(l=>l.type==="variable"?[l.name]:[])}else s=[];a=new AW({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 hee({template:o,templateFormat:r?.templateFormat}));return new this({prompt:n,additionalOptions:r})}async format(e){if(this.prompt instanceof sN){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 sN){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 AW){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 hee){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)]}},Qb=class extends $Ve{static _messageClass(){return Hs}static lc_name(){return"HumanMessagePromptTemplate"}},Ghe=class extends $Ve{static _messageClass(){return eo}static lc_name(){return"AIMessagePromptTemplate"}},Gw=class extends $Ve{static _messageClass(){return Qm}static lc_name(){return"SystemMessagePromptTemplate"}};ld=class Khe extends yee{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 Uc))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=awaitlu.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(iinstanceofUc)o.push(awaitthis._parseImagePrompts(i,n));else{leta;this.templateFormat==="mustache"?a={...n}:a=i.inputVariables.reduce((u,l)=>{if(!(linn)&&!(Zyn(i)&&i.optional))throw$$(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};returnnewKhe(i)}staticfromTemplate(r,n){leto=lu.fromTemplate(r,n),i=newQb({prompt:o});returnthis.fromMessages([i])}staticfromMessages(r,n){leto=r.reduce((s,u)=>s.concat(uinstanceofKhe?u.promptMessages:[Xyn(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))),uN(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 LVe(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 ey(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 lu.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 LVe({inputVariables:r.input_variables,examplePrompt:o,examples:i,exampleSeparator:r.example_separator,prefix:r.prefix,suffix:r.suffix,templateFormat:r.template_format})}},FIt=class kIt extends yee{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))),uN(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 ey(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 kIt(i)}}});var UIt,BIt=v(()=>{PW();bee();UIt=class Xhe extends Ww{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=Xhe.extractRequiredInputValues(n,i.inputVariables);i instanceof ld?n[o]=await i.formatMessages(a):n[o]=await i.format(a)}return Xhe.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 Xhe(n)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}}});function zIt(t){return typeof t=="object"&&t!=null&&"withStructuredOutput"in t&&typeof t.withStructuredOutput=="function"}function Yyn(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 VIt,JIt=v(()=>{Qh();bee();VIt=class HIt extends ld{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(zIt(r))return super.pipe(r.withStructuredOutput(this.schema));if(Yyn(r)&&zIt(r.bound))return super.pipe(new Hw({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 HIt.fromMessages(r,{schema:n,method:o})}}});var Q
`)});functionCc(t,e){letr=`atom${++rbn}`,n={toString(){return(Al.env?Al.env.MODE:void0)!=="production"&&this.debugLabel?r+":"+this.debugLabel:r}};returntypeoft=="function"?n.read=t:(n.init=t,n.read=nbn,n.write=obn),e&&(n.write=e),n}functionnbn(t){returnt(this)}functionobn(t,e,r){returne(this,typeofr=="function"?r(t(this)):r)}varAl,rbn,WIt,kVe,qVe,Qhe,BVe,ibn,abn,zVe,KIt,Yhe,ZIt,GIt,jW,UVe,sbn,ubn,XIt,lL,YIt,cL,vee,QIt,VVe=v(()=>{Al={},rbn=0;WIt=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,kVe=t=>"init"int,qVe=t=>!!t.write,Qhe=newWeakMap,BVe=t=>{vare;returnzVe(t)&&!((e=Qhe.get(t))!=null&&e[1])},ibn=(t,e)=>{letr=Qhe.get(t);if(r)r[1]=!0,r[0].forEach(n=>n(e));elseif((Al.env?Al.env.MODE:void0)!=="production")thrownewError("[Bug] cancelable promise not found")},abn=t=>{if(Qhe.has(t))return;lete=[newSet,!1];Qhe.set(t,e);letr=()=>{e[1]=!0};t.then(r,r),t.onCancel=n=>{e[0].add(n)}},zVe=t=>typeoft?.then=="function",KIt=t=>"v"int||"e"int,Yhe=t=>{if("e"int)throwt.e;if((Al.env?Al.env.MODE:void0)!=="production"&&!("v"int))thrownewError("[Bug] atom state is not initialized");returnt.v},ZIt=(t,e,r)=>{r.p.has(t)||(r.p.add(t),e.then(()=>{r.p.delete(t)},()=>{r.p.delete(t)}))},GIt=(t,e,r,n,o)=>{vari;if((Al.env?Al.env.MODE:void0)!=="production"&&n===e)thrownewError("[Bug] atom cannot depend on itself");r.d.set(n,o.n),BVe(r.v)&&ZIt(e,r.v,o),(i=o.m)==null||i.t.add(e),t&&sbn(t,n,e)},jW=()=>[newMap,newMap,newSet],UVe=(t,e,r)=>{t[0].has(e)||t[0].set(e,newSet),t[1].set(e,r)},sbn=(t,e,r)=>{letn=t[0].get(e);n&&n.add(r)},ubn=(t,e)=>t[0].get(e),XIt=(t,e)=>{t[2].add(e)},lL=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},YIt=(...[t,e,r,n])=>{leto;(Al.env?Al.env.MODE:void0)!=="production"&&(o=newSet);leti=(_,w,O)=>{letT="v"inw,P=w.v,M=BVe(w.v)?w.v:null;if(zVe(O)){abn(O);for(letIofw.d.keys())ZIt(_,O,t(I));w.v=O,deletew.e}elsew.v=O,deletew.e;(!T||!Object.is(P,w.v))&&(++w.n,M&&ibn(M,O))},a=(_,w,O)=>{varT;letP=t(w);if(KIt(P)&&(P.m&&!O?.has(w)||Array.from(P.d).every(([V,q])=>a(_,V,O).n===q)))returnP;P.d.clear();letM=!0,I=V=>{if(WIt(w,V)){letJ=t(V);if(!KIt(J))if(kVe(V))i(V,J,V.init);elsethrownewError("no atom init");returnYhe(J)}letq=a(_,V,O);try{returnYhe(q)}finally{if(M)GIt(_,w,P,V,q);else{letJ=jW();GIt(J,w,P,V,q),p(J,w,P),lL(J)}}},j,A,k={getsignal(){returnj||(j=newAbortController),j.signal},getsetSelf(){return(Al.env?Al.env.MODE:void0)!=="production"&&!qVe(w)&&console.warn("setSelf function cannot be used with read-only atom"),!A&&qVe(w)&&(A=(...V)=>{if((Al.env?Al.env.MODE:void0)!=="production"&&M&&console.warn("setSelf function cannot be called in sync"),!M)returnf(w,...V)}),A}};try{letV=e(w,I,k);if(i(w,P,V),zVe(V)){(T=V.onCancel)==null||T.call(V,()=>j?.abort());letq=()=>{if(P.m){letJ=jW();p(J,w,P),lL(J)}};V.then(q,q)}returnP}catch(V){returndeleteP.v,P.e=V,++P.n,P}finally{M=!1}},s=_=>Yhe(a(void0,_)),u=(_,w,O)=>{varT,P;letM=newMap;for(letIof((T=O.m)==null?void0:T.t)||[])M.set(I,t(I));for(letIofO.p)M.set(I,t(I));return(P=ubn(_,w))==null||P.forEach(I=>{M.set(I,t(I))}),M};functionl(_,w,O){letT=[],P=newSet,M=newSet,I=[[w,O]];for(;I.length>0;){let[j,A]=I[I.length-1];if(M.has(j)){I.pop();continue}if(P.has(j)){T.push([j,A,A.n]),M.add(j),I.pop();continue}P.add(j);for(let[k,V]ofu(_,j,A))j!==k&&!P.has(k)&&I.push([k,V])}return[T,M]}letc=(_,w,O)=>{let[T,P]=l(_,w,O),M=newSet([w]);for(letI=T.length-1;I>=0;--I){let[j,A,k]=T[I],V=!1;for(letqofA.d.keys())if(q!==j&&M.has(q)){V=!0;break}V&&(a(_,j,P),p(_,j,A),k!==A.n&&(UVe(_,j,A),M.add(j))),P.delete(j)}},d=(_,w,...O)=>{letT=!0,P=I=>Yhe(a(_,I)),M=(I,...j)=>{letA=t(I);try{if(WIt(w,I)){if(!kVe(I))thrownewError("atom not writable");letk=A.n,V=j[0];i(I,A,V),p(_,I,A),k!==A.n&&(UVe(_,I,A),c(_,I,A));return}elsereturnd(_,I,...j)}finally{T||lL(_)}};try{returnr(w,P,M,...O)}finally{T=!1}},f=(_,...w)=>{letO=jW();try{returnd
`)||o.startsWith("\r")?o.slice(1):o}}returnt}functionyO(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(qW(a)))}returnn&&(Array.isArray(n)?n.forEach(i=>{typeofi=="string"&&o.add(qW(i))}):typeofn=="string"&&o.add(qW(n))),Array.from(o)}functionsge(t,e,r){if(e.length===0)return[];e=e.map(i=>qW(i));letn=r&&r.length>0?r:Eee(t,"/"),o=[];for(letiofn){leta=yO(i);e.some(s=>a.includes(s))&&o.push(i)}returno}asyncfunctionxc(t){lete=(0,ry.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(iinstanceofry.TFile)thrownewError(`Path conflict: "${n}" exists as a file, expected folder.`);continue}awaitapp.vault.adapter.mkdir(n)}}asyncfunctionBW(t,e){returnt.extension!="md"&&t.extension!="canvas"?null:awaite.cachedRead(t)}functionuge(t){returnt.basename}functionbO(t){returnt?Dbn.includes(t.extension):!1}functionsb(t){returnt==="copilot_plus"||t==="project"}functionzW(t,e){returnt?t.extension==="md"||t.extension==="canvas"?!0:sb(e):!1}functionERt(t,e){return!t||!e?!1:t.includes(iHe)&&e.includes(iHe)||t==="small"&&e==="cohereai"||t==="cohereai"&&e==="small"?!0:t===e}functionlge(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}functionPRt(t,e){letr=newMap;returnt.forEach(n=>{leto=e.getAbstractFileByPath(n);if(oinstanceofry.TFile)r.set(o.path,o);else{leta=e.getMarkdownFiles().filter(s=>s.basename===n);a.length>0&&($bn(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())}functionmL(t,e){letr=/\[\[(.*?)\]\]/g,n=t.match(r);if(!n)return[];leto=n.map(i=>i.slice(2,-2));returnPRt(o,e)}functionMRt(t,e){letr=/\{\[\[(.*?)\]\]\}/g,n=t.match(r);if(!n)return[];leto=n.map(i=>i.slice(3,-3));returnPRt(o,e)}function$bn(t,e){returne.getMarkdownFiles().filter(n=>n.basename===t).length===1}functionIRt(t){returnt=t.trim(),t.startsWith("[[")&&t.endsWith("]]")?`${t.slice(2,-2).trim()}.md`:t}functionRRt(t){lete=newSet;returnt.forEach(r=>{r.metadata?.title&&e.add(r.metadata?.title)}),Array.from(e)}functionaHe(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=sHe(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"}}functionsHe(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}}functionARt(t){return`https://www.youtube.com/watch?v=${t}`}functionNRt(t){returnaHe(t).isValid}functionjRt(t){lete=t.matchAll(newRegExp(Lbn,"g"));returnArray.from(e,r=>r[0])}asyncfunctionNl(t,e={}){letr=newHeaders(e.headers),n=Object.fromEntries(r.entries());deleten["content-length"],B("safeFetch request");leto=e.method?.toUpperCase()||"POST",a=await(0,ry.requestUrl)({url:t,contentType:"application/json",headers:n,method:o,...["POST","PUT","PATCH"].includes(o)&&{body:e.body?.toString()},throw:!1});if(a.status>=400){lets;try{s=typeofa.json=="string"?JSON.parse(a.json):a.json}catch{try{s=typeofa.text=="string"?JSON.parse(a.text):a.text}catch{s=null}}letu=newError(oHe.REQUEST_FAILED(a.status));if(u.json=s,s?.detail?.reason==="Invalid license key"||s?.reason==="Invalid license key")u.message="Invalid license key";elseif(s?.detail?.message||s?.message){letl=s?.detail?.message||s?.message,c=s?.detail?.reason||s?.reason;u.message=c?`${l}: ${c}`:l}elses?.detail?u.message=JSON.stringify(s.detail):s&&(u.message+=". "+JSON.stringify(s));throwu}return{ok:a.status>=200&&a.status<300,status:a
`),e=e.trim(),e}async function Mz(t,e=!1){let r=app.workspace.getMostRecentLeaf();if(!r){new ry.Notice("No active leaf found.");return}if(r.view instanceof ry.MarkdownView||(r=app.workspace.getLeaf(!1),await r.setViewState({type:"markdown",state:r.view.getState()})),!(r.view instanceof ry.MarkdownView)){new ry.Notice("Failed to open a markdown view.");return}let n=r.view.editor,o=n.getCursor("from"),i=n.getCursor("to"),a=cge(t);e?n.replaceRange(a,o,i):n.replaceRange(a,i),new ry.Notice("Message inserted into the active note.")}function dge(t,e){let r;return(...n)=>{clearTimeout(r),r=setTimeout(()=>t(...n),e)}}function fge(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 DRt(){try{return{version:(await(0,ry.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 Mee(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 kbn(t){return typeof t=="string"?t.startsWith("gpt-5"):(t.modelName||t.model||"").startsWith("gpt-5")}function VW(t){let e=typeof t=="string"?t:t.modelName||t.model||"",r=Mee(e),n=kbn(e),o=e.startsWith("claude-3-7-sonnet")||e.startsWith("claude-sonnet-4");return{isOSeries:r,isGPT5:n,isThinkingEnabled:o}}function Iz(t,e="system"){return Mee(t)?"human":e}function uHe(){let t=["3rd party (openai-format)","ollama","lm-studio","azure openai","github-copilot","copilot-plus","copilot-plus-jina"];return Object.keys(rC).filter(e=>!t.includes(e))}function HW(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=!!uHe().find(o=>o===t.provider),n=!ab(t.provider,t);return r&&n?{hasApiKey:!1,errorNotice:`PleaseconfigureAPIKeyfor${t.name}insettingsfirst.
Path:Settings>copilotplugin>BasicTab>SetKeys`}:{hasApiKey:!0}}function Rz(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>e.text).join(""):String(t||"")}function Az(t){let r=Rz(t).replace(/<think>[\s\S]*?<\/think>/g,"");return r=r.replace(/<think>[\s\S]*$/g,""),r.trim()}function JW(t){return Rz(t).replace(/<errorChunk>[\s\S]*?<\/errorChunk>/g,"").trim()}function $Rt(){return crypto.randomUUID()}async function rh(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 pge(t,e,r="Operation"){let{TimeoutError:n}=await Promise.resolve().then(()=>(Xw(),SRt)),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 lHe(){let t=app.workspace.getActiveViewOfType(ry.MarkdownView);return t?t.getState().source===!0:!0}function Iee(t){return new TextEncoder().encode(t).length}function cHe(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}async function LRt(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 CRt,ry,oHe,Eee,Nbn,jbn,TRt,eg,Dbn,Lbn,Zt=v(()=>{Bc();Or();_t();CRt=L(vRt()),ry=require("obsidian");pL();tHe();oHe={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}`};Eee=(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})};Nbn=t=>t.last?.modelName||t.last?.model,jbn=t=>t.last?.retriever!==void 0,TRt=t=>Nbn(t)||jbn(t),eg=(t,e="local")=>{let r=(0,CRt.default)(t);return e==="utc"&&r.utc(),{fileName:r.format("YYYYMMDD_HHmmss"),display:r.format("YYYY/MM/DD HH:mm:ss"),epoch:r.valueOf()}};Dbn=["md","pdf","canvas"];Lbn=/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|shorts\/)|youtu\.be\/)([^\s&]+)/});var WW,dHe,Ree,Bc=v(()=>{fO();wv();_v();FVe();Zt();WW=class WW{static createNewLLMChain(e){let{llm:r,memory:n,prompt:o,abortController:i}=e,a=r.withConfig({signal:i?.signal}),s=Rl.from([{input:u=>u.input,memory:()=>n.loadMemoryVariables({})},{input:u=>u.input,history:u=>u.memory.history},o,a]);return WW.instances.set("llm_chain",s),console.log("New LLM chain created."),s}static getLLMChainFromMap(e){let r=WW.instances.get("llm_chain");return r||(r=WW.createNewLLMChain(e)),r}static createConversationalRetrievalChain(e,r,n){let{llm:o,retriever:i,systemMessage:a}=e,u=lu.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.`,qRt=`Return the new note content or canvas JSON in <writeToFile> tags.
`,Nee="note_context",n_="selected_text",pHe="web_selected_text",jee="variable",Nz="variable_note",Dee="embedded_pdf",mHe="embedded_note",$ee="dataview_block",hHe="retrieved_document",gHe="web_tab_context",mge="active_web_tab",yHe="youtube_video_context",Lee="{activeWebTab}",jz=6e3,bHe=.4,_He=448e3,KW=3e4,Sv={DEFAULT:"",READING_FILES:"Reading files",SEARCHING_WEB:"Searching the web",READING_FILE_TREE:"Reading file tree",COMPACTING:"Compacting"},pN={SETTINGS:"settings",EXPIRED_MODAL:"expired_modal",CHAT_MODE_SELECT:"chat_mode_select",MODE_SELECT_TOOLTIP:"mode_select_tooltip"},ub={MAX_TOKENS:6e3,TEMPERATURE:.1,REASONING_EFFORT:"low",VERBOSITY:"medium"},r_=(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))(r_||{}),hL={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-2.5-flash-lite",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"google/gemini-2.5-flash",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"google/gemini-2.5-pro",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"openai/gpt-4.1",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"openai/gpt-4.1-mini",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"grok-4-fast",provider:"xai",enabled:!0,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"x-ai/grok-4-fast",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-5",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"gpt-5-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"gpt-4.1",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-4.1-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"claude-sonnet-4-20250514",provider:"anthropic",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-flash-lite",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gemini-2.5-pro",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"azure-openai",provider:"azure openai",enabled:!0,isBuiltIn:!0},{name:"deepseek-chat",provider:"deepseek",enabled:!0,isBuiltIn:!0},{name:"deepseek-reasoner",provider:"deepseek",enabled:!0,isBuiltIn:!0,capabilities:["reasoning"]},{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"]}],gO=(d=>(d.OPENAI="openai",d.OPENROUTERAI="openrouterai",d.COHEREAI="cohereai",d.GOOGLE="google",d.AZURE_OPENAI="azure openai",d.OLLAMA="ollama",d.LM_STUDIO="lm-studio",d.OPENAI_FORMAT="3rd party (openai-format)",d.COPILOT_PLUS="copilot-plus",d.COPILOT_PLUS_JINA="copilot-plus-jina",d.SILICONFLOW="siliconflow",d))(gO||{}),Tz=[{name:"copilot-plus-small",provider:"copilot-plus",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,plusExclusive:!0},{name:
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")return$v(i);if(o==="hex")return$Ht(i);if(o===void0||o==="utf8"||o==="utf-8")returny_e(i);if(typeofTextDecoder=="function")returnnewTextDecoder(o).decode(i);thrownewError("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(e)thrownewError(FHt);if(e=!0,kHt(t))returnn(t);if(YWe(t))returnt;thrownewError(`Cannot transform payload to web stream, got ${t}`)}})},kHt=t=>typeofBlob=="function"&&tinstanceofBlob});varBHt=v(()=>{});varr6e=v(()=>{cHt();dHt();pHt();mHt();hHt();gHt();UHt();BHt()});varkN,n6e=v(()=>{r6e();kN=async(t=newUint8Array,e)=>{if(tinstanceofUint8Array)returnW6.mutate(t);if(!t)returnW6.mutate(newUint8Array);letr=e.streamCollector(t);returnW6.mutate(awaitr)}});functiono6e(t){returnencodeURIComponent(t).replace(/[!'()*]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}varzHt=v(()=>{});varnF,i6e=v(()=>{nF=t=>typeoft=="function"?t():t});var__e,v_e=v(()=>{__e=(t,e,r,n,o)=>({name:e,namespace:t,traits:r,input:n,output:o})});varVHt,HHt,a6e,JHt=v(()=>{lre();VHt=L(pS());v_e();HHt=t=>(e,r)=>asyncn=>{let{response:o}=awaite(n),{operationSchema:i}=(0,VHt.getSmithyContext)(r),[,a,s,u,l,c]=i??[];try{letd=awaitt.protocol.deserializeResponse(__e(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(J6.isInstance(o)){let{headers:p={}}=o,m=Object.entries(p);d.$metadata={httpStatusCode:o.statusCode,requestId:a6e(/^x-[\w-]+-request-?id$/,m),extendedRequestId:a6e(/^x-[\w-]+-id-2$/,m),cfId:a6e(/^x-[\w-]+-cf-id$/,m)}}}catch{}}throwd}},a6e=(t,e)=>(e.find(([r])=>r.match(t))||[void0,void0])[1]});varWHt,KHt,GHt=v(()=>{WHt=L(pS());v_e();KHt=t=>(e,r)=>asyncn=>{let{operationSchema:o}=(0,WHt.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(__e(i,a,s,u,l),n.input,{...t,...r,endpoint:c});returne({...n,request:d})}});functionw_e(t){return{applyToStack:e=>{e.add(KHt(t),_xn),e.add(HHt(t),bxn),t.protocol.setSerdeContext(t)}}}varbxn,_xn,XHt=v(()=>{JHt();GHt();bxn={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},_xn={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});varmS,g4=v(()=>{mS=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}}});varS_e,ZHt,YHt=v(()=>{g4();S_e=classS_eextendsmS{constructor(){super(...arguments);x(this,"name");x(this,"traits");x(this,"valueSchema");x(this,"symbol",S_e.symbol)}};x(S_e,"symbol",Symbol.for("@smithy/lis"));ZHt=S_e});varC_e,QHt,eJt=v(()=>{g4();C_e=classC_eextendsmS{constructor(){super(...arguments);x(this,"name");x(this,"traits");x(this,"keySchema");x(this,"valueSchema");x(this,"symbol",C_e.symbol)}};x(C_e,"symbol",Symbol.for("@smithy/map"));QHt=C_e});varx_e,tJt,rJt=v(()=>{g4();x_e=classx_eextendsmS{constructor(){super(...arguments);x(this,"name");x(this,"traits");x(this,"input");x(this,"output");x(this,"symbol",x_e.symbol)}};x(x_e,"symbol",Symbol.for("@smithy/ope"));tJt=x_e});varT_e,O_e,s6e=v(()=>{g4();T_e=classT_eextendsmS{constructor(){super(...arguments);x(this,"name");x(this,"traits");x(this,"memberNames");x(this,"memberList");x(this,"symbol",T_e.symbol)}};x(T_e,"symbol",Symbol.for("@smithy/str"));O_e=T_e});varE_e,nJt,oJt=v(()=>{s6e();E_e=classE_eextendsO_e{constructor(){super(...arguments);x(this,"ctor");x(this,"symbol",E_e.symbol)}};x(E_e,"symbol",Symbol.for("@smithy/err"));nJt=E_e});functiony4(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}varu6e=v(()=>{});functionpre(t,e){if(tinstanceofYi)returnObject.assign(t,{memberName:e,_isMemberSchema:!0});letr=Yi;returnnewr(t,e)}varoF,Yi,l6e,vxn,iJt=v(()=>{i6e();u6e();oF=classoF{constructor(e,r){x(this,"ref");x(this,"memberName");x(this,"symbol",oF.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;l6e(o);)n.push(o[1]),o=o[0],i=nF(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,y4(s))}}elsethis.memberTraits=0;if(iinstanceofoF){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=nF(i),vxn(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"
`),Txn={warn:console.warn}});function I_e(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`${Exn[n]},${u}${p6e[r]}${e}${l}:${c}:${d}GMT`}var Exn,p6e,Pxn,bJt,Mxn,_Jt,Ixn,Rxn,Axn,vJt,wJt,mre,Nxn,jxn,Dxn,f6e,$xn,Lxn,Fxn,XO,kxn,qxn,X6,SJt=v(()=>{d6e();Exn=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],p6e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];Pxn=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),bJt=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=Pxn.exec(t);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");let[r,n,o,i,a,s,u,l]=e,c=G6(X6(n)),d=XO(o,"month",1,12),f=XO(i,"day",1,31);return mre(c,d,f,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l})},Mxn=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),_Jt=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=Mxn.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=G6(X6(n)),f=XO(o,"month",1,12),p=XO(i,"day",1,31),m=mre(d,f,p,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l});return c.toUpperCase()!="Z"&&m.setTime(m.getTime()-qxn(c)),m},Ixn=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$/),Rxn=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$/),Axn=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})$/),vJt=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-7231 date-times must be expressed as strings");let e=Ixn.exec(t);if(e){let[r,n,o,i,a,s,u,l]=e;return mre(G6(X6(i)),f6e(o),XO(n,"day",1,31),{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l})}if(e=Rxn.exec(t),e){let[r,n,o,i,a,s,u,l]=e;return Dxn(mre(Nxn(i),f6e(o),XO(n,"day",1,31),{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l}))}if(e=Axn.exec(t),e){let[r,n,o,i,a,s,u,l]=e;return mre(G6(X6(l)),f6e(n),XO(o.trimLeft(),"day",1,31),{hours:i,minutes:a,seconds:s,fractionalMilliseconds:u})}throw new TypeError("Invalid RFC-7231 date-time value")},wJt=t=>{if(t==null)return;let e;if(typeof t=="number")e=t;else if(typeof t=="string")e=hJt(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))},mre=(t,e,r,n)=>{let o=e-1;return Lxn(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),kxn(n.fractionalMilliseconds)))},Nxn=t=>{let e=new Date().getUTCFullYear(),r=Math.floor(e/100)*100+G6(X6(t));return r<e?r+100:r},jxn=50*365*24*60*60*1e3,Dxn=t=>t.getTime()-new Date().getTime()>jxn?new Date(Date.UTC(t.getUTCFullYear()-100,t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds(),t.getUTCMilliseconds())):t,f6e=t=>{let e=p6e.indexOf(t);if(e<0)throw new TypeError(`Invalidmonth:${t}`);return e+1},$xn=[31,28,31,30,31,30,31,31,30,31,30,31],Lxn=(t,e,r)=>{let n=$xn[e];if(e===1&&Fxn(t)&&(n=29),r>n)throw new TypeError(`Invaliddayfor${p6e[e]}in${t}:${r}`)},Fxn=t=>t%4===0&&(t%100!==0||t%400===0),XO=(t,e,r,n)=>{let o=yJt(X6(t));if(o<r||o>n)throw new TypeError(`${e}mustbebetween${r}and${n},inclusive`);return o},kxn=t=>t==null?0:gJt("0."+t)*1e3,qxn=t=>{let e=t[0],r=1;if(e=="+")r=1;else if(e=="-")r=-1;else throw new Typ
${bS(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,V6t.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=B6t(e).replace(/[\-:]/g,"");return{longDate:r,shortDate:r.slice(0,8)}}getCanonicalHeaderList(e){returnObject.keys(e).sort().join(";")}}});varCre,J6t=v(()=>{o5();cF();dF();J6e();P6t();R6t();j6t();$6t();F6t();k6t();H6t();Cre=classextendsrve{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",neweve)}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>O6t)returnPromise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");lety=Y_e(h,p,d??this.service),g=L6t(G6e(r),{unhoistableHeaders:s,hoistableHeaders:l});f.sessionToken&&(g.query[U6e]=f.sessionToken),g.query[f6t]=X_e,g.query[p6t]=`${f.accessKeyId}/${y}`,g.query[k6e]=m,g.query[h6t]=i.toString(10);letb=W6e(g,a,u);returng.query[m6t]=this.getCanonicalHeaderList(b),g.query[q6e]=awaitthis.getSignature(m,y,this.getSigningKey(f,p,h,d),this.createCanonicalRequest(g,b,awaitQ_e(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=Y_e(l,u,s??this.service),f=awaitQ_e({headers:{},body:n},this.sha256),p=newthis.sha256;p.update(r);letm=bS(awaitp.digest()),h=[S6t,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(zN(r)),bS(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=G6e(r),{longDate:d,shortDate:f}=this.formatDate(n),p=Y_e(f,l,s??this.service);c.headers[z6e]=d,u.sessionToken&&(c.headers[b6t]=u.sessionToken);letm=awaitQ_e(c,this.sha256);!D6t(Sre,c.headers)&&this.applyChecksum&&(c.headers[Sre]=m);leth=W6e(c,i,o),y=awaitthis.getSignature(d,p,this.getSigningKey(u,l,f,s),this.createCanonicalRequest(c,h,m));returnc.headers[B6e]=`${X_e} Credential=${u.accessKeyId}/${p}, SignedHeaders=${this.getCanonicalHeaderList(h)}, Signature=${y}`,c}asyncgetSignature(r,n,o,i){leta=awaitthis.createStringToSign(r,n,i,X_e),s=newthis.sha256(awaito);returns.update(zN(a)),bS(awaits.digest())}getSigningKey(r,n,o,i){returnE6t(this.sha256,r,o,n,i||this.service)}}});varW6t=v(()=>{});varK6t=v(()=>{J6t();dF();J6e();W6t()});functionsOn(t,{credentials:e,credentialDefaultProvider:r}){letn;returne?e?.memoized?n=e:n=l3t(e,u3t,C6e):r?n=FN(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}functionuOn(t,e){if(e.configBound)returne;letr=asyncn=>e({...n,callerClientConfig:t});returnr.memoized=e.memoized,r.configBound=!0,r}varnve,G6t=v(()=>{J_e();ZO();K6t();nve=t=>{lete=t.credentials,r=!!t.credentials,n;Object.defineProperty(t,"credentials",{set(l){l&&l!==e&&l!==n&&(r=!0),e=l;letc=sOn(t,{credentials:e,credentialDefaultProvider:t.credentialDefaultProvider}),d=uOn(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)?n5(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=FN(t.signer):t.regionInfoProvider?s=()=>FN(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||Cre;returnnewm(p)}):s=asyncl=>{l=Object.assign({},{name:"sigv4",signingName:t.signingName||t.defaultSigningName,signingRegion:awaitFN(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||Cre;returnnewp(f)},Object.assign(t,{systemClockOffset:i,signingEscapePath:o,signer:s})}});varX6t=v(()=>{o6t();a6t();s6t();G6t()});varZ6t=v(()=>{X6t();i6t()});varY6t,ove,Q6t=v(()=>{Y6t=typeofTextEncoder=="function"?newTextEncoder:null,ove=t=>{if(typeoft=="string"){if(Y6t)returnY6t.encode(t).byteLength;lete=t.length;for(letr=e-1;r>=0;r--){letn=t.charCodeAt(r);n>127&
${bF.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("/")?"/":""}`;returnQwe.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=WIn(e).replace(/[\-:]/g,"");return{longDate:r,shortDate:r.slice(0,8)}}getCanonicalHeaderList(e){returnObject.keys(e).sort().join(";")}},JKe=classextendsiSe{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",newzKe)}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>HZt)returnPromise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");lety=rSe(h,p,d??this.service),g=KZt(HKe(r),{unhoistableHeaders:s,hoistableHeaders:l});f.sessionToken&&(g.query[GKe]=f.sessionToken),g.query[RZt]=eSe,g.query[AZt]=`${f.accessKeyId}/${y}`,g.query[WKe]=m,g.query[jZt]=i.toString(10);letb=BKe(g,a,u);returng.query[NZt]=this.getCanonicalHeaderList(b),g.query[KKe]=awaitthis.getSignature(m,y,this.getSigningKey(f,p,h,d),this.createCanonicalRequest(g,b,awaitnSe(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=rSe(l,u,s??this.service),f=awaitnSe({headers:{},body:n},this.sha256),p=newthis.sha256;p.update(r);letm=bF.toHex(awaitp.digest()),h=[BZt,c,d,i,m,f].join(`
`;super(r),this.name="AggregateError",this.errors=e}};t8e.exports={AggregateError:e8e,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 uRn},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:lRn,deprecate(t,e){return t},addAbortListener:Ure().addAbortListener||function(e,r){if(e===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);cYt(e,"signal"),cRn(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[oRn]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[iRn](){var o;(o=n)===null||o===void 0||o()}}},AbortSignalAny:aRn.any||function(e){if(e.length===1)return e[0];let r=new sRn,n=()=>r.abort();return e.forEach(o=>{cYt(o,"signals"),o.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{e.forEach(o=>o.removeEventListener("abort",n))},{once:!0}),r.signal}};t8e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var hb=S((oma,pYt)=>{"usestrict";var{format:dRn,inspect:lSe,AggregateError:fRn}=hy(),pRn=globalThis.AggregateError||fRn,mRn=Symbol("kIsNodeError"),hRn=["string","function","number","object","Function","Object","boolean","bigint","symbol"],gRn=/^([A-Z][a-z0-9]*)+$/,yRn="__node_internal_",cSe={};function A4(t,e){if(!t)throw new cSe.ERR_INTERNAL_ASSERTION(e)}function dYt(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 bRn(t,e,r){if(typeof e=="function")return A4(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 A4(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:dRn(e,...r)}function cg(t,e,r){r||(r=Error);class n extends r{constructor(...i){super(bRn(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[mRn]=!0,cSe[t]=n}function fYt(t){let e=yRn+t.name;return Object.defineProperty(t,"name",{value:e}),t}function _Rn(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new pRn([e,t],e.message);return r.code=e.code,r}return t||e}var r8e=class extends Error{constructor(e="Theoperationwasaborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new cSe.ERR_INVALID_ARG_TYPE("options","Object",r);super(e,r),this.code="ABORT_ERR",this.name="AbortError"}};cg("ERR_ASSERTION","%s",Error);cg("ERR_INVALID_ARG_TYPE",(t,e,r)=>{A4(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)A4(typeof u=="string","Allexpectedentrieshavetobeoftypestring"),hRn.includes(u)?o.push(u.toLowerCase()):gRn.test(u)?i.push(u):(A4(u!=="object",'The value "object" should be written as "Object"'),a.push(u));if(i.length>
`),pT(this,_ne,void0),pT(this,p0e,void0),pT(this,vne,"-".repeat(2)),pT(this,X4,newTextEncoder),pT(this,wne,void0),pT(this,Sne,void0),pT(this,m0e,void0),!cor(t))thrownewTypeError("Expected first argument to be a FormData instance.");letn;if(oor(e)?r=e:n=e,n||(n=gkn()),typeofn!="string")thrownewTypeError("Expected boundary argument to be a string.");if(r&&!oor(r))thrownewTypeError("Expected options argument to be an object.");bne(this,Sne,Array.from(t.entries())),bne(this,m0e,{..._kn,...r}),bne(this,_ne,Pc(this,X4).encode(Pc(this,EF))),bne(this,p0e,Pc(this,_ne).byteLength),this.boundary=`form-data-boundary-${n}`,this.contentType=`multipart/form-data; boundary=${this.boundary}`,bne(this,wne,Pc(this,X4).encode(`${Pc(this,vne)}${this.boundary}${Pc(this,vne)}${Pc(this,EF).repeat(2)}`));leto={"Content-Type":this.contentType},i=i9e(this,a9e,dor).call(this);i&&(this.contentLength=i,o["Content-Length"]=i),this.headers=bkn(Object.freeze(o)),Object.defineProperties(this,{boundary:f0e,contentType:f0e,contentLength:f0e,headers:f0e})}*values(){for(let[t,e]ofPc(this,Sne)){letr=Z4(e)?e:Pc(this,X4).encode(lor(e));yieldi9e(this,h0e,l9e).call(this,t,r),yieldr,yieldPc(this,_ne)}yieldPc(this,wne)}async*encode(){for(lettofthis.values())Z4(t)?yield*hkn(t.stream()):yield*uor(t)}[Symbol.iterator](){returnthis.values()}[Symbol.asyncIterator](){returnthis.encode()}};EF=newWeakMap;_ne=newWeakMap;p0e=newWeakMap;vne=newWeakMap;X4=newWeakMap;wne=newWeakMap;Sne=newWeakMap;m0e=newWeakMap;h0e=newWeakSet;l9e=function(t,e){letr="";if(r+=`${Pc(this,vne)}${this.boundary}${Pc(this,EF)}`,r+=`Content-Disposition: form-data; name="${aor(t)}"`,Z4(e)&&(r+=`; filename="${aor(e.name)}"${Pc(this,EF)}`,r+=`Content-Type: ${e.type||"application/octet-stream"}`),Pc(this,m0e).enableAdditionalHeaders===!0){letn=Z4(e)?e.size:e.byteLength;n!=null&&!isNaN(n)&&(r+=`${Pc(this,EF)}Content-Length: ${n}`)}returnPc(this,X4).encode(`${r}${Pc(this,EF).repeat(2)}`)};a9e=newWeakSet;dor=function(){lett=0;for(let[e,r]ofPc(this,Sne)){letn=Z4(r)?r:Pc(this,X4).encode(lor(r)),o=Z4(n)?n.size:n.byteLength;if(o==null||isNaN(o))return;t+=i9e(this,h0e,l9e).call(this,e,n).byteLength,t+=o,t+=Pc(this,p0e)}returnString(t+Pc(this,wne).byteLength)}});vargor=S((Zha,hor)=>{"use strict";hor.exports=typeofself=="object"?self.FormData:window.FormData});varyor=S(dg=>{"use strict";varwkn=dg&&dg.__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]}),Skn=dg&&dg.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Q5=dg&&dg.__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"&&wkn(r,e,n[o]);returnSkn(r,e),r}}(),PF=dg&&dg.__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(dg,"__esModule",{value:!0});dg.WebFormData=dg.Node16FormData=dg.Node18FormData=void0;dg.newFormData=Ckn;varg0e=V5();functionc9e(t){returntypeoft=="object"&&t!=null&&"name"int}functionCkn(){returnPF(this,void0,void0,function*(){lett;returng0e.RUNTIME.type==="node"&&g0e.RUNTIME.parsedVersion!=null&&g0e.RUNTIME.parsedVersion>=18?t=newy0e:g0e.RUNTIME.type==="node"?t=newb0e:t=new_0e,yieldt.setup(),t})}vary0e=class{setup(){returnPF(this,void0,void0,function*(){this.fd=new(yieldPromise.resolve().then(()=>Q5(eor()))).FormData})}append(e
`);o.enqueue(s)}catch(i){o.error(i)}})},cancel(){returnIne(this,void0,void0,function*(){varo;yield(o=r.return)===null||o===void0?void0:o.call(r)})}})}};pg.StreamUtils=Q9e;functionwir(t,e){returnAne(this,arguments,function*(){varn,o,i,a;if(!t.body)throwe?.abort(),newoK.CohereError({message:"Attempted to iterate over a response with no body"});lets=newe7e,u=newMF,l=t7e(t.body);try{for(varc=!0,d=Rne(JUn(l)),f;f=yieldLl(d.next()),n=f.done,!n;c=!0){a=f.value,c=!1;letp=a;for(letmofu.decode(p)){leth=s.decode(m);h&&(yieldyieldLl(h))}}}catch(p){o={error:p}}finally{try{!c&&!n&&(i=d.return)&&(yieldLl(i.call(d)))}finally{if(o)throwo.error}}for(letpofu.flush()){letm=s.decode(p);m&&(yieldyieldLl(m))}})}functionJUn(t){returnAne(this,arguments,function*(){varr,n,o,i;leta=newUint8Array;try{for(vars=!0,u=Rne(t),l;l=yieldLl(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=WUn(a))!==-1;)yieldyieldLl(a.slice(0,p)),a=a.slice(p)}}catch(c){n={error:c}}finally{try{!s&&!r&&(o=u.return)&&(yieldLl(o.call(u)))}finally{if(n)thrown.error}}a.length>0&&(yieldyieldLl(a))})}functionWUn(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}vare7e=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]=GUn(e,":");returno.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},MF=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();thrownewoK.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);thrownewoK.CohereError({message:`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`})}thrownewoK.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}};pg.LineDecoder=MF;MF.NEWLINE_CHARS=newSet([`
`)}}}}catch(M){s={error:M}}finally{try{!b&&!a&&(u=_.return)&&(yield u.call(_))}finally{if(s)throw s.error}}for(let M of T.flush()){let I=(0,nu.parseAWSEvent)(M);if(I){let j=yield(0,nu.mapResponseFromBedrock)(m,d,f,I);P.push(JSON.stringify(j)+`
`)}}return P.end(),{ok:!0,body:P,rawResponse:g.rawResponse}}else{let O=yield g.body;return{ok:!0,body:yield(0,nu.mapResponseFromBedrock)(m,d,f,O),rawResponse:g.rawResponse}}}catch(O){throw O}});nu.fetchOverride=Rto});var f1=S(TCe=>{"use strict";Object.defineProperty(TCe,"__esModule",{value:!0});TCe.CohereEnvironment=void 0;TCe.CohereEnvironment={Production:"https://api.cohere.com"}});var kF=S((Bsr,ECe)=>{(function(t,e,r){typeof ECe<"u"&&ECe.exports?ECe.exports=r():typeof define=="function"&&define.amd?define(r):e[t]=r()})("urljoin",Bsr,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 LYe=S(y_=>{"use strict";var Ato=y_&&y_.__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]}),Nto=y_&&y_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),ioe=y_&&y_.__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"&&Ato(r,e,n[o]);return Nto(r,e),r}}(),TK=y_&&y_.__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())})},jto=y_&&y_.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(y_,"__esModule",{value:!0});y_.V2=void 0;var PCe=ioe(f1()),Qi=ioe(te()),qn=ioe(LN()),qF=ioe(d1()),MCe=jto(kF()),hg=ioe(Tc()),$Ye=class{constructor(e={}){this._options=e}chatStream(e,r){return Qi.HttpResponsePromise.fromPromise(this.__chatStream(e,r))}__chatStream(e,r){return TK(this,void 0,void 0,function*(){var n,o,i;let a=yield((n=this._options.fetcher)!==null&&n!==void 0?n:Qi.fetcher)({url:(0,MCe.default)((i=(o=yield Qi.Supplier.get(this._options.baseUrl))!==null&&o!==void 0?o:yield Qi.Supplier.get(this._options.environment))!==null&&i!==void 0?i:PCe.CohereEnvironment.Production,"v2/chat"),method:"POST",headers:Object.assign({Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield Qi.Supplier.get(this._options.clientName))!=null?yield Qi.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":Qi.RUNTIME.type,"X-Fern-Runtime-Version":Qi.RUNTIME.version},r?.headers),contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},qF.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 Qi.Stream({stream:a.body,parse:s=>TK(this,void 0,void
`}}),rawResponse:u.rawResponse};if(u.error.reason==="status-code")switch(u.error.statusCode){case400:thrownewRe.BadRequestError(u.error.body,u.rawResponse);case401:thrownewRe.UnauthorizedError(u.error.body,u.rawResponse);case403:thrownewRe.ForbiddenError(u.error.body,u.rawResponse);case404:thrownewRe.NotFoundError(u.error.body,u.rawResponse);case422:thrownewRe.UnprocessableEntityError(u.error.body,u.rawResponse);case429:thrownewRe.TooManyRequestsError(u.error.body,u.rawResponse);case498:thrownewRe.InvalidTokenError(u.error.body,u.rawResponse);case499:thrownewRe.ClientClosedRequestError(u.error.body,u.rawResponse);case500:thrownewRe.InternalServerError(u.error.body,u.rawResponse);case501:thrownewRe.NotImplementedError(u.error.body,u.rawResponse);case503:thrownewRe.ServiceUnavailableError(u.error.body,u.rawResponse);case504:thrownewRe.GatewayTimeoutError(u.error.body,u.rawResponse);default:thrownewMo.CohereError({statusCode:u.error.statusCode,body:u.error.body,rawResponse:u.rawResponse})}switch(u.error.reason){case"non-json":thrownewMo.CohereError({statusCode:u.error.statusCode,body:u.error.rawBody,rawResponse:u.rawResponse});case"timeout":thrownewMo.CohereTimeoutError("Timeout exceeded when calling POST /v1/chat.");case"unknown":thrownewMo.CohereError({message:u.error.errorMessage,rawResponse:u.rawResponse})}})}chat(e,r){returnct.HttpResponsePromise.fromPromise(this.__chat(e,r))}__chat(e,r){returnC_(this,void0,void0,function*(){varn,o,i;let{accepts:a}=e,s=Xsr(e,["accepts"]),u=yield((n=this._options.fetcher)!==null&&n!==void0?n:ct.fetcher)({url:(0,MC.default)((i=(o=yieldct.Supplier.get(this._options.baseUrl))!==null&&o!==void0?o:yieldct.Supplier.get(this._options.environment))!==null&&i!==void0?i:PC.CohereEnvironment.Production,"v1/chat"),method:"POST",headers:Object.assign({Authorization:yieldthis._getAuthorizationHeader(),"X-Client-Name":(yieldct.Supplier.get(this._options.clientName))!=null?yieldct.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":ct.RUNTIME.type,"X-Fern-Runtime-Version":ct.RUNTIME.version,Accepts:a??void0},r?.headers),contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},Wc.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:Wc.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:thrownewRe.BadRequestError(u.error.body,u.rawResponse);case401:thrownewRe.UnauthorizedError(u.error.body,u.rawResponse);case403:thrownewRe.ForbiddenError(u.error.body,u.rawResponse);case404:thrownewRe.NotFoundError(u.error.body,u.rawResponse);case422:thrownewRe.UnprocessableEntityError(u.error.body,u.rawResponse);case429:thrownewRe.TooManyRequestsError(u.error.body,u.rawResponse);case498:thrownewRe.InvalidTokenError(u.error.body,u.rawResponse);case499:thrownewRe.ClientClosedRequestError(u.error.body,u.rawResponse);case500:thrownewRe.InternalServerError(u.error.body,u.rawResponse);case501:thrownewRe.NotImplementedError(u.error.body,u.rawResponse);case503:thrownewRe.ServiceUnavailableError(u.error.body,u.rawResponse);case504:thrownewRe.GatewayTimeoutError(u.error.body,u.rawResponse);default:thrownewMo.CohereError({statusCode:u.error.statusCode,body:u.error.body,rawResponse:u.rawResponse})}switch(u.error.reason){case"non-json":thrownewMo.CohereError({statusCode:u.error.statusCode,body:u.error.rawBody,rawResponse:u.rawResponse});case"timeout":thrownewMo.CohereTimeoutError("Timeout exceeded when calling POST
`}}),rawResponse:a.rawResponse};if(a.error.reason==="status-code")switch(a.error.statusCode){case 400:throw new Re.BadRequestError(a.error.body,a.rawResponse);case 401:throw new Re.UnauthorizedError(a.error.body,a.rawResponse);case 403:throw new Re.ForbiddenError(a.error.body,a.rawResponse);case 404:throw new Re.NotFoundError(a.error.body,a.rawResponse);case 422:throw new Re.UnprocessableEntityError(a.error.body,a.rawResponse);case 429:throw new Re.TooManyRequestsError(a.error.body,a.rawResponse);case 498:throw new Re.InvalidTokenError(a.error.body,a.rawResponse);case 499:throw new Re.ClientClosedRequestError(a.error.body,a.rawResponse);case 500:throw new Re.InternalServerError(a.error.body,a.rawResponse);case 501:throw new Re.NotImplementedError(a.error.body,a.rawResponse);case 503:throw new Re.ServiceUnavailableError(a.error.body,a.rawResponse);case 504:throw new Re.GatewayTimeoutError(a.error.body,a.rawResponse);default:throw new Mo.CohereError({statusCode:a.error.statusCode,body:a.error.body,rawResponse:a.rawResponse})}switch(a.error.reason){case"non-json":throw new Mo.CohereError({statusCode:a.error.statusCode,body:a.error.rawBody,rawResponse:a.rawResponse});case"timeout":throw new Mo.CohereTimeoutError("TimeoutexceededwhencallingPOST/v1/generate.");case"unknown":throw new Mo.CohereError({message:a.error.errorMessage,rawResponse:a.rawResponse})}})}generate(e,r){return ct.HttpResponsePromise.fromPromise(this.__generate(e,r))}__generate(e,r){return C_(this,void 0,void 0,function*(){var n,o,i;let a=yield((n=this._options.fetcher)!==null&&n!==void 0?n:ct.fetcher)({url:(0,MC.default)((i=(o=yield ct.Supplier.get(this._options.baseUrl))!==null&&o!==void 0?o:yield ct.Supplier.get(this._options.environment))!==null&&i!==void 0?i:PC.CohereEnvironment.Production,"v1/generate"),method:"POST",headers:Object.assign({Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield ct.Supplier.get(this._options.clientName))!=null?yield ct.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":ct.RUNTIME.type,"X-Fern-Runtime-Version":ct.RUNTIME.version},r?.headers),contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},Wc.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:Wc.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 Re.BadRequestError(a.error.body,a.rawResponse);case 401:throw new Re.UnauthorizedError(a.error.body,a.rawResponse);case 403:throw new Re.ForbiddenError(a.error.body,a.rawResponse);case 404:throw new Re.NotFoundError(a.error.body,a.rawResponse);case 422:throw new Re.UnprocessableEntityError(a.error.body,a.rawResponse);case 429:throw new Re.TooManyRequestsError(a.error.body,a.rawResponse);case 498:throw new Re.InvalidTokenError(a.error.body,a.rawResponse);case 499:throw new Re.ClientClosedRequestError(a.error.body,a.rawResponse);case 500:throw new Re.InternalServerError(a.error.body,a.rawResponse);case 501:throw new Re.NotImplementedError(a.error.body,a.rawResponse);case 503:throw new Re.ServiceUnavailableError(a.error.body,a.rawResponse);case 504:throw new Re.GatewayTimeoutError(a.error.body,a.rawResponse);default:throw new Mo.CohereError({statusCode:a.error.statusCode,body:a.error.body,rawResponse:a.rawResponse})}switch(a.error.reason){case"non-json":throw new Mo.CohereError({statusCode:a.error.statusCode,body:a.error.rawBody,rawResponse:a.rawResponse});case"timeout":throw new Mo.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=mur.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=oQe.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=oQe.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(...Tro(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)}},FCe=oQe;xro(FCe,"specialTokenRegex",t=>new RegExp(t.map(e=>Ero(e)).join("|"),"g"))});var gur=v(()=>{hur()});async function aQe(t){return t in kCe||(kCe[t]=Mro.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>new FCe(e)).catch(e=>{throw delete kCe[t],e})),await kCe[t]}async function qCe(t){return aQe(iQe(t))}var Pro,kCe,Mro,sQe=v(()=>{Bo();GB();gur();Pro={};Rt(Pro,{encodingForModel:()=>qCe,getEncoding:()=>aQe});kCe={},Mro=new Fw({})});function Hv(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 Iro,UCe,Rro,yur,bur,Aro,jK,v2,Jv=v(()=>{Bo();H0();GB();Qh();lee();pur();sQe();Iro={};Rt(Iro,{BaseLangChain:()=>jK,BaseLanguageModel:()=>v2,calculateMaxTokens:()=>bur,getEmbeddingContextSize:()=>Rro,getModelContextSize:()=>yur,getModelNameForTiktoken:()=>UCe,isOpenAITool:()=>Hv});UCe=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,Rro=t=>{switch(t){case"text-embedding-ada-002":return 8191;default:return 2046}},yur=t=>{switch(UCe(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}};bur=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 ilr(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 GCe(t){return!!t.finishReason&&mno.includes(t.finishReason)}function HF(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];GCe(i)&&(o+=`Candidatewasblockeddueto${i.finishReason}`,i.finishMessage&&(o+=`:${i.finishMessage}`))}return o}function Coe(t){return this instanceof Coe?(this.v=t,this):new Coe(t)}function hno(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 Coe?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 gno(t){let e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),r=_no(e),[n,o]=r.tee();return{stream:bno(n),response:yno(o)}}async function yno(t){let e=[],r=t.getReader();for(;;){let{done:n,value:o}=await r.read();if(n)return OQe(vno(e));e.push(o)}}function bno(t){return hno(this,arguments,function*(){let r=t.getReader();for(;;){let{value:n,done:o}=yield Coe(r.read());if(o)break;yield yield Coe(OQe(n))}})}function _no(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 gh("Failed to parse stream"));return}n.close();return}o+=a;let u=o.match(alr),l;for(;u;){try{l=JSON.parse(u[1])}catch{n.error(new gh(`ErrorparsingJSONresponse:"${u[1]}"`));return}n.enqueue(l),o=o.substring(u[0].length),u=o.match(alr)}return i()}).catch(a=>{let s=a;throw s.stack=a.stack,s.name==="AbortError"?s=new ZCe("Request aborted when reading from the stream"):s=new gh("Error reading from the stream"),s})}}})}function vno(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 dlr(t,e,r,n){let o=await Ooe(e,x2.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(r),n);return gno(o)}async function flr(t,e,r,n){let i=await(await Ooe(e,x2.GENERATE_CONTENT,t,!1,JSON.stringify(r),n)).json();return{response:OQe(i)}}function plr(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}functioneR(t,e){if(!(thisinstanceofeR))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=newTm(e.headers),this.url=e.url||"",this._initBody(t)}functionAlr(t,e){returnnewPromise(function(r,n){varo=newE2(t,e);if(o.signal&&o.signal.aborted)returnn(newT2("Aborted","AbortError"));vari=newXMLHttpRequest;functiona(){i.abort()}i.onload=function(){varl={statusText:i.statusText,headers:Jno(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(neweR(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(newT2("Aborted","AbortError"))},0)};functions(l){try{returnl===""&&Sg.location.href?Sg.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&&(bb.blob?i.responseType="blob":bb.arrayBuffer&&(i.responseType="arraybuffer")),e&&typeofe.headers=="object"&&!(e.headersinstanceofTm||Sg.Headers&&e.headersinstanceofSg.Headers)){varu=[];Object.getOwnPropertyNames(e.headers).forEach(function(l){u.push(DK(l)),i.setRequestHeader(l,jQe(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)})}varSg,bb,Elr,Mlr,zno,Wno,T2,Nlr=v(()=>{Sg=typeofglobalThis<"u"&&globalThis||typeofself<"u"&&self||typeofwindow<"u"&&window||{},bb={searchParams:"URLSearchParams"inSg,iterable:"Symbol"inSg&&"iterator"inSymbol,blob:"FileReader"inSg&&"Blob"inSg&&function(){try{returnnewBlob,!0}catch{return!1}}(),formData:"FormData"inSg,arrayBuffer:"ArrayBuffer"inSg};bb.arrayBuffer&&(Elr=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],Mlr=ArrayBuffer.isView||function(t){returnt&&Elr.indexOf(Object.prototype.toString.call(t))>-1});Tm.prototype.append=function(t,e){t=DK(t),e=jQe(e);varr=this.map[t];this.map[t]=r?r+", "+e:e};Tm.prototype.delete=function(t){deletethis.map[DK(t)]};Tm.prototype.get=function(t){returnt=DK(t),this.has(t)?this.map[t]:null};Tm.prototype.has=function(t){returnthis.map.hasOwnProperty(DK(t))};Tm.prototype.set=function(t,e){this.map[DK(t)]=jQe(e)};Tm.prototype.forEach=function(t,e){for(varrinthis.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)};Tm.prototype.keys=function(){vart=[];returnthis.forEach(function(e,r){t.push(r)}),DQe(t)};Tm.prototype.values=function(){vart=[];returnthis.forEach(function(e){t.push(e)}),DQe(t)};Tm.prototype.entries=function(){vart=[];returnthis.forEach(function(e,r){t.push([r,e])}),DQe(t)};bb.iterable&&(Tm.prototype[Symbol.iterator]=Tm.prototype.entries);zno=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];E2.prototype.clone=function(){returnnewE2(this,{body:this._bodyInit})};Rlr.call(E2.prototype);Rlr.call(eR.pro
`,t}var qlr=v(()=>{});function Hr(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r}function xe(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}var IS=v(()=>{});var HQe,JQe=v(()=>{HQe=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return HQe=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(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))}});function Eoe(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var Poe,nxe=v(()=>{Poe=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)}});var Vt,Em,Ic,JF,tR,FK,kK,qK,UK,BK,zK,VK,HK,JK,WK,rR,nR=v(()=>{nxe();Vt=class extends Error{},Em=class t extends Vt{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;let i=r;this.code=i?.code,this.param=i?.param,this.type=i?.type}static makeMessage(e,r,n){let o=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&o?`${e}${o}`:e?`${e}statuscode(nobody)`:o||"(no status code or body)"}static generate(e,r,n,o){if(!e||!o)return new JF({message:n,cause:Poe(r)});let i=r?.error;return e===400?new FK(e,i,n,o):e===401?new kK(e,i,n,o):e===403?new qK(e,i,n,o):e===404?new UK(e,i,n,o):e===409?new BK(e,i,n,o):e===422?new zK(e,i,n,o):e===429?new VK(e,i,n,o):e>=500?new HK(e,i,n,o):new t(e,i,n,o)}},Ic=class extends Em{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},JF=class extends Em{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},tR=class extends JF{constructor({message:e}={}){super({message:e??"Request timed out."})}},FK=class extends Em{},kK=class extends Em{},qK=class extends Em{},UK=class extends Em{},BK=class extends Em{},zK=class extends Em{},VK=class extends Em{},HK=class extends Em{},JK=class extends Vt{constructor(){super("Could not parse response content as the length limit was reached")}},WK=class extends Vt{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},rR=class extends Error{constructor(e){super(e)}}});function KQe(t){return typeof t!="object"?{}:t??{}}function Blr(t){if(!t)return!0;for(let e in t)return!1;return!0}function zlr(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function KK(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var ioo,Ulr,Sy,WQe,Vlr,Hlr,b1=v(()=>{nR();ioo=/^[a-z][a-z0-9+.-]*:/i,Ulr=t=>ioo.test(t),Sy=t=>(Sy=Array.isArray,Sy(t)),WQe=Sy;Vlr=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Vt(`${t}mustbeaninteger`);if(e<0)throw new Vt(`${t}mustbeapositiveinteger`);return e},Hlr=t=>{try{return JSON.parse(t)}catch{return}}});var oR,GK=v(()=>{oR=t=>new Promise(e=>setTimeout(e,t))});var WF,GQe=v(()=>{WF="6.16.0"});function aoo(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}function uoo(){if(typeof navigator>"
`,"\r"]);P2.NEWLINE_REGEXP=/\r\n|[\n\r]/g});functionIoe(){}functioncxe(t,e,r){return!e||dxe[t]>dxe[r]?Ioe:e[t].bind(e)}functionKc(t){lete=t.logger,r=t.logLevel??"off";if(!e)returnhoo;letn=hcr.get(e);if(n&&n[0]===r)returnn[1];leto={error:cxe("error",e,r),warn:cxe("warn",e,r),info:cxe("info",e,r),debug:cxe("debug",e,r)};returnhcr.set(e,[r,o]),o}vardxe,aet,hoo,hcr,_1,Roe=v(()=>{b1();dxe={off:0,error:200,warn:300,info:400,debug:500},aet=(t,e,r)=>{if(t){if(zlr(dxe,t))returnt;Kc(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(dxe))}`)}};hoo={error:Ioe,warn:Ioe,info:Ioe,debug:Ioe},hcr=newWeakMap;_1=t=>(t.options&&(t.options={...t.options},deletet.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headersinstanceofHeaders?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"int&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),deletet.retryOfRequestLogID),t)});asyncfunction*goo(t,e){if(!t.body)throwe.abort(),typeofglobalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?newVt("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):newVt("Attempted to iterate over a response with no body");letr=newset,n=newP2,o=YQe(t.body);forawait(letiofyoo(o))for(letaofn.decode(i)){lets=r.decode(a);s&&(yields)}for(letiofn.flush()){leta=r.decode(i);a&&(yielda)}}asyncfunction*yoo(t){lete=newUint8Array;forawait(letroft){if(r==null)continue;letn=rinstanceofArrayBuffer?newUint8Array(r):typeofr=="string"?XK(r):r,o=newUint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;leti;for(;(i=pcr(e))!==-1;)yielde.slice(0,i),e=e.slice(i)}e.length>0&&(yielde)}functionboo(t,e){letr=t.indexOf(e);returnr!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}varAoe,aR,set,uet=v(()=>{IS();nR();Moe();mcr();Moe();nxe();lxe();Roe();nR();aR=classt{constructor(e,r,n){this.iterator=e,Aoe.set(this,void0),this.controller=r,Hr(this,Aoe,n,"f")}staticfromSSEResponse(e,r,n){leto=!1,i=n?Kc(n):console;asyncfunction*a(){if(o)thrownewVt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;lets=!1;try{forawait(letuofgoo(e,r))if(!s){if(u.data.startsWith("[DONE]")){s=!0;continue}if(u.event===null||!u.event.startsWith("thread.")){letl;try{l=JSON.parse(u.data)}catch(c){throwi.error("Could not parse message into JSON:",u.data),i.error("From chunk:",u.raw),c}if(l&&l.error)thrownewEm(void0,l.error,void0,e.headers);yieldl}else{letl;try{l=JSON.parse(u.data)}catch(c){throwconsole.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),c}if(u.event=="error")thrownewEm(void0,l.error,l.message,void0);yield{event:u.event,data:l}}}s=!0}catch(u){if(Eoe(u))return;throwu}finally{s||r.abort()}}returnnewt(a,r,n)}staticfromReadableStream(e,r,n){leto=!1;asyncfunction*i(){lets=newP2,u=YQe(e);forawait(letlofu)for(letcofs.decode(l))yieldc;for(letlofs.flush())yieldl}asyncfunction*a(){if(o)thrownewVt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;lets=!1;try{forawait(letuofi())s||u&&(yieldJSON.parse(u));s=!0}catch(u){if(Eoe(u))return;throwu}finally{s||r.abort()}}returnnewt(a,r,n)}[(Aoe=newWeakMap,Symbol.asyncIterator)](){returnthis.iterator()}tee(){lete=[],r=[],n=this.iterator(),o=i=>({next:()=>{if(i.length===0){leta=n.next();e.push(a),r.push(a)}returni.shift()}});return[newt(()=>o(e),this.controller,xe(this,Aoe,"f")),newt(()=>o(r),this.controller,xe(this,Aoe,"f"))]}toReadableStream(){lete=this,r;returnZQe({asyncstart(){r=e[Symbol.asyncIterator]()},asyncpull(n){try{let{value:o,done:i}=awaitr.next();if(i)returnn.close();leta=XK(JSON.stringify(o)+`
${d}`)}return a},je=Too(Scr)});var I2,gxe=v(()=>{kr();Iu();ns();I2=class extends ze{list(e,r={},n){return this._client.getAPIList(je`/chat/completions/${e}/messages`,ri,{query:r,...n})}}});var AC=v(()=>{nR()});function Foe(t){return t!==void 0&&"function"in t&&t.function!==void 0}function Ccr(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function koe(t){return t?.$brand==="auto-parseable-response-format"}function R2(t){return t?.$brand==="auto-parseable-tool"}function xcr(t,e){return!e||!bet(e)?{...t,choices:t.choices.map(r=>(Tcr(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:qoe(t,e)}function qoe(t,e){let r=t.choices.map(n=>{if(n.finish_reason==="length")throw new JK;if(n.finish_reason==="content_filter")throw new WK;return Tcr(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(o=>Ioo(e,o))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?Moo(e,n.message.content):null}}});return{...t,choices:r}}function Moo(t,e){return t.response_format?.type!=="json_schema"?null:t.response_format?.type==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function Ioo(t,e){let r=t.tools?.find(n=>Foe(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:R2(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function Ocr(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(n=>Foe(n)&&n.function?.name===e.function.name);return Foe(r)&&(R2(r)||r?.function.strict||!1)}function bet(t){return koe(t.response_format)?!0:t.tools?.some(e=>R2(e)||e.type==="function"&&e.function.strict===!0)??!1}function Tcr(t){for(let e of t||[])if(e.type!=="function")throw new Vt(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Ecr(t){for(let e of t??[]){if(e.type!=="function")throw new Vt(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new Vt(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var YK=v(()=>{AC()});var QK,_et,vet=v(()=>{QK=t=>t?.role==="assistant",_et=t=>t?.role==="tool"});var wet,yxe,bxe,Uoe,Boe,_xe,zoe,w1,Voe,vxe,wxe,e8,Pcr,KF,Sxe=v(()=>{IS();AC();KF=class{constructor(){wet.add(this),this.controller=new AbortController,yxe.set(this,void 0),bxe.set(this,()=>{}),Uoe.set(this,()=>{}),Boe.set(this,void 0),_xe.set(this,()=>{}),zoe.set(this,()=>{}),w1.set(this,{}),Voe.set(this,!1),vxe.set(this,!1),wxe.set(this,!1),e8.set(this,!1),Hr(this,yxe,new Promise((e,r)=>{Hr(this,bxe,e,"f"),Hr(this,Uoe,r,"f")}),"f"),Hr(this,Boe,new Promise((e,r)=>{Hr(this,_xe,e,"f"),Hr(this,zoe,r,"f")}),"f"),xe(this,yxe,"f").catch(()=>{}),xe(this,Boe,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},xe(this,wet,"m",Pcr).bind(this))},0)}_connected(){this.ended||(xe(this,bxe,"f").call(this),this._emit("connect"))}get ended(){return xe(this,Voe,"f")}get errored(){return xe(this,vxe,"f")}get aborted(){return xe(this,wxe,"f")}abort(){this.controller.abort()}on(e,r){return(xe(this,w1,"f")[e]||(xe(this,w1,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=xe(this,w1,"f")[e];if(!n)return this;let o=n.findIndex(i=>i.listener===r);return o>=0&&n.splice(o,1),this}once(e,r){return(xe(this,w1,"f")[e]||(xe(this,w1,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{Hr(this,e8,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){Hr(this,e8,!0,"f"),await xe(this,Boe,"f")}_emit(e,...r){if(xe(this,Voe,"f"))return;e==="end"&&(Hr(this,Voe,!0,"f"),xe(this,_xe,"f").call(this));let n=xe(this,w1,"f")[e];if(n&&(xe(this,w1,"f")[e]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...r))),e==="abort"){let o=r[0];!xe(this,e8,"f")&&!n?.length
\r `.includes(t[n]);)n++};return a()},Aet=t=>Aoo(t,yh.ALL^yh.NUM)});var Net=v(()=>{uet()});function joo(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 Vt(`missing finish_reason for choice ${d}`);let{content:m=null,function_call:h,tool_calls:y,...g}=l,b=l.role;if(!b)throw new Vt(`missing role for choice ${d}`);if(h){let{arguments:_,name:w}=h;if(_==null)throw new Vt(`missing function_call.arguments for choice ${d}`);if(!w)throw new Vt(`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}}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:O,type:T,id:P,...M}=_,{arguments:I,name:j,...A}=O||{};if(P==null)throw new Vt(`missing choices[${d}].tool_calls[${w}].id
${Txe(t)}`);if(T==null)throw new Vt(`missing choices[${d}].tool_calls[${w}].type
${Txe(t)}`);if(j==null)throw new Vt(`missing choices[${d}].tool_calls[${w}].function.name
${Txe(t)}`);if(I==null)throw new Vt(`missing choices[${d}].tool_calls[${w}].function.arguments
${Txe(t)}`);return{...M,id:P,type:T,function:{...A,name:j,arguments:I}}})}}:{...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 xcr(u,e)}function Txe(t){return JSON.stringify(t)}var Mm,S1,r8,GF,jet,xxe,Det,$et,Let,Oxe,Fet,Ncr,A2,Exe=v(()=>{IS();Acr();AC();YK();Net();Pet();A2=class t extends t8{constructor(e){super(),Mm.add(this),S1.set(this,void 0),r8.set(this,void 0),GF.set(this,void 0),Hr(this,S1,e,"f"),Hr(this,r8,[],"f")}get currentChatCompletionSnapshot(){return xe(this,GF,"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())),xe(this,Mm,"m",jet).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)xe(this,Mm,"m",Det).call(this,a);if(i.controller.signal?.aborted)throw new Ic;return this._addChatCompletion(xe(this,Mm,"m",Oxe).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),xe(this,Mm,"m",jet).call(this),this._connected();let o=aR.fromReadableStream(e,this.controller),i;for await(let a of o)i&&i!==a.id&&this._addChatCompletion(xe(this,Mm,"m",Oxe).call(this)),xe(this,Mm,"m",Det).call(this,a),i=a.id;if(o.controller.signal?.aborted)throw new Ic;return this._addChatCompletion(xe(this,Mm,"m",Oxe).call(this))}[(S1=new WeakMap,r8=new WeakMap,GF=new WeakMap,Mm=new WeakSet,jet=function(){this.ended||Hr(this,GF,void 0,"f")},xxe=function(r){let n=xe(this,r8,"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},xe(this,r8,"f")[r.index]=n,n)},Det=function(r){if(this.ended)return;let n=xe(this,Mm,"m",Ncr).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=xe(this,Mm,"m",xxe).call(this,i);i.finish_reason&&(xe(this,Mm,"m",Let).call(this,i),a.current_tool_call_index!=null&&xe(this,Mm,"m",$et).call(this,i,a.current_tool_call_index));for(let s of o.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(xe(this,Mm,"m",Let).call(this,i),a.current_tool_call_index!=null&&xe(this,Mm,"m",$et).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))}}},$et=function(r,n){if(xe(this,Mm,"m",xxe).call(this,r).done_tool_calls.has(n))return;let i=r.message.tool_calls?.[n];if(!i)throw new Error("notoolcallsnapshot");if(!i.type)throw new Error("toolcallsnapshotmissing`type`");if(i.type==="function"){let a=xe(this,S1,"f")?.tools?.find(s=>Foe(s)&&s.func
`)}`),new H3(h,JSON.stringify(e))}i=o}let a=JA(r),u=await rc.configure(a.callbacks,this.callbacks,a.tags||n,this.tags,a.metadata,this.metadata,{verbose:this.verbose})?.handleToolStart(this.toJSON(),typeof e=="string"?e:JSON.stringify(e),a.runId,void 0,void 0,void 0,a.runName);delete a.runId;let l;try{l=await this._call(i,u,a)}catch(m){throw await u?.handleToolError(m),m}let c,d;if(this.responseFormat==="content_and_artifact")if(Array.isArray(l)&&l.length===2)[c,d]=l;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
Result: ${JSON.stringify(l)}`);else c=l;let f;F$(e)&&(f=e.id),!f&&tSt(a)&&(f=a.toolCall.id);let p=lso({content:c,artifact:d,toolCallId:f,name:this.name,metadata:this.metadata});return await u?.handleToolEnd(p),p}},Int=class extends Mnt{constructor(e){super(e);x(this,"schema",Ct.object({input:Ct.string().optional()}).transform(e=>e.input))}call(e,r){let n=typeof e=="string"||e==null?{input:e}:e;return super.call(n,r)}},Rnt=class extends Int{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=JA(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)}},ypr=class extends Mnt{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=JA(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)}},uso=class{getTools(){return this.tools}}});var Ant=v(()=>{dR();ku();nV()});var bpr=v(()=>{});var _pr=v(()=>{});var vpr=v(()=>{});var wpr=v(()=>{});var Spr=v(()=>{});var dso,fso,pso,mso,hso,gso,yso,bso,_so,vso,gFa,Cpr=v(()=>{Qa();nV();Q2();dso=Kt.object({type:Kt.literal("screenshot")}),fso=Kt.object({type:Kt.literal("click"),x:Kt.number(),y:Kt.number(),button:Kt.enum(["left","right","wheel","back","forward"]).default("left")}),pso=Kt.object({type:Kt.literal("double_click"),x:Kt.number(),y:Kt.number(),button:Kt.enum(["left","right","wheel","back","forward"]).default("left")}),mso=Kt.object({type:Kt.literal("drag"),path:Kt.array(Kt.object({x:Kt.number(),y:Kt.number()}))}),hso=Kt.object({type:Kt.literal("keypress"),keys:Kt.array(Kt.string())}),gso=Kt.object({type:Kt.literal("move"),x:Kt.number(),y:Kt.number()}),yso=Kt.object({type:Kt.literal("scroll"),x:Kt.number(),y:Kt.number(),scroll_x:Kt.number(),scroll_y:Kt.number()}),bso=Kt.object({type:Kt.literal("type"),text:Kt.string()}),_so=Kt.object({type:Kt.literal("wait"),duration:Kt.number().optional()}),vso=Kt.discriminatedUnion("type",[dso,fso,pso,mso,hso,gso,yso,bso,_so]),gFa=Kt.object({action:vso})});var wso,vFa,xpr=v(()=>{nV();Q2();wso=Kt.object({type:Kt.literal("exec"),command:Kt.array(Kt.string()),env:Kt.record(Kt.string(),Kt.string()).optional(),working_directory:Kt.string().optional(),timeout_ms:Kt.number().optional(),user:Kt.string().optional()}),vFa=Kt.discriminatedUnion("type",[wso])});var xFa,Opr=v(()=>{nV();Q2();xFa=Kt.object({commands:Kt.array(Kt.string()).describe("Arrayofshellcommandstoexecute"),timeout_ms:Kt.number().optional().describe("Optionaltimeoutinmillisecondsforthecommands"),max_output_length:Kt.number().optional().describe("Optionalmaximumnumberofcharacterstoreturnfromeachcommand")})});var Sso,Cso,xso,PFa,Tpr=v(()=>{nV();Q2();Sso=Kt.object({type:Kt.literal("create_file"),path:Kt.string(),diff:Kt.string()}),Cso=Kt.object({type:Kt.literal("update_file"),path:Kt.string(),diff:Kt.string()}),xso=Kt.object({type:Kt.literal("delete_file"),path:Kt.string()}),PFa=Kt.discriminatedUnion("type",[Sso,Cso,xso])});var Epr=v(()=>{Ant();bpr();_pr();vpr();wpr();Spr();Cpr();xpr();Opr();Tpr()});var Ppr=v(()=>{_v();nV();JB()});var Mpr=v(()=>{L8()});var Ipr=v(()=>{L8();yOe()});var oV=v(()=>{ak();sk();uk();iie();L8();pOe();wnt();yOe();_Oe();xnt();Ont();mpr();Tnt();hpr();Ent();gpr();Ant();Epr();Ppr();Mpr();Ipr();dR()});var Apr=S((Jka,Rpr)=>{Rpr.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 Oso,Tso,Npr,jpr=v(()=>{Oso=L(Apr(),1),Tso=Object.defineProperty,Npr=(t,e)=>{for(var r in e)Tso(t,r,{get:e[r],enumerable:!0})}});var Eso,Nnt,Dpr=v(()=>{jpr();ku();S2();zF();Eso={};Npr(Eso,{JinaEmbeddings:()=>Nnt});Nnt=class extends PS{co
- `),Dso={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Donotpassthelanguageoptiontocreatewhenusingacustomtokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported.
- ${jso}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmerpropertymustbeafunction.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.oramasearch.com/open-source/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Customstopwordsarraymustonlycontainstrings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boostvaluemustbeanumbergreaterthan,orlessthan0.",INVALID_FILTER_OPERATION:"Youcanonlyuseoneoperationperfilter,yourequested%d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sortisdisabled.Pleasereadthedocumentationathttps://docs.oramasearch for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead.
Inputvectorsmustbeofthesizedeclaredintheschema,ascalculatingsimilaritybetweenvectorsofdifferentsizescanleadtounexpectedresults.`,WRONG_SEARCH_PROPERTY_TYPE:'Property "%s" is not searchable. Only "string" properties are searchable.',FACET_NOT_SUPPORTED:`Facetdoens't support the type "%s".`,INVALID_DISTANCE_SUFFIX:'Invaliddistancesuffix"%s".Validsuffixesare:cm,m,km,mi,yd,ft.',INVALID_SEARCH_MODE:'Invalidsearchmode"%s".Validmodesare:"fulltext","vector","hybrid".',MISSING_VECTOR_AND_SECURE_PROXY:"No vector was provided and no secure proxy was configured. Please provide a vector or configure an Orama Secure Proxy to perform hybrid search.",MISSING_TERM:'"term"isarequiredparameterwhenperforminghybridsearch.Pleaseprovideasearchterm.',INVALID_VECTOR_INPUT:'Invalid"vector"property.Expectedanobjectwith"value"and"property"properties,butgot"%s"instead.',PLUGIN_CRASHED:"A plugin crashed during initialization. Please check the error message for more information:",PLUGIN_SECURE_PROXY_NOT_FOUND:`Could not find '@orama/secure-proxy-plugin' 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."}});function Wpr(t){return{raw:Number(t),formatted:sV(t)}}function Kpr(t){if(t.id){if(typeof t.id!="string")throw Fr("DOCUMENT_ID_MUST_BE_STRING",typeof t.id);return t.id}return lie()}function $nt(t,e){for(let[r,n]of Object.entries(e)){let o=t[r];if(!(typeof o>"u")&&!(n==="geopoint"&&typeof o=="object"&&typeof o.lon=="number"&&typeof o.lat=="number")&&!(n==="enum"&&(typeof o=="string"||typeof o=="number"))){if(n==="enum[]"&&Array.isArray(o)){let i=o.length;for(let a=0;a<i;a++)if(typeof o[a]!="string"&&typeof o[a]!="number")return r+"."+a;continue}if(N1(n)){let i=Fnt(n);if(!Array.isArray(o)||o.length!==i)throw Fr("INVALID_INPUT_VECTOR",r,i,o.length);continue}if(B8(n)){if(!Array.isArray(o))return r;let i=Lnt(n),a=o.length;for(let s=0;s<a;s++)if(typeof o[s]!==i)return r+"."+s;continue}if(typeof n=="object"){if(!o||typeof o!="object")return r;let i=$nt(o,n);if(i)return r+"."+i;continue}if(typeof o!==n)return r}}}function Gpr(t){return t==="geopoint"}function N1(t){return typeof t=="string"&&/^vector\[\d+\]$/.test(t)}function B8(t){return typeof t=="string"&&$so[t]}function Lnt(t){return Lso[t]}function Fnt(t){let e=Number(t.slice(7,-1));switch(!0){case isNaN(e):throw Fr("INVALID_VECTOR_VALUE",t);case e<=0:throw Fr("INVALID_VECTOR_SIZE",t);default:return e}}var $so,Lso,cie=v(()=>{bh();Gc();Gc();$so={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},Lso={"string[]":"string","number[]":"number","boolean[]":"boolean","enum[]":"enum"}});function Xpr(){return{idToInternalId:new Map,internalIdToId:[],save:Fso,load:kso}}function Fso(t){return{internalIdToId:t.internalIdToId}}function kso(t,e){let{internalIdToId:r}=e;t.internalDocumentIDStore.idToInternalId.clear(),t.internalDocumentIDStore.internalIdToId=[];let n=r.length;for(let o=0;o<n;o++){let i=r[o];t.internalDocumentIDStore.idToInternalId.set(i,o+1),t.internalDocumentIDStore.internalIdToId.push(i)}}function iu(t,e){if(typeof e=="string"){let r=t.idToInternalId.get(e);if(r)return r;let n=t.idToInternalId.size+1;return t.idToInternalId.set(e,n),t.internalIdToId.push(e),n}return e>t.internalIdToId.length?iu(t,e.toString()):e}function NS(t,e){if(t.internalIdToId.length<e)throw new Error(`Invalid internalId ${e}`);return t.internalIdToId[e-1]}var jS=v(()=>{});function Uso(t,e){return{sharedInternalDocumentStore:e,docs:{},count:0}}function Bso(t,e){let r=iu(t.sharedInternalDocumentStore,e);return t.docs[r]}function zso(t,e){let r=e.length,n=Array.from({length:r});for(let o=0;o<r;o++){let i=iu(t.sharedInternalDocumentStore,e[o]);n[o]=t.docs[i]}return n}function Vso(t){return t.docs}function Hso(t,e,r){let n=iu(t.sharedInternalDocumentStore,e);return typeof t.docs[n]<"u"?!1:(t.docs[n]=r,t.count++,!0)}function Jso(t,e){let r=iu(t.sharedInternalDocumentStore,e);return typeof t.docs[r]>"u"?!1:(delete t.docs[r],t.count--,!0)}function Wso(t){return t.count}function Kso(t,e){let r=e;return{docs:r.docs,count:r.count,sharedInternalDocumentStore:t}}function Gso(t){return{docs:t.docs,count:t.count}}function Zpr(){return{create:Uso,get:Bso,getMultiple:zso,getAll:Vso,store:Hso,remove:Jso,count:Wso,load:Kso,save:Gso}}var knt=v(()=>{jS()});function Qpr(t,e){let r=[],n=t.plugins?.length;if(!n)return r;for(let o=0;o<n;o++)try{let i=t.plugins[o];typeof i[e]=="function"&&r.push(i[e])}catch(i){throw console.error("Caught error in getAllPluginsByHook:",i),Fr("PLUGIN_CRASHED")}return r}var Ypr,emr=v(()=>{bh();Ypr=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeLoad","afterLoad","afterCreate"]});function zC(t,e,r,n){if(t.some(yd))return(async()=>{for(let i of t)await i(e,r,n)})();for(let i of t)i(e,r,n)}function uV(t,e,r){if(t.some(yd))return(async()=>{for(let o of t)await o(e,r)})();for(let o o
which is longer than the specified ${this.chunkSize}`),o.length>0)){let l=this.joinDocs(o,r);for(l!==null&&n.push(l);i>this.chunkOverlap||i+u+o.length*r.length>this.chunkSize&&i>0;)i-=await this.lengthFunction(o[0]),o.shift()}o.push(s),i+=u}let a=this.joinDocs(o,r);return a!==null&&n.push(a),n}},Sie=class Pot extends Pgr{constructor(r){super(r);x(this,"separators",[`
`," ",""];throw new Error(`Language ${r} is not supported.`)}}});var Mot=v(()=>{Mgr()});var Igr,bR,TTe,Rgr=v(()=>{Or();aV();_t();Ogr();ot();Zt();Igr=L(mV());Mot();bR=require("obsidian");vb();TTe=class{constructor(e,r,n){this.app=e;this.dbOps=r;this.embeddingsManager=n;this.state={isIndexingPaused:!1,isIndexingCancelled:!1,indexedCount:0,totalFilesToIndex:0,processedFiles:new Set,currentIndexingNotice:null,indexNoticeMessage:null};let o=ae();this.rateLimiter=new vie(o.embeddingRequestsPerMin),this.embeddingBatchSize=o.embeddingBatchSize,this.checkpointInterval=8*this.embeddingBatchSize,al(async()=>{let i=ae();this.rateLimiter=new vie(i.embeddingRequestsPerMin),this.embeddingBatchSize=i.embeddingBatchSize,this.checkpointInterval=8*this.embeddingBatchSize})}async indexVaultToVectorStore(e){let r=[];try{let n=await this.embeddingsManager.getEmbeddingsAPI();if(!n)return console.error("Embedding instance not found."),0;await this.dbOps.checkAndHandleEmbeddingModelChange(n)&&(e=!0),e?(await this.dbOps.clearIndex(n),this.dbOps.clearFilesMissingEmbeddings()):await this.dbOps.garbageCollect();let i=await this.getFilesToIndex(e);if(i.length===0)return new bR.Notice("Copilot vault index is up-to-date."),0;this.initializeIndexingState(i.length),this.createIndexingNotice(),this.dbOps.clearFilesMissingEmbeddings();let a=await this.prepareAllChunks(i);if(a.length===0)return new bR.Notice("No valid content to index."),0;for(let s=0;s<a.length&&!this.state.isIndexingCancelled;s+=this.embeddingBatchSize){await this.handlePause();let u=a.slice(s,s+this.embeddingBatchSize);try{await this.rateLimiter.wait();let l=await n.embedDocuments(u.map(f=>f.content));if(!l||l.length!==u.length)throw new Error(`Embedding model returned ${l?.length??0} embeddings for ${u.length} documents`);for(let f=0;f<u.length;f++){let p=u[f],m=l[f];if(!m||!Array.isArray(m)||m.length===0){ne(`Invalid embedding for document ${p.fileInfo.path}: ${m}`),this.dbOps.markFileMissingEmbeddings(p.fileInfo.path);continue}try{await this.dbOps.upsert({...p.fileInfo,id:this.getDocHash(p.content),content:p.content,embedding:m,created_at:Date.now(),nchars:p.content.length}),this.state.processedFiles.add(p.fileInfo.path)}catch(h){this.handleError(h,{filePath:p.fileInfo.path,errors:r}),this.dbOps.markFileMissingEmbeddings(p.fileInfo.path);continue}}this.state.indexedCount=this.state.processedFiles.size,this.updateIndexingNoticeMessage();let c=Math.floor((this.state.indexedCount-u.length)/this.checkpointInterval);Math.floor(this.state.indexedCount/this.checkpointInterval)>c&&(await this.dbOps.saveDB(),console.log("Copilot index checkpoint save completed."))}catch(l){if(this.handleError(l,{filePath:u?.[0]?.fileInfo?.path,errors:r,batch:u}),this.isRateLimitError(l))break}}return this.finalizeIndexing(r),setTimeout(()=>{this.dbOps.saveDB().then(()=>{B("Copilot index final save completed."),this.dbOps.checkIndexIntegrity().catch(s=>{ne("Background integrity check failed:",s)})}).catch(s=>{ne("Background save failed:",s)})},100),this.state.indexedCount}catch(n){return this.handleError(n),0}}async prepareAllChunks(e){let r=await this.embeddingsManager.getEmbeddingsAPI();if(!r)return console.error("Embedding instance not found."),[];let n=gd.getModelName(r),o=Sie.fromLanguage("markdown",{chunkSize:jz}),i=[];for(let a of e){let s=await this.app.vault.cachedRead(a);if(!s?.trim())continue;let u=this.app.metadataCache.getFileCache(a),l={title:a.basename,path:a.path,embeddingModel:n,ctime:a.stat.ctime,mtime:a.stat.mtime,tags:u?.tags?.map(d=>d.tag)??[],extension:a.extension,metadata:{...u?.frontmatter??{},created:eg(new Date(a.stat.ctime)).display,modified:eg(new Date(a.stat.mtime)).display}};(await o.createDocuments([s],[],{chunkHeader:`
`,appendChunkOverlapHeader:!0})).forEach(d=>{d.pageContent.trim()&&i.push({content:d.pageContent,fileInfo:l})})}return i}getDocHash(e){return(0,Igr.MD5)(e).toString()}async getFilesToIndex(e){let{inclusions:r,exclusions:n}=Xc(),o=this.app.vault.getMarkdownFiles();if(e)return o.filter(c=>bl(c,r,n));let i=new Set(await this.dbOps.getIndexedFiles()),a=await this.dbOps.getLatestFileMtime(),s=new Set(this.dbOps.getFilesMissingEmbeddings()),u=new Set,l=new Set;for(let c of o){if(!bl(c,r,n))continue;let d=await this.app.vault.cachedRead(c);if(!d||d.trim().length===0){l.add(c.path);continue}let f=i.has(c.path),p=s.has(c.path);(!f||p||c.stat.mtime>a)&&u.add(c)}return B([`Files to index: ${u.size}`,`Previously indexed: ${i.size}`,`Empty files skipped: ${l.size}`,`Files missing embeddings: ${s.size}`].join(`
`)),Array.from(u)}initializeIndexingState(e){this.state={isIndexingPaused:!1,isIndexingCancelled:!1,indexedCount:0,totalFilesToIndex:e,processedFiles:new Set,currentIndexingNotice:null,indexNoticeMessage:null}}createIndexingNotice(){let e=document.createDocumentFragment(),r=e.createEl("div",{cls:"copilot-notice-container"});this.state.indexNoticeMessage=r.createEl("div",{cls:"copilot-notice-message"}),this.updateIndexingNoticeMessage();let n=r.createEl("div",{cls:"copilot-notice-buttons"}),o=n.createEl("button");o.textContent="Pause",o.addEventListener("click",a=>{a.stopPropagation(),a.preventDefault(),this.state.isIndexingPaused?(this.resumeIndexing(),o.textContent="Pause"):(this.pauseIndexing(),o.textContent="Resume")});let i=n.createEl("button");return i.textContent="Stop",i.style.marginLeft="8px",i.addEventListener("click",a=>{a.stopPropagation(),a.preventDefault(),this.cancelIndexing()}),e.appendChild(this.state.indexNoticeMessage),e.appendChild(n),this.state.currentIndexingNotice=new bR.Notice(e,0),this.state.currentIndexingNotice}async handlePause(){if(this.state.isIndexingPaused){for(;this.state.isIndexingPaused&&!this.state.isIndexingCancelled;)await new Promise(e=>setTimeout(e,100));if(!this.state.isIndexingCancelled){let e=await this.getFilesToIndex();if(e.length===0){console.log("No files to index after filter change, stopping indexing"),this.cancelIndexing(),new bR.Notice("No files to index with current filters");return}this.state.totalFilesToIndex=e.length,console.log("Total files to index:",this.state.totalFilesToIndex),console.log("Files to index:",e),this.updateIndexingNoticeMessage()}}}pauseIndexing(){this.state.isIndexingPaused=!0}resumeIndexing(){this.state.isIndexingPaused=!1}updateIndexingNoticeMessage(){if(this.state.indexNoticeMessage){let e=this.state.isIndexingPaused?" (Paused)":"",r=["Copilot is indexing your vault...",`${this.state.indexedCount}/${this.state.totalFilesToIndex} files processed${e}`],n=ae(),o=O_(n.qaInclusions);o.length>0&&r.push(`Inclusions: ${o.join(", ")}`);let a=[...yie(this.app),...O_(n.qaExclusions)];a.length>0&&r.push(`Exclusions: ${a.join(", ")}`),this.state.indexNoticeMessage.textContent=r.join(`
`)}}isStringLengthError(e){if(!e)return!1;if(e instanceof RangeError&&e.message.toLowerCase().includes("string length"))return!0;let n=(e.message||e.toString()).toLowerCase();return n.includes("string length")||n.includes("rangeerror")}handleError(e,r){let n=r?.filePath;if(n?(r.batch?console.error("Batch processing error:",{error:e,batchSize:r.batch.length||0,firstChunk:r.batch[0]?{path:r.batch[0].fileInfo?.path,contentLength:r.batch[0].content?.length,hasFileInfo:!!r.batch[0].fileInfo}:"No chunks in batch",errorType:e?.constructor?.name,errorMessage:e?.message}):console.error(`Error indexing file ${n}:`,e),r.errors?.push(n)):console.error("Fatal error during indexing:",e),this.state.currentIndexingNotice&&this.state.currentIndexingNotice.hide(),this.isStringLengthError(e)){new bR.Notice("Vault is too large for 1 partition, please increase the number of partitions in your Copilot QA settings!",1e4);return}if(this.isRateLimitError(e))return;let o=n?`Error indexing file ${n}. Check console for details.`:"Fatal error during indexing. Check console for details.";new bR.Notice(o)}isRateLimitError(e){return e?.message?.includes?.("rate limit")||!1}finalizeIndexing(e){if(this.state.currentIndexingNotice&&this.state.currentIndexingNotice.hide(),this.state.isIndexingCancelled){new bR.Notice("Indexing cancelled");return}e.length>0?new bR.Notice(`Indexing completed with ${e.length} errors. Check console for details.`):new bR.Notice("Indexing completed successfully!")}async reindexFile(e){try{let r=await this.embeddingsManager.getEmbeddingsAPI();if(!r)return;if(await this.dbOps.removeDocs(e.path),await this.dbOps.checkAndHandleEmbeddingModelChange(r)){await this.indexVaultToVectorStore(!0);return}let o=await this.prepareAllChunks([e]);if(o.length===0)return;let i=await r.embedDocuments(o.map(a=>a.content));for(let a=0;a<o.length;a++){let s=o[a];await this.dbOps.upsert({...s.fileInfo,id:this.getDocHash(s.content),content:s.content,embedding:i[a],created_at:Date.now(),nchars:s.content.length})}this.dbOps.markUnsavedChanges(),ae().debug&&console.log(`Reindexed file: ${e.path}`)}catch(r){this.handleError(r,{filePath:e.path})}}async cancelIndexing(){console.log("Indexing cancelled by user"),this.state.isIndexingCancelled=!0,await new Promise(e=>setTimeout(e,100)),this.state.currentIndexingNotice&&this.state.currentIndexingNotice.hide()}}});var xg={};Rn(xg,{default:()=>D1});var Cie,D1,Am=v(()=>{Xw();aV();ot();Cie=require("obsidian");_ie();xgr();Rgr();D1=class t{constructor(){this.embeddingsManager=gd.getInstance(),this.dbOps=new yR(app),this.indexOps=new TTe(app,this.dbOps,this.embeddingsManager),this.eventHandler=new OTe(app,this.indexOps,this.dbOps),this.initializationPromise=this.initialize(),this.setupSettingsSubscription()}static getInstance(){return t.instance||(t.instance=new t),t.instance}setupSettingsSubscription(){this.lastKnownSettings={...ae()};let e=async()=>{let r=ae(),n=this.lastKnownSettings;if(this.lastKnownSettings={...r},r.enableIndexSync!==n?.enableIndexSync){let o=await this.dbOps.getDbPath();this.dbOps.getCurrentDbPath()!==o&&await this.dbOps.initializeDB(await this.embeddingsManager.getEmbeddingsAPI())}};al(()=>{this.initializationPromise=e()})}async initialize(){if(ae().enableSemanticSearchV3)try{let r=3;for(;r>0;)try{let n=await this.embeddingsManager.getEmbeddingsAPI();await this.dbOps.initializeDB(n);break}catch(n){if(n instanceof Ao&&n.message.includes("Vault adapter not available")&&(r--,r>0)){await new Promise(o=>setTimeout(o,100));continue}new Cie.Notice("Failed to initialize vector store. Please make sure you have a valid API key for your embedding model and restart the plugin."),console.error("Failed to initialize vector store:",n);break}}catch(r){console.error("Failed to initialize vector store:",r)}}async waitForInitialization(){await this.initializationPromise}async indexVaultToVectorStore(e){return await this.waitForInitialization(),Cie.Platform.isMobile&&ae().disableIndexOnMobile?(new Cie.Notice("Indexing is disabled on mobile devices"),0):this.indexOps.indexVaultToVectorStore(e)}async clearIndex(){a
</url_content>`),u.error&&(o[u.original]=u.error))}),{urlContext:r,imageUrls:n,processedErrorUrls:o}}asyncprocessUrls(e){letr=this.extractUrls(e);returnthis.processUrlList(r)}getMentions(){returnthis.mentions}clearMentions(){this.mentions.clear()}}});varUgr,MTe,Bgr=v(()=>{_t();Ugr=L(mV()),MTe=classt{constructor(){this.cacheDir=".copilot/pdf-cache"}staticgetInstance(){returnt.instance||(t.instance=newt),t.instance}asyncensureCacheDir(){awaitapp.vault.adapter.exists(this.cacheDir)||(B("Creating PDF cache directory:",this.cacheDir),awaitapp.vault.adapter.mkdir(this.cacheDir))}getCacheKey(e){letr=`${e.path}:${e.stat.size}:${e.stat.mtime}`,n=(0,Ugr.MD5)(r).toString();returnB("Generated cache key for PDF:",{path:e.path,key:n}),n}getCachePath(e){return`${this.cacheDir}/${e}.json`}asyncget(e){try{letr=this.getCacheKey(e),n=this.getCachePath(r);if(awaitapp.vault.adapter.exists(n)){B("Cache hit for PDF:",e.path);leto=awaitapp.vault.adapter.read(n);returnJSON.parse(o)}returnB("Cache miss for PDF:",e.path),null}catch(r){returnne("Error reading from PDF cache:",r),null}}asyncset(e,r){try{awaitthis.ensureCacheDir();letn=this.getCacheKey(e),o=this.getCachePath(n);B("Caching PDF response for:",e.path),awaitapp.vault.adapter.write(o,JSON.stringify(r))}catch(n){ne("Error writing to PDF cache:",n)}}asyncclear(){try{if(awaitapp.vault.adapter.exists(this.cacheDir)){lete=awaitapp.vault.adapter.list(this.cacheDir);B("Clearing PDF cache, removing files:",e.files.length);for(letrofe.files)awaitapp.vault.adapter.remove(r)}}catch(e){ne("Error clearing PDF cache:",e)}}}});function$1(t){if(!t||typeoft!="object")return!1;lete=t.message||t.toString();returne.includes("Request rate limit exceeded")||e.includes("RATE_LIMIT_EXCEEDED")||e.includes("429")||t.status===429}functionzgr(t){letr=(t?.message||t?.toString()||"").match(/Try again in ([\d\w\s]+)/);returnr?r[1]:"some time"}varxie=v(()=>{});varVgr,RTe,Hgr,ITe,Jgr=v(()=>{Vgr=require("obsidian"),ITe=class{constructor(e){this.vault=e;aqe(this,RTe)}asyncload(e){letr=awaitthis.vault.read(e),{nodes:n=[],edges:o=[]}=JSON.parse(r),i=awaitPromise.all(n.map(asyncu=>{if(u.type==="file"&&u.file){letl=this.vault.getAbstractFileByPath(u.file),c=linstanceofVgr.TFile?awaitthis.vault.cachedRead(l):"";return{...u,content:c}}returnu.type==="text"?{...u,content:u.text??""}:{...u,content:""}})),a=[...o];Awt(this,RTe,Hgr).call(this,i,a);lets=Object.fromEntries(i.map(u=>[u.id,u]));return{nodes:i,edges:a,byId:s}}buildPrompt(e){letr=newMap,n=e.nodes.filter(s=>s.type==="group");for(letsofn){letu=e.nodes.filter(l=>{if(l.id===s.id)return!1;letc=l.x+l.width/2,d=l.y+l.height/2;returnc>=s.x&&d>=s.y&&c<=s.x+s.width&&d<=s.y+s.height});r.set(s.label||s.id,u)}leto=`This canvas contains the following elements:
`,o}};RTe=newWeakSet,Hgr=function(e,r){letn=e.filter(o=>o.type==="group");for(letoofn)for(letiofe){if(i.id===o.id)continue;leta=i.x+i.width/2,s=i.y+i.height/2;a>=o.x&&s>=o.y&&a<=o.x+o.width&&s<=o.y+o.height&&r.push({id:crypto.randomUUID(),fromNode:o.id,toNode:i.id,label:"contains"})}}});varWgr,qot,ATe,Uot,sG,Oie,vk,NTe=v(()=>{Bgr();iG();_t();xie();Wgr=require("obsidian");Jgr();qot=class{constructor(){this.supportedExtensions=["md"]}asyncparseFile(e,r){returnawaitr.read(e)}},ATe=class{constructor(e){this.supportedExtensions=["pdf"];this.brevilabsClient=e,this.pdfCache=MTe.getInstance()}asyncparseFile(e,r){try{B("Parsing PDF file:",e.path);letn=awaitthis.pdfCache.get(e);if(n)returnB("Using cached PDF content for:",e.path),n.response;leto=awaitr.readBinary(e);B("Calling pdf4llm API for:",e.path);leti=awaitthis.brevilabsClient.pdf4llm(o);returnawaitthis.pdfCache.set(e,i),i.response}catch(n){returnne(`Error extracting content from PDF ${e.path}:`,n),`[Error: Could not extract content from PDF ${e.basename}]`}}asyncclearCache(){B("Clearing PDF cache"),awaitthis.pdfCache.clear()}},Uot=class{constructor(){this.supportedExtensions=["canvas"]}asyncparseFile(e,r){try{B("Parsing Canvas file:",e.path);letn=newITe(r),o=awaitn.load(e);returnn.buildPrompt(o)}catch(n){returnne(`Error parsing Canvas file ${e.path}:`,n),`[Error: Could not parse Canvas file ${e.basename}]`}}},sG=classsG{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=Yv.getInstance(),this.currentProject=r}staticresetRateLimitNoticeTimer(){sG.lastRateLimitNoticeTime=0}asyncparseFile(e,r){try{if(B(`[Docs4LLMParser] Project ${this.currentProject?.name}: Parsing ${e.extension} file: ${e.path}`),!this.currentProject)throwne("[Docs4LLMParser] No project context for parsing file: ",e.path),newError("No project context provided for file parsing");letn=awaitthis.projectContextCache.getOrReuseFileContext(this.currentProject,e.path);if(n)returnB(`[Docs4LLMParser] Project ${this.currentProject.name}: Using cached content for: ${e.path}`),n;B(`[Docs4LLMParser] Project ${this.currentProject.name}: Cache miss for: ${e.path}. Proceeding to API call.`);leto=awaitr.readBinary(e);B(`[Docs4LLMParser] Project ${this.currentProject.name}: Calling docs4llm API for: ${e.path}`);leti=awaitthis.brevilabsClient.docs4llm(o,e.extension);if(!i||!i.response)thrownewError("Empty response from docs4llm API");leta="";if(typeofi.response=="string")a=i.response;elseif(Array.isArray(i.response)){lets=[];for(letuofi.response)u.content&&(u.content.md?s.push(u.content.md):u.content.text&&s.push(u.content.text));a=s.join(`
`)}elsetypeofi.response=="object"?i.response.md?a=i.response.md:i.response.text?a=i.response.text:i.response.content?a=i.response.content:a=JSON.stringify(i.response,null,2):a=String(i.response);returnawaitthis.projectContextCache.setFileContext(this.currentProject,e.path,a),B(`[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),$1(n)&&this.showRateLimitNotice(n),n}}showRateLimitNotice(e){letr=Date.now();if(r-sG.lastRateLimitNoticeTime<6e4)return;sG.lastRateLimitNoticeTime=r;letn=zgr(e);newWgr.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(){B("Cache clearing is now handled at the project level")}};sG.lastRateLimitNoticeTime=0;Oie=sG,vk=class{constructor(e,r,n=!1,o=null){this.parsers=newMap;this.isProjectMode=n,this.currentProject=o,this.registerParser(newqot),this.registerParser(newOie(e,o)),n||this.registerParser(newATe(e)),this.registerParser(newUot)}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");einstanceofATe&&awaite.clearCache()}}});varWot={};Rn(Wot,{createToolCallMarker:()=>DTe,decodeResultFromMarker:()=>Vot,decodeToolCallMarkerResults:()=>Jlo,ensureEncodedToolCallMarkerResults:()=>jTe,parseToolCallMarkers:()=>Hot,updateToolCallMarker:()=>Jot});functionzot(t){try{return`ENC:${encodeURIComponent(t)}`}catch{returnt}}functionVot(t){if(typeoft!="string"||!t.startsWith("ENC:"))returnt;try{returndecodeURIComponent(t.slice(4))}catch{returnt}}functionHlo(t){return`Tool '${t}' ${Vlo}`}functionJlo(t){return!t||typeoft!="string"?t:t.replace(/<!--TOOL_CALL_END:([^:]+):(ENC:[\s\S]*?)-->/g,(e,r,n)=>{leto=Vot(n)||n;return`<!--TOOL_CALL_END:${r}:${o}-->`})}functionjTe(t){return!t||typeoft!="string"?t:t.replace(/<!--TOOL_CALL_END:([^:]+):([\s\S]*?)-->/g,(e,r,n)=>{if(n.startsWith("ENC:"))returne;leto=zot(n);return`<!--TOOL_CALL_END:${r}:${o}-->`})}functionBot(t,e=0,r=""){letn=[],o=/<errorChunk>([\s\S]*?)<\/errorChunk>/g,i=0,a;for(;(a=o.exec(t))!==null;){a.index>i&&n.push({type:"text",content:t.slice(i,a.index)});let[s,u]=a,l=e+a.index,c=r?`${r}-error-${l}`:`error-${l}`;n.push({type:"error",content:u,error:{id:c,errorContent:u,startIndex:l,endIndex:e+a.index+s.length}}),i=a.index+s.length}returni<t.length&&n.push({type:"text",content:t.slice(i)}),n.length===0&&n.push({type:"text",content:t}),n}functionHot(t,e){letr=[],n=/<!--TOOL_CALL_START:([^:]+):([^:]+):([^:]+):([^:]+):([^:]*):([^:]+)-->([\s\S]*?)<!--TOOL_CALL_END:\1:([\s\S]*?)-->/g,o=0,i;for(;(i=n.exec(t))!==null;){if(i.index>o){let_=t.slice(o,i.index);Bot(_,o,e).forEach(O=>{O.type==="text"&&O.content.trim()?r.push({type:"text",content:O.content}):O.type==="error"&&O.error&&r.push({type:"error",content:O.content,error:O.error})})}let[a,s,u,l,c,d,f,p,m]=i,y=Vot(typeofm=="string"?m:""),b=(typeofy=="string"?y.length:0)>5e3?Hlo(u):y??void0;r.push({type:"toolCall",content:p,toolCall:{id:s,toolName:u,displayName:l,emoji:c,confirmationMessage:d||void0,isExecuting:f==="true",result:b,startIndex:i.index,endIndex:i.index+a.length}}),o=i.index+a.length}if(o<t.length){leta=t.slice(o);Bot(a,o,e).forEach(u=>{u.type==="text"&&u.content.trim()?r.push({type:"text",content:u.content}):u.type==="error"&&u.error&&r.push({type:"error",content:u.content,error:u.error})})}returnr.length===0&&Bot(t,0,e).forEach(s=>{s.type==="text"?r.push({type:"text",content:s.content}):s.type==="error"&&s.error&&r.push({type:"error",content:s.content,error:s.error})}),{segments:r}}functionDTe(t,e,r,n,o="",i=!0,a="",s=""){letu=s&&zot(s);return`<!--TOOL_CALL_START:${t}:${e}:${r}:${n}:${o}:${i}-->${a}<!--TOOL_CAL
`,{turns:Array.isArray(c)?c.length:0});letd=2e3;try{let{parseToolCallMarkers:f}=awaitPromise.resolve().then(()=>(Tie(),Wot)),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;B(`Final AI response (truncated):
`,h)}catch{letf=typeofe=="string"?e:String(e??""),p=f.length>d?f.slice(0,d)+"... (truncated)":f;B(`Final AI response (truncated):
`,p)}returne}asynchandleError(e,r){letn=Sn(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&&B("[LayerToMessagesConverter] Added L2 (cumulative context) to system")),a.push({role:"system",content:f.join(`
`)}),i&&B("[LayerToMessagesConverter] Added L1 (System) + L2 (Cumulative) as stable prefix")}if(c&&c.text&&i&&B("[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:
`)}functionSk(t){let{messages:e,modelName:r,contextEnvelope:n}=t;try{lG={timestamp:newDate().toISOString(),modelName:r,serializedMessages:Glo(e),messagesArray:e,contextEnvelope:n}}catch{lG={timestamp:newDate().toISOString(),modelName:r,serializedMessages:String(e),messagesArray:e,contextEnvelope:n}}}functioncG(){lG=null}asyncfunction$Te(){if(!lG)return;let{timestamp:t,modelName:e,serializedMessages:r,messagesArray:n,contextEnvelope:o}=lG,i=[`### Prompt \u2014 ${t}${e?` \u2014 ${e}`:""}`,"","**Actual Messages Sent to LLM:**","","```json",r,"```",""],a=Xlo(n,o);i.push("**Layered Context Metadata:**"),i.push(""),i.push("```"),i.push(a),i.push("```"),i.push(""),ige(i),lG=null}varlG,F1=v(()=>{_t();yV();lG=null});functionGgr(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}}functionXgr(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}varZgr=v(()=>{});functionZlo(){return1e4}functionYlo(t,e){letr=e??Zlo();if(!t||t.length<=r)returnt;letn=t.substring(0,r),o=t.length-r;return`${n}
<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)}processChunk(e){if(this.shouldTruncate)return;Ggr(e).wasTruncated&&(this.wasTruncated=!0);letn=Xgr(e);n&&(this.tokenUsage=n);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.modelAdapter?.shouldTruncateStreaming?.(this.fullResponse)&&(this.shouldTruncate=!0,this.fullResponse=this.truncateToLastCompleteToolCall(this.fullResponse)),this.updateCurrentAiMessage(this.fullResponse)}truncateToLastCompleteToolCall(e){letr=e.lastIndexOf("</use_tool>");if(r===-1)returne;letn=e.substring(0,r+11);returnthis.modelAdapter?.sanitizeResponse?this.modelAdapter.sanitizeResponse(n,1):n}processErrorChunk(e){this.errorResponse=dG(e)}close(){returnthis.hasOpenThinkBlock&&(this.fullResponse+="</think>"),this.errorResponse&&(this.fullResponse+=this.errorResponse),this.updateCurrentAiMessage(this.fullResponse),{content:this.fullResponse,wasTruncated:this.wasTruncated,tokenUsage:this.tokenUsage}}}});varIie,Ygr=v(()=>{Or();Mie();_t();ot();Zt();Pie();uG();F1();bV();qs();Iie=classextendsL1{asyncconstructMessages(e){if(!e.contextEnvelope)thrownewError("[LLMChainRunner] Context envelope is required but not available. Cannot proceed with LLM chain.");B("[LLMChainRunner] Using envelope-based context");letr=vR.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();awaitwk(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=ae(),s=i_(),u=!1;try{u=!_O(s,a.activeModels).capabilities?.includes("reasoning")}catch(f){B("Could not determine model capabilities, defaulting to include thinking blocks",f)}letl=newT_(n,void0,u);try{letf=awaitthis.constructMessages(e),m=this.chainManager.chatModelManager.getChatModel()?.modelName;Sk({messages:f,modelName:m,contextEnvelope:e.contextEnvelope}),B(`Final Request to AI:
`,f);leth=awaitrh(()=>this.chainManager.chatModelManager.getChatModel().stream(f,{signal:r.signal}));forawait(letyofh){if(r.signal.aborted){B("Stream iteration aborted",{reason:r.signal.reason});break}l.processChunk(y)}}catch(f){f.name==="AbortError"||r.signal.aborted?B("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)}}});asyncfunctionFTe(t,e){letr=`Given the following conversation and a follow up question,
`,". "," ",""],keepSeparator:!1})}asyncgetChunks(e,r={}){try{if(!Array.isArray(e))returnBe("ChunkManager: Invalid notePaths provided"),[];if(e.length===0)return[];e.length>1e3&&(Be("ChunkManager: Too many note paths, limiting to 1000"),e=e.slice(0,1e3));letn=e.filter(a=>!(!a||typeofa!="string"||a.includes("..")||a.startsWith("/")));if(n.length===0)returnBe("ChunkManager: No valid note paths provided"),[];leto={...Zot,...r},i=[];for(letaofn){lets=this.cache.get(a);if(!s&&(s=awaitthis.generateChunksForNote(a,o),s.length>0)){letu=this.calculateChunkBytes(s);this.memoryUsage+u<=o.maxBytesTotal?(this.cache.set(a,s),this.memoryUsage+=u):Be(`ChunkManager: Skipping cache for ${a}, would exceed memory budget`)}i.push(...s)}returnB(`ChunkManager: Retrieved ${i.length} chunks from ${n.length} notes (${this.formatMemoryUsage()})`),i}catch(n){returnBe("ChunkManager: Failed to get chunks",n),[]}}asyncgetChunkText(e){return(awaitthis.ensureChunkExists(e))?.content||""}asyncensureChunkExists(e){let[r]=e.split("#"),o=(awaitthis.getValidatedChunks(r)).find(i=>i.id===e);returno||Be(`ChunkManager: Chunk ${e} not found after regeneration`),o||null}asyncgetValidatedChunks(e){letr=this.cache.get(e);if(!r&&(B(`ChunkManager: Cache miss for ${e}, regenerating...`),r=awaitthis.regenerateChunks(e),!r||r.length===0))returnBe(`ChunkManager: Failed to regenerate chunks for ${e}`),[];letn=this.app.vault.getAbstractFileByPath(e);returnn&&ninstanceofYot.TFile&&r.length>0&&n.stat.mtime>r[0].mtime&&(B(`ChunkManager: File ${e} modified, regenerating chunks`),r=awaitthis.regenerateChunks(e),!r||r.length===0)?(Be(`ChunkManager: Failed to regenerate chunks after modification for ${e}`),[]):r}getChunkTextSync(e){let[r]=e.split("#"),n=this.cache.get(r);returnn?n.find(i=>i.id===e)?.content||"":(Be(`ChunkManager: Chunk not in cache: ${e} (use async getChunkText for auto-regeneration)`),"")}asyncregenerateChunks(e){try{letr=awaitthis.generateChunksForNote(e,Zot);if(r.length>0){letn=this.calculateChunkBytes(r);if(this.memoryUsage+n<=Zot.maxBytesTotal){leto=this.cache.get(e);o&&(this.memoryUsage-=this.calculateChunkBytes(o)),this.cache.set(e,r),this.memoryUsage+=n}elseBe(`ChunkManager: Cannot cache regenerated chunks for ${e}, would exceed memory budget`)}returnr}catch(r){returnBe(`ChunkManager: Failed to regenerate chunks for ${e}`,r),[]}}clearCache(){this.cache.clear(),this.memoryUsage=0,B("ChunkManager: Cache cleared")}asyncgenerateChunksForNote(e,r){try{letn=this.app.vault.getAbstractFileByPath(e);if(!n||!(ninstanceofYot.TFile))return[];leto=awaitthis.safeReadFile(n);if(!o?.trim())return[];leta=(this.app.metadataCache.getFileCache(n)?.headings||[]).slice().sort((l,c)=>l.position.start.offset-c.position.start.offset),s=[],u=0;if(a.length===0){letl=awaitthis.processContentSection(o,"",n,u,r);returns.push(...l),s}for(letl=0;l<a.length;l++){letc=a[l],d=a[l+1],f=c.position.start.offset,p=d?.position.start.offset||o.length,m=o.substring(f,p),h=awaitthis.processContentSection(m,c.heading,n,u,r);s.push(...h),u+=h.length}returns}catch(n){returnBe(`ChunkManager: Failed to chunk note ${e}`,n),[]}}asyncprocessContentSection(e,r,n,o,i){leta=n.basename,s=[],u=`
`,l=u+e;if(l.length<=i.maxChars){letc=this.generateChunkId(n.path,o),d=this.calculateContentHash(l);s.push({id:c,notePath:n.path,chunkIndex:o,content:l,contentHash:d,title:a,heading:r,mtime:n.stat.mtime})}elsetry{(awaitthis.splitter.createDocuments([e],[],{chunkHeader:u,appendChunkOverlapHeader:i.overlap>0})).forEach((d,f)=>{letp=o+f,m=this.generateChunkId(n.path,p),h=this.calculateContentHash(d.pageContent);s.push({id:m,notePath:n.path,chunkIndex:p,content:d.pageContent,contentHash:h,title:a,heading:r,mtime:n.stat.mtime})})}catch(c){Be(`ChunkManager: Failed to split section in ${n.path}`,c);letd=this.generateChunkId(n.path,o),f=this.calculateContentHash(l);s.push({id:d,notePath:n.path,chunkIndex:o,content:l,contentHash:f,title:a,heading:r,mtime:n.stat.mtime})}returns}calculateChunkBytes(e){returne.reduce((r,n)=>r+Buffer.byteLength(n.content,"utf8"),0)}asyncsafeReadFile(e){try{return(awaitthis.app.vault.cachedRead(e))?.trim()||""}catch(r){returnBe(`ChunkManager: Failed to read ${e.path}`,r),""}}generateChunkId(e,r){return`${e}#${r}`}calculateContentHash(e){letr=e.length.toString(16),n=e.slice(0,32).replace(/\s/g,"").substring(0,8);returnr+n}formatMemoryUsage(){return`${(this.memoryUsage/1024/1024).toFixed(1)}MB`}}});varrco,nyr,oyr,Og,Rie,fG,nco,iyr,Aie,zTe,nit,Qot,oco,ayr,syr,ait,sit,uyr,ico,Nie,eit,aco,sco,uco,lco,tit,Qgr,cco,oit,iit,rit,dco,eyr,tyr,ryr,UTe,BTe,lyr,fco,cyr=v(()=>{rco="ENTRIES",nyr="KEYS",oyr="VALUES",Og="",Rie=class{constructor(e,r){letn=e._tree,o=Array.from(n.keys());this.set=e,this._type=r,this._path=o.length>0?[{node:n,keys:o}]:[]}next(){lete=this.dive();returnthis.backtrack(),e}dive(){if(this._path.length===0)return{done:!0,value:void0};let{node:e,keys:r}=fG(this._path);if(fG(r)===Og)return{done:!1,value:this.result()};letn=e.get(fG(r));returnthis._path.push({node:n,keys:Array.from(n.keys())}),this.dive()}backtrack(){if(this._path.length===0)return;lete=fG(this._path).keys;e.pop(),!(e.length>0)&&(this._path.pop(),this.backtrack())}key(){returnthis.set._prefix+this._path.map(({keys:e})=>fG(e)).filter(e=>e!==Og).join("")}value(){returnfG(this._path).node.get(Og)}result(){switch(this._type){caseoyr:returnthis.value();casenyr:returnthis.key();default:return[this.key(),this.value()]}}[Symbol.iterator](){returnthis}},fG=t=>t[t.length-1],nco=(t,e,r)=>{letn=newMap;if(e===void0)returnn;leto=e.length+1,i=o+r,a=newUint8Array(i*o).fill(r+1);for(lets=0;s<o;++s)a[s]=s;for(lets=1;s<i;++s)a[s*o]=s;returniyr(t,e,r,n,a,1,o,""),n},iyr=(t,e,r,n,o,i,a,s)=>{letu=i*a;e:for(letloft.keys())if(l===Og){letc=o[u-1];c<=r&&n.set(s,[t.get(l),c])}else{letc=i;for(letd=0;d<l.length;++d,++c){letf=l[d],p=a*c,m=p-a,h=o[p],y=Math.max(0,c-r-1),g=Math.min(a-1,c+r);for(letb=y;b<g;++b){let_=f!==e[b],w=o[m+b]++_,O=o[m+b+1]+1,T=o[p+b]+1,P=o[p+b+1]=Math.min(w,O,T);P<h&&(h=P)}if(h>r)continuee}iyr(t.get(l),e,r,n,o,c,a,s+l)}},Aie=classt{constructor(e=newMap,r=""){this._size=void0,this._tree=e,this._prefix=r}atPrefix(e){if(!e.startsWith(this._prefix))thrownewError("Mismatched prefix");let[r,n]=zTe(this._tree,e.slice(this._prefix.length));if(r===void0){let[o,i]=ait(n);for(letaofo.keys())if(a!==Og&&a.startsWith(i)){lets=newMap;returns.set(a.slice(i.length),o.get(a)),newt(s,e)}}returnnewt(r,e)}clear(){this._size=void0,this._tree.clear()}delete(e){returnthis._size=void0,oco(this._tree,e)}entries(){returnnewRie(this,rco)}forEach(e){for(let[r,n]ofthis)e(r,n,this)}fuzzyGet(e,r){returnnco(this._tree,e,r)}get(e){letr=nit(this._tree,e);returnr!==void0?r.get(Og):void0}has(e){letr=nit(this._tree,e);returnr!==void0&&r.has(Og)}keys(){returnnewRie(this,nyr)}set(e,r){if(typeofe!="string")thrownewError("key must be a string");returnthis._size=void0,Qot(this._tree,e).set(Og,r),this}getsize(){if(this._size)returnthis._size;this._size=0;lete=this.entries();for(;!e.next().done;)this._size+=1;returnthis._size}update(e,r){if(typeofe!="string")thrownewError("key must be a string");this._size=void0;letn=Qot(this._tree,e);returnn.set(Og,r(n.get(Og))),this}fetch(e,r){if(typeofe!=
`).map(l=>l.trim()),o=[r],i=new Set,a=null;for(let l of n)if(!(!l||l==="")){if(l.toUpperCase().includes("QUERIES")){a="queries";continue}if(l.toUpperCase().includes("TERMS")||l.toUpperCase().includes("KEYWORDS")){a="terms";continue}if(a==="queries"&&o.length<=this.config.maxVariants){let c=l.replace(/^[-•*\d.)\s]+/,"").trim();c&&c!==r&&o.push(c)}else if(a==="terms"){let c=l.replace(/^[-•*\d.)\s]+/,"").trim().toLowerCase();c&&this.isValidTerm(c)&&i.add(c)}}if(o.length===1&&i.size===0)for(let l of n.slice(0,this.config.maxVariants))l&&!l.toUpperCase().includes("QUERY")&&o.push(l);let s=this.extractSalientTermsFromOriginal(r),u=o.slice(1);return{queries:o.slice(0,this.config.maxVariants+1),salientTerms:s,originalQuery:r,expandedQueries:u.slice(0,this.config.maxVariants),expandedTerms:Array.from(i)}}fallbackExpansion(e){let r=this.extractTermsFromQueries([e]),n=mG(e),o=this.combineBaseAndTagTerms(r,n,e),i=new Set([e]);for(let s of o)if(!s.startsWith("#")&&s.length>=3){let u=WTe.generateVariants(s);for(let l of u.slice(0,3))if(l!==s){let c=e.toLowerCase().replace(new RegExp(`\\b${s}\\b`,"gi"),l);c!==e.toLowerCase()&&i.add(c)}}return{queries:[e],salientTerms:o,originalQuery:e,expandedQueries:[],expandedTerms:[]}}extractTermsFromQueries(e){let r=new Set;for(let n of e){let o=n.toLowerCase().replace(/[^\w\s-]/g," ").split(/\s+/);for(let i of o)this.isValidTerm(i)&&(r.add(i),i.includes("-")&&i.split("-").forEach(a=>{this.isValidTerm(a)&&r.add(a)}))}return Array.from(r)}isValidTerm(e){if(e.length<this.config.minTermLength)return!1;if(e.startsWith("#"))try{return/^#[\p{L}\p{N}_/-]+$/u.test(e)}catch{return/^#[A-Za-z0-9_/-]+$/.test(e)}try{return/^[\p{L}\p{N}_-]+$/u.test(e)}catch{return/^[A-Za-z0-9_-]+$/.test(e)}}combineBaseAndTagTerms(e,r,n){let o=new Set([...e,...r]);if(r.length===0)return Array.from(o);let i=this.collectStandaloneTerms(n);for(let a of r){let s=a.slice(1);s.length>0&&!i.has(s)&&o.delete(s)}return Array.from(o)}collectStandaloneTerms(e){let r=new Set;if(!e)return r;let n=e.toLowerCase(),o=this.findTagRanges(n),i=[/[\p{L}\p{N}_-]+/gu,/[a-z0-9_-]+/g];for(let a of i)try{for(let s of n.matchAll(a)){if(s.index===void 0)continue;let u=s.index,l=u+s[0].length;if(o.some(({start:f,end:p})=>u>=f&&l<=p))continue;let d=s[0];this.isValidTerm(d)&&!d.startsWith("#")&&(r.add(d),d.includes("-")&&d.split("-").forEach(f=>{this.isValidTerm(f)&&!f.startsWith("#")&&r.add(f)}))}break}catch{continue}return r}findTagRanges(e){let r=[],n=[/#[\p{L}\p{N}_/-]+/gu,/#[a-z0-9_/-]+/g];for(let o of n)try{for(let i of e.matchAll(o))i.index!==void 0&&r.push({start:i.index,end:i.index+i[0].length});break}catch{continue}return r}cacheResult(e,r){if(this.cache.size>=this.config.cacheSize){let n=this.cache.keys().next().value;n&&this.cache.delete(n)}this.cache.set(e,r)}clearCache(){this.cache.clear(),B("QueryExpander: Cache cleared")}getCacheSize(){return this.cache.size}async expandQueries(e){return(await this.expand(e)).queries}};GTe.PROMPT_TEMPLATE=`Analyzethissearchqueryandprovide:
`))}if(r.protocol==="http:"||r.protocol==="https:")return{type:"url",url:t};throw new Error([`InvalidimageURLprotocol:${JSON.stringify(r.protocol)}.Anthropiconlysupportsimagesashttp,https,orbase64-encodeddataURLson'image_url'contentblocks.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
`))}function bco(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 Hs({content:[{type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}]}))}else e.push(new Hs({content:[{type:"tool_result",...r.content!=null?{content:hit(r)}:{},tool_use_id:r.tool_call_id}]}));else e.push(r);return e}function zyr(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*_co(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){Ym(n)&&(yield Zx(n,Dyr));let o="cache_control"in n?n.cache_control:void 0;if(n.type==="image_url"){let i;typeof n.image_url=="string"?i=Byr(n.image_url):typeof n.image_url=="object"&&n.image_url!==null&&"url"in n.image_url&&typeof n.image_url.url=="string"&&(i=Byr(n.image_url.url)),i&&(yield{type:"image",source:i,...o?{cache_control:o}:{}})}else{if(jyr(n))return n;if(n.type==="document")yield{...n,...o?{cache_control:o}:{}};else if(Ryr(n))yield{type:"thinking",thinking:n.thinking,signature:n.signature,...o?{cache_control:o}:{}};else if(Ayr(n))yield{type:"redacted_thinking",data:n.data,...o?{cache_control:o}:{}};else if(Nyr(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 hit(t){let{content:e}=t;return typeof e=="string"?e:Array.from(_co(e))}function rEe(t){let e=bco(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(Pl(i)&&i.response_metadata?.output_version==="v1")return{role:a,content:qyr(i)};if(Pl(i)&&i.tool_calls?.length){if(typeof i.content=="string")return i.content===""?{role:a,content:i.tool_calls.map(zyr)}:{role:a,content:[{type:"text",text:i.content},...i.tool_calls.map(zyr)]};{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:hit(i)}}}else return{role:a,content:hit(i)}});return{messages:vco(o),system:r}}function vco(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 git=v(()=>{$yr();Uyr();Qa()});function Vyr(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}functionyit(t){lete;returnt.status===400&&t.message.includes("tool")?e=nEe(t,"INVALID_TOOL_RESULTS"):t.status===401?e=nEe(t,"MODEL_AUTHENTICATION"):t.status===404?e=nEe(t,"MODEL_NOT_FOUND"):t.status===429?e=nEe(t,"MODEL_RATE_LIMIT"):e=t,e}varWyr=v(()=>{});functionfr(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}functionMe(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)}varq1=v(()=>{});varbit,Kyr=v(()=>{bit=function(){let{crypto:t}=globalThis;if(t?.randomUUID)returnbit=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))}});functionU1(t){returntypeoft=="object"&&t!==null&&("name"int&&t.name==="AbortError"||"message"int&&String(t.message).includes("FetchRequestCanceledException"))}varFie,gG=v(()=>{Fie=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)}});varnn,_h,Tg,xk,yG,bG,_G,vG,wG,SG,CG,xG,OG,VC=v(()=>{gG();nn=classextendsError{},_h=classtextendsnn{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)returnnewxk({message:n,cause:Fie(r)});leti=r;returne===400?newbG(e,i,n,o):e===401?new_G(e,i,n,o):e===403?newvG(e,i,n,o):e===404?newwG(e,i,n,o):e===409?newSG(e,i,n,o):e===422?newCG(e,i,n,o):e===429?newxG(e,i,n,o):e>=500?newOG(e,i,n,o):newt(e,i,n,o)}},Tg=classextends_h{constructor({message:e}={}){super(void0,void0,e||"Request was aborted.",void0)}},xk=classextends_h{constructor({message:e,cause:r}){super(void0,void0,e||"Connection error.",void0),r&&(this.cause=r)}},yG=classextendsxk{constructor({message:e}={}){super({message:e??"Request timed out."})}},bG=classextends_h{},_G=classextends_h{},vG=classextends_h{},wG=classextends_h{},SG=classextends_h{},CG=classextends_h{},xG=classextends_h{},OG=classextends_h{}});functionwit(t){returntypeoft!="object"?{}:t??{}}functionXyr(t){if(!t)return!0;for(leteint)return!1;return!0}functionZyr(t,e){returnObject.prototype.hasOwnProperty.call(t,e)}varSco,Gyr,_it,vit,Yyr,oEe,CV=v(()=>{VC();Sco=/^[a-z][a-z0-9+.-]*:/i,Gyr=t=>Sco.test(t),_it=t=>(_it=Array.isArray,_it(t)),vit=_it;Yyr=(t,e)=>{if(typeofe!="number"||!Number.isInteger(e))thrownewnn(`${t} must be an integer`);if(e<0)thrownewnn(`${t} must be a positive integer`);returne},oEe=t=>{try{returnJSON.parse(t)}catch{return}}});varQyr,ebr=v(()=>{Qyr=t=>newPromise(e=>setTimeout(e,t))});varOk,Sit=v(()=>{Ok="0.65.0"});functionCco(){returntypeofDeno<"u"&&Deno.build!=null?"deno":typeofEdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeofglobalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}functionOco(){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"]);B1.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function Uie(){}function aEe(t,e,r){return!e||sEe[t]>sEe[r]?Uie:e[t].bind(e)}function vh(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Mco;let n=mbr.get(e);if(n&&n[0]===r)return n[1];let o={error:aEe("error",e,r),warn:aEe("warn",e,r),info:aEe("info",e,r),debug:aEe("debug",e,r)};return mbr.set(e,[r,o]),o}var sEe,Pit,Mco,mbr,z1,uEe=v(()=>{CV();sEe={off:0,error:200,warn:300,info:400,debug:500},Pit=(t,e,r)=>{if(t){if(Zyr(sEe,t))return t;vh(r).warn(`${e}wassetto${JSON.stringify(t)},expectedoneof${JSON.stringify(Object.keys(sEe))}`)}};Mco={error:Uie,warn:Uie,info:Uie,debug:Uie},mbr=new WeakMap;z1=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*Ico(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new nn("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 nn("Attempted to iterate over a response with no body");let r=new Mit,n=new B1,o=kie(t.body);for await(let i of Rco(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*Rco(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"?qie(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let i;for(;(i=pbr(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function Aco(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var Bie,wR,Mit,Iit=v(()=>{q1();VC();TG();Eit();TG();gG();CV();Tit();uEe();VC();wR=class t{constructor(e,r,n){this.iterator=e,Bie.set(this,void 0),this.controller=r,fr(this,Bie,n,"f")}static fromSSEResponse(e,r,n){let o=!1,i=n?vh(n):console;async function*a(){if(o)throw new nn("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let s=!1;try{for await(let u of Ico(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 _h(void 0,oEe(u.data)??u.data,void 0,e.headers)}s=!0}catch(u){if(U1(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 B1,u=kie(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 nn("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(U1(u))return;throw u}finally{s||r.abort()}}return new t(a,r,n)}[(Bie=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,Me(this,Bie,"f")),new t(()=>o(r),this.controller,Me(this,Bie,"f"))]}toReadableStream(){let e=this,r;return xit({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=qie(JSON.stringify(o)+`
${d}`)}returna},Cy=Bco(Sbr)});varPG,kit=v(()=>{SR();Tk();CR();fEe();EG();PG=classextends_d{list(e={},r){let{betas:n,...o}=e??{};returnthis._client.getAPIList("/v1/files",LS,{query:o,...r,headers:ea([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},r?.headers])})}delete(e,r={},n){let{betas:o}=r??{};returnthis._client.delete(Cy`/v1/files/${e}`,{...n,headers:ea([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString()},n?.headers])})}download(e,r={},n){let{betas:o}=r??{};returnthis._client.get(Cy`/v1/files/${e}/content`,{...n,headers:ea([{"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(Cy`/v1/files/${e}`,{...n,headers:ea([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString()},n?.headers])})}upload(e,r){let{betas:n,...o}=e;returnthis._client.post("/v1/files",gbr({body:o,...r,headers:ea([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},r?.headers])},this._client))}}});varMG,qit=v(()=>{SR();Tk();CR();EG();MG=classextends_d{retrieve(e,r={},n){let{betas:o}=r??{};returnthis._client.get(Cy`/v1/models/${e}?beta=true`,{...n,headers:ea([{...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",LS,{query:o,...r,headers:ea([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void0},r?.headers])})}}});varIG,Uit=v(()=>{VC();TG();Eit();IG=classt{constructor(e,r){this.iterator=e,this.controller=r}async*decoder(){lete=newB1;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"?newnn("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):newnn("Attempted to iterate over a response with no body");returnnewt(kie(e.body),r)}}});varJie=v(()=>{VC()});varRG,Bit=v(()=>{SR();Tk();CR();Uit();Jie();EG();RG=classextends_d{create(e,r){let{betas:n,...o}=e;returnthis._client.post("/v1/messages/batches?beta=true",{body:o,...r,headers:ea([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}retrieve(e,r={},n){let{betas:o}=r??{};returnthis._client.get(Cy`/v1/messages/batches/${e}?beta=true`,{...n,headers:ea([{"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",LS,{query:o,...r,headers:ea([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}delete(e,r={},n){let{betas:o}=r??{};returnthis._client.delete(Cy`/v1/messages/batches/${e}?beta=true`,{...n,headers:ea([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString()},n?.headers])})}cancel(e,r={},n){let{betas:o}=r??{};returnthis._client.post(Cy`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:ea([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString()},n?.headers])})}asyncresults(e,r={},n){leto=awaitthis.retrieve(e);if(!o.results_url)thrownewnn(`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:ea([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((a,s)=>IG.fromResponse(s.response,s.controller))}}});varzit=v(()=>{Iit()});varJco,AG,Wco,Kco,mEe,Vit=v(()=>{Jco=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=CEe[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:ea([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers]),stream:e.stream??!1})}stream(e,r){return SEe.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:ea([{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString()},r?.headers])})}toolRunner(e,r){return new DG(this._client,e,r)}};Mk.Batches=RG;Mk.BetaToolRunner=DG});var OR,Qit=v(()=>{SR();kit();kit();qit();qit();Yit();Yit();OR=class extends _d{constructor(){super(...arguments),this.models=new MG(this._client),this.messages=new Mk(this._client),this.files=new PG(this._client)}};OR.Models=MG;OR.Messages=Mk;OR.Files=PG});var EV,eat=v(()=>{SR();CR();EV=class extends _d{create(e,r){let{betas:n,...o}=e;return this._client.post("/v1/complete",{body:o,timeout:this._client._options.timeout??6e5,...r,headers:ea([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers]),stream:e.stream??!1})}}});function Nbr(t){return t.type==="tool_use"||t.type==="server_tool_use"}var kS,Ik,eae,OEe,tae,rae,TEe,nae,J1,oae,EEe,PEe,$G,MEe,IEe,tat,Ibr,rat,nat,oat,iat,Rbr,Abr,REe,jbr=v(()=>{q1();gG();Jie();zit();Vit();Abr="__json_buf";REe=class t{constructor(){kS.add(this),this.messages=[],this.receivedMessages=[],Ik.set(this,void 0),this.controller=new AbortController,eae.set(this,void 0),OEe.set(this,()=>{}),tae.set(this,()=>{}),rae.set(this,void 0),TEe.set(this,()=>{}),nae.set(this,()=>{}),J1.set(this,{}),oae.set(this,!1),EEe.set(this,!1),PEe.set(this,!1),$G.set(this,!1),MEe.set(this,void 0),IEe.set(this,void 0),rat.set(this,e=>{if(fr(this,EEe,!0,"f"),U1(e)&&(e=new Tg),e instanceof Tg)return fr(this,PEe,!0,"f"),this._emit("abort",e);if(e instanceof nn)return this._emit("error",e);if(e instanceof Error){let r=new nn(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new nn(String(e)))}),fr(this,eae,new Promise((e,r)=>{fr(this,OEe,e,"f"),fr(this,tae,r,"f")}),"f"),fr(this,rae,new Promise((e,r)=>{fr(this,TEe,e,"f"),fr(this,nae,r,"f")}),"f"),Me(this,eae,"f").catch(()=>{}),Me(this,rae,"f").catch(()=>{})}get response(){return Me(this,MEe,"f")}get request_id(){return Me(this,IEe,"f")}async withResponse(){let e=await Me(this,eae,"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")},Me(this,rat,"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{Me(this,kS,"m",nat).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)Me(this,kS,"m",oat).call(this,u);if(s.controller.signal?.aborted)throw new Tg;Me(this,kS,"m",iat).call(this)}finally{o&&i&&o.removeEventListener("abort",i)}}_connected(e){this.ended||(fr(this,MEe,e,"f"),fr(this,IEe,e?.headers.get("request-id"),"f"),Me(this,OEe,"f").call(this,e),this._emit("connect"))}get ended(){return Me(this,oae,"f")}get errored(){return Me(this,EEe,"f")}get aborted(){return Me(this,PEe,"f")}abort(){this.controller.abort()}on(e,r){return(Me(this,J1,"f")[e]||(Me(this,J1,"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=CEe[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 REe.createMessage(this,e,r)}countTokens(e,r){return this._client.post("/v1/messages/count_tokens",{body:e,...r})}},Dbr={"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"};Rk.Batches=LG});var PV,uat=v(()=>{SR();Tk();CR();EG();PV=class extends _d{retrieve(e,r={},n){let{betas:o}=r??{};return this._client.get(Cy`/v1/models/${e}`,{...n,headers:ea([{...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",LS,{query:o,...r,headers:ea([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers])})}}});var $br=v(()=>{_br();Qit();eat();sat();uat()});var iae,Lbr=v(()=>{iae=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 lat,cat,AEe,Fbr,kbr,qbr,mc,TR,dat=v(()=>{q1();Kyr();CV();ebr();gG();Cit();TG();lbr();Sit();VC();Tk();Fit();$br();cEe();eat();uat();Qit();sat();Cit();CR();Lbr();uEe();CV();kbr="\\n\\nHuman:",qbr="\\n\\nAssistant:",mc=class{constructor({baseURL:e=iae("ANTHROPIC_BASE_URL"),apiKey:r=iae("ANTHROPIC_API_KEY")??null,authToken:n=iae("ANTHROPIC_AUTH_TOKEN")??null,...o}={}){lat.add(this),AEe.set(this,void 0);let i={apiKey:r,authToken:n,...o,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&obr())throw new nn(`It looks like you're running in a browser-like environment.
`);this.baseURL=i.baseURL,this.timeout=i.timeout??cat.DEFAULT_TIMEOUT,this.logger=i.logger??console;leta="warn";this.logLevel=a,this.logLevel=Pit(i.logLevel,"ClientOptions.logLevel",this)??Pit(iae("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??abr(),fr(this,AEe,ubr,"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){returnea([awaitthis.apiKeyAuth(e),awaitthis.bearerAuth(e)])}asyncapiKeyAuth(e){if(this.apiKey!=null)returnea([{"X-Api-Key":this.apiKey}])}asyncbearerAuth(e){if(this.authToken!=null)returnea([{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)}=`;thrownewnn(`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 ${Ok}`}defaultIdempotencyKey(){return`stainless-node-retry-${bit()}`}makeStatusError(e,r,n,o){return_h.generate(e,r,n,o)}buildURL(e,r,n){leto=!Me(this,lat,"m",Fbr).call(this)&&n||this.baseURL,i=Gyr(e)?newURL(e):newURL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();returnXyr(a)||(r={...a,...r}),typeofr=="object"&&r&&!Array.isArray(r)&&(i.search=this.stringifyQuery(r)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)thrownewnn("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){returnnewxV(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(vh(this).debug(`[${l}] sending request`,z1({retryOfRequestLogID:n,method:o.method,url:s,options:o,headers:a.headers})),o.signal?.aborted)thrownewTg;letf=newAbortController,p=awaitthis.fetchWithTimeout(s,a,u,f).catch(Fie),m=Date.now();if(pinstanceofglobalThis.Error){letg=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)thrownewTg;letb=U1(p)||/timed? ?out/i.test(String(p)+("cause"inp?String(p.cause):""));if(r)returnvh(this).info(`[${l}] connection ${b?"timed out":"failed"} - ${g}`),vh(this).debug(`[${l}] connection ${b?"timed out":"failed"} (${g})`,z1({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(Pl(i)&&i.tool_calls?.length)returni.tool_calls.map(a=>({...a,id:yae(a.id??"")})).map(ck)},o=newSet;for(letioft)"tool_call_id"ini&&typeofi.tool_call_id=="string"&&o.add(yae(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:yae(i.tool_call_id)}];if(Pl(i)){if(a===void0)return[{role:e(i.getType()),content:s}];{letu=a.filter(l=>o.has(yae(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}]})}functionZ7o(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=Bat(r.content);switch(r.role){case"assistant":{leti=[],a=[];for(letsofn)try{letu=kC(s,{returnId:!0});i.push({...u,id:u.id??JEe().replace(/-/g,"")})}catch(u){a.push(AS(s,u.message))}returnneweo({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:returnnewHs({content:o})}}functionY7o(t,e){if(!t.content&&!t.toolCalls)returne?newIr({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??JEe().replace(/-/g,""),type:"function"})):void0,n="assistant";t.role&&(n=t.role);leto=Bat(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"?newmv({content:o}):n==="assistant"?newIr({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"?newIw({content:o,additional_kwargs:i,tool_call_id:r?.[0].id??""}):n==="function"?newpv({content:o,additional_kwargs:i}):newfv({content:o,role:n})}functionQkr(t){if(!(!t||!t.length))returnt.map(e=>{if("function"ine)return{type:e.type??"function",function:e.function};if(bg(e)){letr=e.description??`Tool: ${e.name}`;return{type:"function",function:{name:e.name,description:r,parameters:Ya(e.schema)?Ni(e.schema):e.schema}}}thrownewError(`Unknown tool type passed to ChatMistral: ${JSON.stringify(e,null,2)}`)})}vareqr,tqr,$ct,rqr=v(()=>{C_r();M_r();eqr=L(Ykr(),1),tqr=L(WG(),1);Qa();YI();id();GB();ku();fO();$8();_v();nb();g1();Wv();$ct=classextendsmd{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??vn("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"]);MH.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function Zct(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 Tqr=v(()=>{});async function*mXo(t,e){if(!t.body)throw e.abort(),new jr("Attempted to iterate over a response with no body");let r=new Yct,n=new MH,o=Zct(t.body);for await(let i of hXo(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*hXo(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=xqr(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function gXo(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var QR,Yct,r1e=v(()=>{Kse();uw();Oqr();Tqr();Ki();uw();QR=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 mXo(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 Fm(void 0,s.error,void 0,Qct(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 Fm(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 MH,s=Zct(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 Hct({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]=gXo(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function rdt(t,e,r){if(t=await t,Pqr(t))return t;if(Eqr(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=nue(o)?[await o.arrayBuffer()]:[o];return new ZNe(i,e,r)}let n=await bXo(t);if(e||(e=vXo(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new ZNe(n,e,r)}async function bXo(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(nue(t))e.push(await t.arrayBuffer());else if(wXo(t))for await(let r of t)e.push(r);else throw new Error(`Unexpecteddatatype:${typeoft};constructor:${t?.constructor?.name};props:${_Xo(t)}`);return e}function _Xo(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function vXo(t){return edt(t.name)||edt(t.filename)||edt(t.path)?.split(/[\\/]/).pop()}var Eqr,Pqr,nue,yXo,edt,wXo,ndt,u0,Mqr,tdt,n1e=v(()=>{Kse();Kse();Eqr=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",Pqr=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&nue(t),nue=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",yXo=t=>Pqr(t)||Eqr(t)||Kct(t);edt=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},wXo=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",ndt=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody",u0=async t=>{let e=await Mqr(t.body);return Jct(e,t)},Mqr=async t=>{let e=new Vct;return await Promise.all(Object.entries(t||{}).map(([r,n])=>tdt(e,r,n))),e},tdt=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(yXo(r)){let n=await rdt(r);t.append(e,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>tdt(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>tdt(t,`${e}[${n}]`,o)));else throw new TypeError(`Invalidvaluegiventoform,expectedastring,number,boolean,object,Array,FileorBlobbutgot${r}instead`)}}});async function Dqr(t){let{response:e}=t;if(t.options.stream)return vD("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):QR.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 vD("response",e.status,e.url,e.headers,a),$qr(a,e)}let i=await e.text();return vD("response",e.status,e.url,e.headers,i),i}function $qr(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 EXo(){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 Lqr(t){if(!t)return!0;for(let e in t)return!1;return!0}function Fqr(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Nqr(t,e){fo
\r `.includes(t[n]);)n++};returna()},Pdt=t=>BXo(t,Eh.ALL^Eh.NUM)});functionVXo(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:O,type:T,id:P,...M}=_,{arguments:I,name:j,...A}=O||{};if(P==null)thrownewjr(`missing choices[${d}].tool_calls[${w}].id
${b1e(t)}`);return{...M,id:P,type:T,function:{...A,name:j,arguments:I}}})}}:{...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}:{}};returnHqr(u,e)}functionb1e(t){returnJSON.stringify(t)}varZ9,vu,km,xD,Y9,Eq,Mdt,g1e,Idt,Rdt,Adt,y1e,Ndt,Yqr,Q9,jdt=v(()=>{uw();Odt();r1e();mue();Zqr();Z9=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},vu=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)},Q9=classtextendsX9{constructor(e){super(),km.add(this),xD.set(this,void0),Y9.set(this,void0),Eq.set(this,void0),Z9(this,xD,e,"f"),Z9(this,Y9,[],"f")}getcurrentChatCompletionSnapshot(){returnvu(this,Eq,"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())),vu(this,km,"m",Mdt).call(this);leti=awaite.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();forawait(letaofi)vu(this,km,"m",Idt).call(this,a);if(i.controller.signal?.aborted)thrownewnm;returnthis._addChatCompletion(vu(this,km,"m",y1e).call(this))}async_fromReadableStream(e,r){letn=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),vu(this,km,"m",Mdt).call(this),this._connected();leto=QR.fromReadableStream(e,this.controller),i;forawait(letaofo)i&&i!==a.id&&this._addChatCompletion(vu(this,km,"m",y1e).call(this)),vu(this,km,"m",Idt).call(this,a),i=a.id;if(o.controller.signal?.aborted)thrownewnm;returnthis._addChatCompletion(vu(this,km,"m",y1e).call(this))}[(xD=newWeakMap,Y9=newWeakMap,Eq=newWeakMap,km=newWeakSet,Mdt=function(){this.ended||Z9(this,Eq,void0,"f")},g1e=function(r){letn=vu(this,Y9,"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},vu(this,Y9,"f")[r.index]=n,n)},Idt=function(r){if(this.ended)return;letn=vu(this,km,"m",Yqr).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=vu(this,km,"m",g1e).call(this,i);i.finish_reason&&(vu(this,km,"m",Adt).call(this,i),a.current_tool_call_index!=null&&vu(this,km,"m",Rdt).call(this,i,a.current_tool_call_index));for(letsofo.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(vu(this,km,"m",Adt).call(this,i),a.current_tool_call_index!=null&&vu(this,km,"m",Rdt).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,B("[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:""}}});functionCUr(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&&yZo(r)&&(r=r.slice(xUr.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"){letO=parseInt(w,10);Number.isNaN(O)||t({type:"reconnect-interval",value:O})}}}functionyZo(t){returnxUr.every((e,r)=>t.charCodeAt(r)===e)}varxUr,OUr=v(()=>{xUr=[239,187,191]});var_7,TUr,bZo,_Zo,vZo,IUr,EUr,wZo,SZo,PUr,CZo,MUr,Fq,R1e=v(()=>{ot();hN();_7=require("obsidian");OUr();TUr="Iv1.b507a08c87ecfe98",bZo="https://github.com/login/device/code",_Zo="https://github.com/login/oauth/access_token",vZo="https://api.github.com/copilot_internal/v2/token",IUr="https://api.githubcopilot.com",EUr=`${IUr}/chat/completions`,wZo=`${IUr}/models`,SZo=60*1e3,PUr=60*60*1e3,CZo=3,MUr={401:"Authentication failed - token may be expired",403:"Access denied - check your Copilot subscription",429:"Rate limited - please wait before retrying"},Fq=classt{constructor(){this.abortController=null;this.refreshPromise=null;this.refreshAttempts=0;this.authGeneration=0}staticgetInstance(){returnt.instance||(t.instance=newt),t.instance}getAuthState(){lete=ae(),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:TUr,scope:"read:user"}).toString(),r=await(0,_7.requestUrl)({url:bZo,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)thrownewError("Authentication cancelled by user.");if(u++,o?.(u),awaitthis.delay(r*1e3,a.signal),a.signal.aborted||this.authGeneration!==i)thrownewError("Authentication cancelled by user.");letl=newURLSearchParams({client_id:TUr,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}).toString(),c=await(0,_7.requestUrl)({url:_Zo,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:l,throw:!1});if(a.signal.aborted||this.authGeneration!==i)thrownewError("Authentication cancelled by user.");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)thrownewError("Authentication cancelled by user.");returnt_({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_description?d.error_description:d.error)}}thrownewError("Device code expired. Please restart authentication.")}finally{
withoutCORSError:`+Sn(n)+`
withCORSError:`+Sn(o);throw new Error(i)}}}findModelByName(e){return ae().activeModels.find(n=>n.name===e)}};Zc.ANTHROPIC_THINKING_BUDGET_TOKENS=2048,Zc.REASONING_MODEL_TEMPERATURE=1;l0=Zc});var N1e={};Rn(N1e,{TieredLexicalRetriever:()=>GH});async function TZo(){try{if(!pft){let e=await Promise.resolve().then(()=>(v7(),NUr));pft=()=>e.default.getInstance()}return pft().getChatModel()}catch{return null}}var mft,pft,GH,w7=v(()=>{_t();ot();vb();Zt();tG();kTe();mft=require("obsidian");qTe();tEe();pft=null;GH=class extends vV{constructor(r,n){super();this.app=r;this.options=n;this.lc_namespace=["tiered_lexical_retriever"];this.searchCore=new eEe(r,TZo),typeof this.searchCore.getChunkManager=="function"?this.chunkManager=this.searchCore.getChunkManager():this.chunkManager=new Ck(r)}async getRelevantDocuments(r,n){try{if(this.options.timeRange)return this.getTimeRangeDocuments(r);let o=mL(r,this.app.vault),i=o.map(p=>p.basename),a=this.resolveTagTerms(r);if(this.options.returnAllTags&&a.length>0)return this.getAllTagDocuments(a,r,o);let s=[...new Set([...this.options.salientTerms,...i])];ae().debug&&B("TieredLexicalRetriever: Starting search",{query:r,salientTerms:s,maxK:this.options.maxK});let u=ae(),l=await this.searchCore.retrieve(r,{maxResults:this.options.returnAllTags?jm:this.options.maxK,salientTerms:s,enableLexicalBoosts:u.enableLexicalBoosts,returnAll:this.options.returnAllTags}),c=await this.getTitleMatches(o),d=await this.convertToDocuments(l),f=this.combineResults(d,c);return ae().debug&&B("TieredLexicalRetriever: Search complete",{totalResults:f.length,titleMatches:c.length,searchResults:l.length}),f}catch(o){return Be("TieredLexicalRetriever: Error during search",o),[]}}async getTimeRangeDocuments(r){if(!this.options.timeRange)return[];let{startTime:n,endTime:o}=this.options.timeRange,i=this.generateDailyNoteDateRange(n,o);ae().debug&&B("TieredLexicalRetriever: Generated daily note titles",{startTime:new Date(n).toISOString(),endTime:new Date(o).toISOString(),titlesCount:i.length,firstTitle:i[0],lastTitle:i[i.length-1]});let a=i.join(", "),s=mL(a,this.app.vault).filter(h=>!Q8(h)),l=(await this.getTitleMatches(s)).map(h=>(h.metadata.includeInContext=!0,h)),c=this.app.vault.getMarkdownFiles().filter(h=>!Q8(h)),d=[],f=this.options.returnAll?jm:Math.min(this.options.maxK,jm);for(let h of c)if(h.stat.mtime>=n&&h.stat.mtime<=o){if(s.some(y=>y.path===h.path))continue;if(d.length>=f)break;try{let y=await this.app.vault.cachedRead(h),g=this.app.metadataCache.getFileCache(h),b=(Date.now()-h.stat.mtime)/(1e3*60*60*24),_=Math.max(.3,Math.min(1,1-b/30));d.push(new Rm({pageContent:y,metadata:{path:h.path,title:h.basename,mtime:h.stat.mtime,ctime:h.stat.ctime,tags:g?.tags?.map(w=>w.tag)||[],includeInContext:!0,score:_,rerank_score:_,source:"time-filtered"}}))}catch(y){Be(`TieredLexicalRetriever:Failedtoreadfile${h.path}`,y)}}let p=new Map;for(let h of l)p.set(h.metadata.path,h);for(let h of d)p.has(h.metadata.path)||p.set(h.metadata.path,{...h,metadata:{...h.metadata,includeInContext:!0}});let m=Array.from(p.values()).sort((h,y)=>{let g=h.metadata.score||0;return(y.metadata.score||0)-g});return ae().debug&&B("TieredLexicalRetriever: Time range search complete",{timeRange:this.options.timeRange,dailyNotesFound:s.length,timeFilteredDocs:d.length,totalResults:m.length}),m}resolveTagTerms(r){let n=new Set,o=this.options.tagTerms??[];for(let i of o)typeof i=="string"&&i.startsWith("#")&&n.add(i.toLowerCase());if(n.size===0)for(let i of this.options.salientTerms??[])typeof i=="string"&&i.startsWith("#")&&n.add(i.toLowerCase());if(n.size===0)for(let i of this.extractTagsFromQuery(r))n.add(i);return Array.from(n)}extractTagsFromQuery(r){if(!r)return[];let n=null;try{n=r.match(/#[\p{L}\p{N}_/-]+/gu)}catch{n=r.match(/#[a-z0-9_/-]+/g)}if(!n)return[];let o=new Set;for(let i of n){let a=i.trim();a.length<=1||o.add(a.toLowerCase())}return Array.from(o)}async getAllTagDocuments(r,n,o){let i=ae(),a=r.join(" ")||n,s=await this.searchCore.retrieve(a,{maxResults:jm,candidateLimit:jm,salientTerms:r,enableLexicalBoosts:i.enableLexicalBoosts
Passage:`)}asyncgetRelevantDocuments(r,n){returnrh(async()=>{leto=mL(r,app.vault),i=o.map(h=>h.basename),a=[...newSet([...this.options.salientTerms,...i])],s=awaitthis.getExplicitChunks(o),u=r;n?.runName!=="no_hyde"&&(u=awaitthis.rewriteQuery(r));letl=awaitthis.getOramaChunks(u,a,this.options.textWeight),c=this.filterAndFormatChunks(l,s),d=c;if(c.length===0)returnae().debug&&console.log("No chunks found for query:",r),d;letf=c.reduce((h,y)=>{letg=y.metadata.score;returntypeofg=="number"&&!isNaN(g)?Math.max(h,g):h},0),p=c.every(h=>typeofh.metadata.score!="number"||isNaN(h.metadata.score)),m=this.options.useRerankerThreshold&&(f<this.options.useRerankerThreshold||p);returnm&&(d=(awaitpc.getInstance().rerank(r,c.map(y=>y.pageContent.slice(0,3e3)))).response.data.map(y=>({...c[y.index],metadata:{...c[y.index].metadata,rerank_score:y.relevance_score}}))),ae().debug&&(console.log("*** HYBRID RETRIEVER DEBUG INFO: ***"),n?.runName!=="no_hyde"&&(console.log(`
Explicit Chunks: `,s),console.log("Orama Chunks: ",l),console.log("Combined Chunks: ",c),console.log("Max Orama Score: ",f),m?console.log("Reranked Chunks: ",d):console.log("No reranking applied.")),d})}asyncrewriteQuery(r){try{returnawaitpge(async()=>{letn=awaitthis.queryRewritePrompt.format({question:r}),o=awaitrh(async()=>(awaitNm.instance.getCurrentChainManager().chatModelManager.getChatModelWithTemperature(0)).invoke(n));if(o&&"content"ino){leti=Az(o.content);returnJW(i)}returnconsole.warn("Unexpected rewrittenQuery format. Falling back to original query."),r},KW)}catch(n){returnconsole.error("Error in rewriteQuery:",n),r}}asyncgetExplicitChunks(r){letn=[];for(letoofr){leti=awaitD1.getInstance().getDb(),a=awaityR.getDocsByPath(i,o.path);if(a){lets=a.map(u=>newRm({pageContent:u.document.content,metadata:{...u.document.metadata,score:u.score,path:u.document.path,mtime:u.document.mtime,ctime:u.document.ctime,title:u.document.title,id:u.document.id,embeddingModel:u.document.embeddingModel,tags:u.document.tags,extension:u.document.extension,created_at:u.document.created_at,nchars:u.document.nchars}}));n.push(...s)}}returnn}asyncgetOramaChunks(r,n,o){leti;try{i=awaitthis.convertQueryToVector(r)}catch(l){throwconsole.error("Error in convertQueryToVector, please ensure your embedding model is working and has an adequate context length:",l,`
Query:`,r),l}leta=awaitD1.getInstance().getDb(),s={similarity:this.options.minSimilarityScore,limit:this.options.maxK,includeVectors:!0};if(n.length>0){letl;o||(o=.5),l=1-o;letc=!0;for(letdofn)if(!d.startsWith("#")){c=!1;break}c&&(ae().debug&&console.log("Tag only query detected, setting textWeight to 1 and vectorWeight to 0."),o=1,l=0),s.mode="hybrid",s.term=n.join(" "),s.vector={value:i,property:"embedding"},s.hybridWeights={text:o,vector:l}}elses.mode="vector",s.vector={value:i,property:"embedding"};if(this.options.timeRange){let{startTime:l,endTime:c}=this.options.timeRange,d=this.generateDailyNoteDateRange(l,c);B("Daily note date range:",d[0],d[d.length-1]);letf=mL(d.join(", "),app.vault),m=(awaitthis.getExplicitChunks(f)).map(_=>({..._,metadata:{..._.metadata,includeInContext:!0}}));B("Modified time range:",l,c),s.where={mtime:{between:[l,c]}};lety=(awaitx_(a,s)).hits.map(_=>newRm({pageContent:_.document.content,metadata:{..._.document.metadata,score:_.score,path:_.document.path,mtime:_.document.mtime,ctime:_.document.ctime,title:_.document.title,id:_.document.id,embeddingModel:_.document.embeddingModel,tags:_.document.tags,extension:_.document.extension,created_at:_.document.created_at,nchars:_.document.nchars}})),g=[...m,...y];returnArray.from(newSet(g.map(_=>_.metadata.id))).map(_=>g.find(w=>w.metadata.id===_)).filter(_=>_!==void0)}B(`Orama search params:
`,s);letu=awaitx_(a,s);return!u||!u.hits?(console.warn("Search results or hits are undefined"),[]):u.hits.map(l=>!l||!l.document?(console.warn("Invalid hit or document in search results"),null):((typeofl.score!="number"||isNaN(l.score))&&console.warn("NaN/invalid score detected:",{score:l.score,path:l.document.path,title:l.document.title}),newRm({pageContent:l.document.content||"",metadata:{...l.document.metadata||{},score:l.score,path:l.document.path||"",mtime:l.document.mtime,ctime:l.document.ctime,title:l.document.title||"",id:l.document.id,embeddingModel:l.document.embeddingModel,tags:l.document.tags||[],extension:l.document.extension,created_at:l.document.created_at,nchars:l.document.nchars}}))).filter(l=>l!==null)}asyncconvertQueryToVector(r){leto=await(awaitgd.getInstance().getEmbeddingsAPI()).embedQuery(r);if(o.length===0)thrownewError("Query embedding returned an empty vector");returno}generateDailyNoteDateRange(r,n){leto=[],i=newDate(r),a=newDate(n),s=newDate(i);for(;s<=a;)o.push(`[[${s.toLocaleDateString("en-CA")}]]`),s.setDate(s.getDate()+1);returno}filterAndFormatChunks(r,n){leto=this.options.minSimilarityScore,i=r.filter(u=>{letl=u.metadata.score;returntypeofl!="number"||isNaN(l)?!0:l>=o}),a=newSet(n.map(u=>u.pageContent)),s=[...n];for(letuofi){letl=u.pageContent;a.has(l)||(a.add(l),s.push(u))}returns.map(u=>({...u,metadata:{...u.metadata,includeInContext:!0}}))}}});vargft={};Rn(gft,{MergedSemanticRetriever:()=>Sue});varkq,Sue,D1e=v(()=>{j1e();tEe();w7();tG();kTe();kq=classkqextendsvV{constructor(r,n){super();this.app=r;this.options=n;this.lc_namespace=["merged_semantic_retriever"];this.originalMaxK=Math.max(1,n.maxK),this.returnAll=!!n.returnAll;leto=this.returnAll?jm:Math.min(this.originalMaxK*2,jm),i={...n,maxK:o,returnAll:this.returnAll,returnAllTags:n.returnAllTags,tagTerms:n.tagTerms};this.lexicalRetriever=newGH(r,i);leta=this.returnAll?jm:Math.min(this.originalMaxK*2,jm);this.semanticRetriever=newwue({minSimilarityScore:n.minSimilarityScore??.1,maxK:a,salientTerms:n.salientTerms,timeRange:n.timeRange,textWeight:n.textWeight,returnAll:this.returnAll,useRerankerThreshold:n.useRerankerThreshold})}asyncgetRelevantDocuments(r,n){let[o,i]=awaitPromise.all([this.lexicalRetriever.getRelevantDocuments(r,n),this.semanticRetriever.getRelevantDocuments(r,n)]),a=newMap;for(letlofo)this.insertResult(a,l,"lexical");for(letlofi)this.insertResult(a,l,"semantic");lets=Array.from(a.values()).sort((l,c)=>(c.metadata?.score??0)-(l.metadata?.score??0)),u=this.returnAll?jm:this.originalMaxK;returns.slice(0,u)}insertResult(r,n,o){leti=this.getDocumentKey(n),a=this.decorateDocument(n,o),s=r.get(i);if(!s){r.set(i,a);return}letu=s.metadata?.source,l=this.getDocumentScore(s),c=this.getDocumentScore(a);if(o==="lexical"){(u!=="lexical"||c>l)&&r.set(i,a);return}u!=="lexical"&&c>l&&r.set(i,a)}getDocumentKey(r){letn=r.metadata??{};returnn.chunkId||n.path||n.id||n.title||`${r.pageContent.slice(0,64)}::${r.pageContent.length}`}decorateDocument(r,n){leto={...r.metadata??{},source:n},i=this.extractBaseScore(o),a=n==="lexical"?kq.LEXICAL_WEIGHT:kq.SEMANTIC_WEIGHT,s=i*a;returnn==="lexical"&&this.hasTagMatch(o)&&(s*=kq.TAG_MATCH_BOOST),o.score=s,o.rerank_score=s,newRm({pageContent:r.pageContent,metadata:o})}extractBaseScore(r){letn=[r?.rerank_score,r?.score];for(letoofn)if(typeofo=="number"&&!Number.isNaN(o))returno;return0}getDocumentScore(r){letn=r.metadata?.score;returntypeofn=="number"&&!Number.isNaN(n)?n:0}hasTagMatch(r){letn=r?.explanation;if(!n)return!1;leto=n.lexicalMatches;returnArray.isArray(o)?o.some(i=>i?.field==="tags"):!1}};kq.LEXICAL_WEIGHT=1,kq.SEMANTIC_WEIGHT=1,kq.TAG_MATCH_BOOST=1.1;Sue=kq});function$Ur(t,e=!0){returne?`
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.
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: "The study found X [^1]" not "The study found X. [^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)
- DO NOT write long descriptions - keep titles concise`;PZo=20});varxue,UUr=v(()=>{Or();Xot();Mie();_t();w7();D1e();uit();ot();Zt();Pie();uG();Cue();F1();bV();qs();xue=classextendsL1{asyncrun(e,r,n,o,i){leta=ae(),s=i_(),u=!1;try{u=!_O(s,a.activeModels).capabilities?.includes("reasoning")}catch(p){B("Could not determine model capabilities, defaulting to include thinking blocks",p)}letl=newT_(n,void0,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(Y=>Y.id==="L5_USER")?.text||e.message,y=this.extractTagTerms(h);B("[VaultQA] Extracted tags before condensing:",y);letg=this.chainManager.memoryManager.getMemory(),b=awaitg.loadMemoryVariables({}),_=lge(b),w=h;_.length>0&&(B("[VaultQA] Condensing query with chat history for better retrieval"),w=awaitFTe(h,_),B("[VaultQA] Standalone question:",w));letO=ae(),T={minSimilarityScore:.01,maxK:O.maxSourceChunks,salientTerms:y.length>0?[...y]:[],timeRange:void0,textWeight:void0,returnAll:!1,useRerankerThreshold:void0},M=await(O.enableSemanticSearchV3?newSue(app,{...T,returnAll:y.length>0,returnAllTags:y.length>0,tagTerms:y}):newGH(app,{...T,returnAll:y.length>0,returnAllTags:y.length>0,tagTerms:y})).getRelevantDocuments(w);this.chainManager.storeRetrieverDocuments(M);letI=M.map(Y=>{letse=Y.metadata?.title||"Untitled",ie=Y.metadata?.path||se;return`<${hHe}>
`+I+LUr(V,O.enableInlineCitations);B("[VaultQA] Using envelope-based context construction with LayerToMessagesConverter");letJ=vR.convert(p,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),K=J.find(Y=>Y.role==="system");K&&j.push({role:Iz(A),content:K.content}),awaitwk(g,j);letue=J.find(Y=>Y.role==="user");if(ue){letY=q+`
`+ue.content;if(e.content&&Array.isArray(e.content)){letse=e.content.map(ie=>ie.type==="text"?{...ie,text:Y}:ie);j.push({role:"user",content:se})}elsej.push({role:"user",content:Y})}letoe=A?.modelName;Sk({messages:j,modelName:oe,contextEnvelope:e.contextEnvelope}),B(`Final Request to AI:
`,j);letG=awaitrh(()=>this.chainManager.chatModelManager.getChatModel().stream(j,{signal:r.signal}));forawait(letYofG){if(r.signal.aborted){B("VaultQA stream iteration aborted",{reason:r.signal.reason});break}l.processChunk(Y)}}catch(p){p.name==="AbortError"||r.signal.aborted?B("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=ae();if(!FUr(e))returne;letn=this.chainManager.getRetrievedDocuments(),o=RRt(n).map(i=>({title:i}));return$1e(e,o,r.enableInlineCitations)}extractTagTerms(e){returnmG(e)}}});varS7,k1e=v(()=>{S7=["@vault","@websearch","@composer","@memory"]});functionq1e(){returne_(qq,{store:pw})}functionzUr(){returndL(yft,{store:pw})}functionC7(){returnpw.get(qq)}functionXH(){returnpw.get(yft)}functionU1e(t){pw.set(qq,t)}functionZH(t){lete=pw.get(qq),r=e.findIndex(n=>n.title===t.title);if(r!==-1){letn=[...e];n[r]=t,pw.set(qq,n)}elsepw.set(qq,[...e,t])}functionx7(t){lete=pw.get(qq);pw.set(qq,e.filter(r=>r.title!==t))}functionUq(t){pw.set(yft,t)}functionOue(t){pw.set(BUr,t)}functionTue(){returnpw.get(BUr)}functionBq(t){bft.add(t)}functionzq(t){bft.delete(t)}functionED(t){returnbft.has(t)}functionB1e(){returnae().defaultSystemPromptTitle}functionVUr(){lett=C7(),e=XH();if(e){letn=t.find(o=>o.title===e);if(n)returnn.content}letr=B1e();if(r){letn=t.find(o=>o.title===r);if(n)returnn.content}return""}functionHUr(){lett=B1e();Uq(t)}function_ft(){Oue(!1),Uq("")}varpw,qq,yft,BUr,bft,YH=v(()=>{eC();eC();ot();pw=cL(),qq=Cc([]),yft=Cc(""),BUr=Cc(!1);bft=newSet});functionz1e(){returnVUr()||ae()?.userSystemPrompt||""}functionPD(){lett=z1e();if(Tue())returnt;letr=kRt;returnt?`${r}
<user_custom_instructions>
${t}
</user_custom_instructions>`:r}asyncfunctionMD(t){lete=PD();if(!t)returnB("No UserMemoryManager provided to getSystemPromptWithMemory"),e;letr=awaitt.getUserMemoryPrompt();returnr?`${r}
${e}`:e}varVq=v(()=>{ot();Or();_t();YH()});functionlx(){}functionJUr(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}functionWUr(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)}functionKUr(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)}functionvft(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)}functionwft(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}functionEue(t,e){returnvft(t,e,"")}functionV1e(t,e){returnwft(t,e,"")}functionGUr(t,e){returne.slice(0,UZo(t,e))}functionUZo(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}functionXUr(t,e,r,n){if(e&&r){varo=e.value.match(/^\s*/)[0],i=e.value.match(/\s*$/)[0],a=r.value.match(/^\s*/)[0],s=r.value.match(/\s*$/)[0];if(t){varu=WUr(o,a);t.value=wft(t.value,a,u),e.value=Eue(e.value,u),r.value=Eue(r.value,u)}if(n){varl=KUr(i,s);n.value=vft(n.value,s,l),e.value=V1e(e.value,l),r.value=V1e(r.value,l)}}elseif(r)t&&(r.value=r.value.replace(/^\s*/,"")),n&&(n.value=n.value.replace(/^\s*/,""));elseif(t&&n){varc=n.value.match(/^\s*/)[0],d=e.value.match(/^\s*/)[0],f=e.value.match(/\s*$/)[0],p=WUr(c,d);e.value=Eue(e.value,p);varm=KUr(Eue(c,p),f);e.value=V1e(e.value,m),n.value=vft(n.value,c,m),t.value=wft(t.value,c,c.slice(0,c.length-m.length))}elseif(n){varh=n.value.match(/^\s*/)[0],y=e.value.match(/\s*$/)[0],g=GUr(y,h);e.value=V1e(e.value,g)}elseif(t){varb=t.value.match(/\s*$/)[0],_=e.value.match(/^\s*/)[0],w=GUr(b,_);e.value=Eue(e.value,w)}}functionVZo(t,e){if(typeoft=="function")e.callback=t;elseif(t)for(varrint)t.hasOwnProperty(r)&&(e[r]=t[r]);returne}functionZUr(t,e,r){varn=VZo(r,{ignoreWhitespace:!0});returnK1e.diff(t,e,n)}functionSft(t){"@babel/helpers - typeof";returnSft=typeofSymbol=="function"&&typeofSymbol.iterator=="symbol"?function(e){returntypeofe}:function(e){returne&&typeofSymbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeofe},Sft(t)}functionCft(t,e,r,n,o){e=e||[],r=r||[],n&&(t=n(o,t));vari;for(i=0;i<e.length;i+=1)if(e[i]===t)returnr[i];vara;if(Object.prototype.toString.call(t)==="[object Array]"){for(e.push(t),a=newArray(t.length),r.push(a),i=0;i<t.length;i+=1)a[i]=Cft(t[i],e,r,n,o);returne.pop(),r.pop(),a}if(t&&t.toJSON&&(t=t.toJSON()),Sft(t)==="object"&&t!==null){e.push(t),a={},r.push(a);vars=[],u;for(uint)Object.prototype.hasOwnProperty.call(t,u)&&s.push(u);for(s.sort(),i=0;i<s.length;i+=1)u=s[i],a[u]=Cft(t[u],e,r,n,u);e.pop(),r.pop()}elsea=t;returna}functionYUr(t,e,r){returnJ1e.diff(t,e,r)}varIis,H1e,BZo,W1e,zZo,K1e,HZo,JZo,Pue,J1e,xft=v(()=>{lx.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.
`):l}functionYZo(t){lete=[],r=/-{3,}\s*SEARCH\s*(?:\r?\n)?/,n=/(?:\r?\n)?={3,}\s*(?:\r?\n)?/,o=/(?:\r?\n)?\+{3,}\s*REPLACE/,i=newRegExp(r.source+"([\\s\\S]*?)"+n.source+"([\\s\\S]*?)"+o.source,"g"),a;for(;(a=i.exec(t))!==null;){lets=a[1].trim(),u=a[2].trim();e.push({searchText:s,replaceText:u})}returne}varO7,GZo,Z1e,XZo,lBr,Eft=v(()=>{O7=require("obsidian");Tft();xft();sA();dx();Zt();ot();GZo=Ct.object({path:Ct.string().describe(`(Required) The path to the file to write to.
The path must be relative to the root of the vault.`),content:Ct.union([Ct.string(),Ct.object({}).passthrough()]).describe(`(Required) The content to write to the file. Can be either a string or an object.
}`),confirmation:Ct.preprocess(t=>{if(typeoft=="string"){lete=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}returnt},Ct.boolean()).optional().default(!0).describe("(Optional) Whether to ask for change confirmation with preview UI before writing changes. Default: true. Set to false to skip preview and apply changes immediately.")}),Z1e=Yl({name:"writeToFile",description:`Request to write content to a file at the specified path and show the changes in a Change Preview UI.
`,schema:GZo,handler:async({path:t,content:e,confirmation:r=!0})=>{letn=typeofe=="string"?e:JSON.stringify(e,null,2);if(ae().autoAcceptEdits||r===!1)try{lets=awaitsBr(t);returnawaitapp.vault.modify(s,n),JSON.stringify({result:"accepted",message:"File changes applied without preview. Do not retry or attempt alternative approaches to modify this file in response to the current user request."})}catch(s){returnJSON.stringify({result:"failed",message:`Error writing to file without preview: ${s?.message||s}`})}leta=awaituBr(t,n);returnJSON.stringify({result:a,message:`File change result: ${a}. Do not retry or attempt alternative approaches to modify this file in response to the current user request.`})},timeoutMs:0}),XZo=Ct.object({path:Ct.string().describe("(Required) The path of the file to modify (relative to the root of the vault and include the file extension)."),diff:Ct.string().describe(`(Required) One or more SEARCH/REPLACE blocks. Each block MUST follow this exact format with these exact markers:
- Wrong: Not matching whitespace/indentation exactly`)});lBr=Yl({name:"replaceInFile",description:"Request to replace sections of content in an existing file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a LARGE file.",schema:XZo,handler:async({path:t,diff:e})=>{letr=app.vault.getAbstractFileByPath(t);if(!r||!(rinstanceofO7.TFile))return`File not found at path: ${t}. Please check the file path and try again.`;try{letn=awaitapp.vault.read(r),o=n;if(n.length<3e3)return"File is too small to use this tool. Please use writeToFile instead.";leta=YZo(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}`;lets=0;for(letcofa){let{searchText:d,replaceText:f}=c,p=jue(o),m=jue(d);if(!p.includes(m))if(p.includes(m.trimEnd()))d=d.trimEnd(),f=f.trimEnd();elsereturn`Search text not found in file ${t} : "${d}".`;leth=o;o=ZZo(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(ae().autoAcceptEdits)try{returnawaitapp.vault.modify(r,o),JSON.stringify({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){returnJSON.stringify({result:"failed",blocksApplied:s,message:`Error applying changes without preview: ${c?.message||c}`})}letl=awaituBr(t,o);returnJSON.stringify({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.`}},timeoutMs:0})});varPft,Mft,RD,Y1e=v(()=>{Pft=require("obsidian"),Mft=t=>{switch(t){case"@vault":return"Search through your vault for relevant information";case"@websearch":return"Search the web for information";case"@composer":return"Edit existing notes or create new notes.";case"@memory":return"Save information to user memory";default:return""}},RD=class{staticasynccallTool(e,r){try{if(!e)thrownewError("Tool is undefined");letn=awaite.call(r);returnn??(console.warn(`Tool ${e.name} returned null/undefined result`),null)}catch(n){returnconsole.error("Error calling tool:",n),ninstanceofError?newPft.Notice(n.message):newPft.Notice("An error occurred while executing the tool. Check console for details."),null}}}});functionQ1e(t){lete=t.trim();if(!e)return"note";letr=e.match(/^\[\[([\s\S]+?)\]\]$/),n=r?r[1]:e,[o="",i=""]=n.split("|"),a=i.trim();if(a.length>0)returna;lets=o.trim(),[u]=s.split("#"),l=(u||s).trim()||e,c=l.split("/").filter(Boolean),d=c.length>0?c[c.length-1]:l;returnd.replace(/\.[^/.]+$/,"")||d||"note"}functionQZo(t){lete=t.trim();returne.length<=cBr?e:`${e.slice(0,cBr)}\u2026`}functioneYo(t){if(!t||typeoft!="object")returnnull;lete=typeoft.status=="string"?t.status:null,r=typeoft.message=="string"&&t.message.trim().length>0?QZo(t.message):null,n=typeoft.notePath=="string"?t.notePath:"",i=(typeoft.noteTitle=="string"&&t.noteTitle.trim().length>0?t.noteTitle.trim():Q1e(n))||Q1e(n);if(e==="invalid_path")returnr??`\u26A0\uFE0F Invalid note path "${i}"`;if(e==="not_found")returnr??`\u26A0\uFE0F Note "${i}" not found`;if(e==="not_unique"){letc=Array.isArray(t.candidates)?t.candidates.length:0;returnr||(c>0?`\u26A0\uFE0F Multiple matches for "${i}" (${c} candidates)`:`\u26A0\uFE0F Multiple matches for "${i}"`)}if(e==="empty")returnr??`\u26A0\uFE0F "${i}" contains no readable content`;if(e==="out_of_range"){if(r)returnr;letc=typeoft.totalChunks=="number"&&Number.isFinite(t.totalChunks)?t.totalChunks:null,d=typeoft.chunkIndex=="number"&&Number.isFinite(t.chunkIndex)?t.chunkIndex:null;if(d!==null&&c!==null){letf=Math.max(c-1,0);return`\u26A0\uFE0F Chunk ${d} exceeds available range (max index ${f})`}return"\u26A0\uFE0F Requested chunk is out of range"}leta=typeoft.chunkIndex=="number"&&Number.isFinite(t.chunkIndex)?t.chunkIndex:0,s=typeoft.totalChunks=="number"&&Number.isFinite(t.totalChunks)?t.totalChunks:null,u=!!t.hasMore,l=[`\u2705 Read "${i||"note"}"`];returns&&s>0?l.push(`chunk ${a+1} of ${s}`):l.push(`chunk ${a+1}`),u&&l.push("more available"),l.join(" \xB7 ")}varcBr,fx,Due=v(()=>{cBr=180;fx=class{staticformat(e,r){try{letn=r;if(typeofn=="string"&&n.startsWith("ENC:"))try{n=decodeURIComponent(n.slice(4))}catch{}leto;try{o=JSON.parse(n)}catch{o=n}switch(e){case"localSearch":returnthis.formatLocalSearch(o);case"webSearch":returnthis.formatWebSearch(o);case"youtubeTranscription":returnthis.formatYoutubeTranscription(o
`),n=["\u{1F310} Web Search Results"],o=!1,i=[],a=[];for(let s of r){if(s.includes("Sources:")){o=!0;continue}o?a.push(s):s.includes("Here are the web search results")||i.push(s)}return i.length>0&&(n.push(""),n.push(...i.filter(s=>s.trim()))),a.length>0&&(n.push(""),n.push("Sources:"),a.forEach(s=>{s.trim()&&n.push(s)})),n.join(`
${r.message}`;if(r.results&&Array.isArray(r.results)){let n=[`\u{1F4FA}YouTubeTranscripts(${r.total_urls}video${r.total_urls>1?"s":""})`];n.push("");for(let o of r.results){if(o.success){n.push(`\u{1F4F9}Video:${o.url}`),n.push("");let i=o.transcript.split(`
`),a=0;for(let s of i)if(s.trim()&&(s.match(/^\[(\d+:\d+)\]/)?(a>0&&n.push(""),n.push(`\u23F0${s}`)):n.push(`${s.trim()}`),a++,a>30)){n.push(""),n.push("... (transcript truncated for display)");break}o.elapsed_time_ms&&(n.push(""),n.push(`Processingtime:${(o.elapsed_time_ms/1e3).toFixed(1)}s`))}else n.push(`\u274CFailedtotranscribe:${o.url}`),n.push(`${o.message}`);n.push(""),n.push("---"),n.push("")}return n.join(`
`),i=0;for(let a of o)if(a.trim()&&(a.match(/^\[(\d+:\d+)\]/)?(i>0&&n.push(""),n.push(`\u23F0${a}`)):n.push(`${a.trim()}`),i++,i>50)){n.push(""),n.push("... (transcript truncated for display)");break}return r.elapsed_time_ms&&(n.push(""),n.push(`Processingtime:${(r.elapsed_time_ms/1e3).toFixed(1)}s`)),n.join(`
Generateatitleandsummaryforthisconversation:`,a=[new Qm(o),new Hs(i)];try{let u=(await r.invoke(a)).text,l=this.extractJsonFromResponse(u);try{let c=JSON.parse(l);return{title:c.title||"Untitled Conversation",summary:c.summary||"No summary available"}}catch(c){return ne("[UserMemoryManager] Failed to parse LLM response as JSON:",c),{title:"Untitled Conversation",summary:"Summary generation failed"}}}catch(s){return ne("[UserMemoryManager] Failed to extract title and summary:",s),{title:"Untitled Conversation",summary:"Summary generation failed"}}}}});var oYo,tje,Rft=v(()=>{sA();dx();eje();_t();v7();oYo=Ct.object({statement:Ct.string().min(1).describe("The user statement for explicitly updating saved memories")}),tje=Yl({name:"updateMemory",description:"Update the user memory when the user explicitly asks to update the memory",schema:oYo,handler:async({statement:t})=>{try{let e=new Hq(app),r=l0.getInstance().getChatModel(),n=await e.updateSavedMemory(t,r);return n.error?{success:!1,message:n.error}:{success:!0,message:`Memoryupdatedsuccessfullyinto${e.getSavedMemoriesFilePath()}:${n.content}`}}catch(e){return ne("[updateMemoryTool] Error updating memory:",e),{success:!1,message:`Failedtosavememory:${e.message}`}}}})});function rje(t){return t.replace(/\\/g,"/").toLowerCase()}function iYo(t){return t.replace(/\.[^/.]+$/,"")}function aYo(t,e){if(e.length===0)return!1;let n=rje(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=iYo(s);if(!s.includes(a)&&!u.includes(a))return!1}else if(!s.includes(a))return!1}return!0}function Nft(t){return/\.[^/]+$/.test(t)}async function sYo(t){let e=b=>{let _=app.vault.getAbstractFileByPath(b);return _ instanceof $ue.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(!Nft(b))for(let w of[".md",".canvas"]){let O=e(`${b}${w}`);if(O)return{type:"resolved",file:O}}}let c=app.metadataCache,d=u.trim();if(c&&d){let b=new Set([d]);if(!Nft(d))for(let _ of[".md",".canvas"])b.add(`${d}${_}`);for(let _ of b){let w=c.getFirstLinkpathDest?.(_,"");if(w instanceof $ue.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=rje(d),m=new Set([p]);if(!Nft(d))for(let b of[".md",".canvas"])m.add(rje(`${d}${b}`));for(let b of f){let _=rje(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=>aYo(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 uYo(t){try{return await app.vault.cachedRead(t)}catch(e){return Be(`readNote:failedtoread${t.path}`,e),""}}function lYo(){let t=new Map,e=app.vault.getMarkdownFiles?.()??[];for(let r of e)if(r instanceof $ue.TFile){let n=t.get(r.basename)??[];n.push(r),t.set(r.basename,n)}return t}function cYo(t,e,r){let n=t.trim();if(!n)return[];let o=new Map,i=app.metadataCache.getFirstLinkpathDest?.(n,e);if(i instanceof $ue.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 dYo(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=lYo());let p=cYo(d,e.path,o);n.set(f,{linkText:d,displayText:u?.trim()||d,section:c?.trim()||void 0,ca
`).trimEnd(),heading:d})}returni}var$ue,Aft,pYo,pBr,mBr=v(()=>{$ue=require("obsidian");sA();_t();dx();Aft=200;pYo=Ct.object({notePath:Ct.string().min(1).describe("Full path to the note (relative to the vault root) that needs to be read, such as 'Projects/plan.md'."),chunkIndex:Ct.preprocess(t=>{if(typeoft=="string"){lete=t.trim();if(e.length===0)return;letr=Number(e);returnNumber.isFinite(r)?r:t}returnt},Ct.number().int().min(0)).optional().describe("0-based chunk index to read. Omit to read the first chunk.")}),pBr=Yl({name:"readNote",description:"Read a single note in search v3 sized chunks. Use only when you already know the exact note path and need its contents.",schema:pYo,handler:async({notePath:t,chunkIndex:e=0})=>{letr=t.trim();if(r.startsWith("/"))return{notePath:r,status:"invalid_path",message:"Provide the note path relative to the vault root without a leading slash."};letn=awaitsYo(r);if(n.type==="not_found")returnBe(`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")returnBe(`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}))};leto=n.file,i=o.path,a=awaituYo(o),s=fYo(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};letl=s[e];B(`readNote: returning chunk ${l.chunkIndex} of ${u} for ${i}`);letc=l.chunkIndex<u-1,d=dYo(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:void0}}})});asyncfunctionjft(t,e,r){try{if(!t||!t.name)return{toolName:t?.name||"unknown",result:"Error: Invalid tool call - missing tool name",success:!1};leto=e.find(u=>u.name===t.name);if(!o){letu=e.map(l=>l.name).join(", ");return{toolName:t.name,result:`Error: Tool '${t.name}' not found. Available tools: ${u}. Make sure you have the tool enabled in the Agent settings.`,success:!1}}if(o.isPlusOnly&&!await$S())return{toolName:t.name,result:`Error: ${QH(t.name)} requires a Copilot Plus subscription`,success:!1};leti={...t.args};o.requiresUserMessageContent&&r&&(i._userMessageContent=r);leta=6e4;typeofo.timeoutMs=="number"&&(a=o.timeoutMs);lets;return!a||a===1/0?s=awaitRD.callTool(o,i):s=awaitPromise.race([RD.callTool(o,i),newPromise((u,l)=>setTimeout(()=>l(newError(`Tool execution timed out after ${a}ms`)),a))]),s==null?(Be(`Tool ${t.name} returned null/undefined result`),{toolName:t.name,result:JSON.stringify({message:"Tool executed but returned no result",status:"empty"}),success:!0}):{toolName:t.name,result:typeofs=="string"?s:JSON.stringify(s),success:!0}}catch(o){returnne(`Error executing tool ${t.name}:`,o),{toolName:t.name,result:`Error: ${Sn(o)}`,success:!1}}}functionQH(t){returnt==="localSearch"?ae().enableSemanticSearchV3?"vault search (semantic)":"vault search (index-free)":{webSearch:"web search",getFileTree:"file tree",getCurrentTime:"current time",getTimeRangeMs:"time range",getTimeInfoByEpoch:"time info",convertTimeBetweenTimezones:"timezone converter",startPomodoro:"pomodoro timer",pomodoroTool:"pomodoro timer",youtubeTranscription:"YouTube transcription",indexVault:"vault indexing",indexTool:"index",writeToFile:"file editor",replaceInFile:"file editor"}[t]||t}functionE7(t){return{localSearch:"\u{1F50D}",webSearch:"\u{1F310}",getFileTree:"\u{1F4C1}",getCurrentTime:"\u{1F552}",getTimeRangeMs:"\u{1F4C5}",getTimeInfoByEpoch:"\u{1F570}\uFE0F",convertTimeBetweenTimezones:"\u{1F30D}",youtubeTranscription:"\u{1F4FA}",indexVault:"\u{1F4DA}",indexTool:"\u{1F4DA}",writeToFile:"\u270F\uFE0F",replaceInFile:"\u{1F504}",readNote:
${JSON.stringify(t)}`}var kft,yYo,gBr,bYo,_Br,vBr=v(()=>{sA();dx();kft=5e5,yYo=500,gBr=50,bYo=Ct.object({includeInline:Ct.boolean().optional().describe("Include inline tags in addition to frontmatter tags. Defaults to true."),maxEntries:Ct.number().int().positive().max(5e3).optional().describe("Maximum number of tag entries to return, sorted by occurrences. Responses are capped at ~500KB.")}).describe("Parameters for retrieving the tag list.");_Br=()=>Yl({name:"getTagList",description:"Get the list of tags in the vault with occurrence statistics.",schema:bYo,handler:async t=>{let e=_Yo(),r=t?.includeInline??!0,n=t?.maxEntries??yYo;if(!e)return bBr({totalUniqueTags:0,returnedTagCount:0,totalOccurrences:0,includedSources:r?["frontmatter","inline"]:["frontmatter"],truncated:!1,tags:[],note:"Metadata cache is unavailable. Try again after the vault finishes indexing."});let o=vYo(e,r,n),i=wYo(o);return bBr(i)},isBackground:!0})});var wBr=S((qft,Uft)=>{(function(t,e){typeof qft=="object"&&typeof Uft<"u"?Uft.exports=e():typeof define=="function"&&define.amd?define(e):(t=typeof globalThis<"u"?globalThis:t||self).dayjs_plugin_quarterOfYear=e()})(qft,function(){"use strict";var t="month",e="quarter";return function(r,n){var o=n.prototype;o.quarter=function(s){return this.$utils().u(s)?Math.ceil((this.month()+1)/3):this.month(this.month()%3+3*(s-1))};var i=o.add;o.add=function(s,u){return s=Number(s),this.$utils().p(u)===e?this.add(3*s,t):i.bind(this)(s,u)};var a=o.startOf;o.startOf=function(s,u){var l=this.$utils(),c=!!l.u(u)||u;if(l.p(s)===e){var d=this.quarter()-1;return c?this.month(3*d).startOf(t).startOf("day"):this.month(3*d+2).endOf(t).endOf("day")}return a.bind(this)(s,u)}}})});var Wq=S((Bft,zft)=>{(function(t,e){typeof Bft=="object"&&typeof zft<"u"?zft.exports=e():typeof define=="function"&&define.amd?define(e):(t=typeof globalThis<"u"?globalThis:t||self).dayjs=e()})(Bft,function(){"use strict";var t=1e3,e=6e4,r=36e5,n="millisecond",o="second",i="minute",a="hour",s="day",u="week",l="month",c="quarter",d="year",f="date",p="Invalid Date",m=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,h=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,y={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(k){var V=["th","st","nd","rd"],q=k%100;return"["+k+(V[(q-20)%10]||V[q]||V[0])+"]"}},g=function(k,V,q){var J=String(k);return!J||J.length>=V?k:""+Array(V+1-J.length).join(q)+k},b={s:g,z:function(k){var V=-k.utcOffset(),q=Math.abs(V),J=Math.floor(q/60),K=q%60;return(V<=0?"+":"-")+g(J,2,"0")+":"+g(K,2,"0")},m:function k(V,q){if(V.date()<q.date())return-k(q,V);var J=12*(q.year()-V.year())+(q.month()-V.month()),K=V.clone().add(J,l),ue=q-K<0,oe=V.clone().add(J+(ue?-1:1),l);return+(-(J+(q-K)/(ue?K-oe:oe-K))||0)},a:function(k){return k<0?Math.ceil(k)||0:Math.floor(k)},p:function(k){return{M:l,y:d,w:u,d:s,D:f,h:a,m:i,s:o,ms:n,Q:c}[k]||String(k||"").toLowerCase().replace(/s$/,"")},u:function(k){return k===void 0}},_="en",w={};w[_]=y;var O="$isDayjsObject",T=function(k){return k instanceof j||!(!k||!k[O])},P=function k(V,q,J){var K;if(!V)return _;if(typeof V=="string"){var ue=V.toLowerCase();w[ue]&&(K=ue),q&&(w[ue]=q,K=ue);var oe=V.split("-");if(!K&&oe.length>1)return k(oe[0])}else{var G=V.name;w[G]=V,K=G}return!J&&K&&(_=K),K||!J&&_},M=function(k,V){if(T(k))return k.clone();var q=typeof V=="object"?V:{};return q.date=k,q.args=arguments,new j(q)},I=b;I.l=P,I.i=T,I.w=function(k,V){return M(k,{locale:V.$L,utc:V.$u,x:V.$x,$offset:V.$offset})};var j=function(){function k(q){this.$L=P(q.locale,null,!0),this.parse(q),this.$x=this.$x||q.x||{},this[O]=!0}var V=k.prototype;return V.parse=function(q){this.$d=function(J){var K=J.date,ue=J.utc;if(K===null)return new Date(NaN);if(I.u(K))return new Date;if(K instanceof Date)return new Date(K);if(typeof K=="string"&&!/Z$/i.test(K)){var oe=K.match(m);if(oe){var G=oe[2]-1||0,Y=
- Los Angeles: UTC-8 (UTC-7 during DST)`)}),handler:async({timezoneOffset:t})=>nti(t),isBackground:!0}),d2r={jan:1,january:1,feb:2,february:2,mar:3,march:3,apr:4,april:4,may:5,jun:6,june:6,jul:7,july:7,aug:8,august:8,sep:9,september:9,oct:10,october:10,nov:11,november:11,dec:12,december:12};f2r=Yl({name:"getTimeRangeMs",description:"Convert natural language time expressions to date ranges for use with localSearch",schema:Ct.object({timeExpression:Ct.string().describe(`Natural language time expression to convert to a date range.
3. Then use the returned time range with localSearch`)}),handler:async({timeExpression:t})=>dti(t),isBackground:!0});p2r=Yl({name:"getTimeInfoByEpoch",description:"Convert a Unix timestamp (in seconds or milliseconds) to detailed time information",schema:Ct.object({epoch:Ct.number().describe("Unix timestamp in seconds or milliseconds")}),handler:async({epoch:t})=>fti(t),isBackground:!0});m2r=Yl({name:"convertTimeBetweenTimezones",description:"Convert a specific time from one timezone to another using UTC offsets",schema:Ct.object({time:Ct.string().describe(`Time to convert. Supports various formats:
- "what is 9am Beijing time in New York" \u2192 time: "9am", fromOffset: "+8", toOffset: "-5"`)}),handler:async({time:t,fromOffset:e,toOffset:r})=>pti(t,e,r),isBackground:!0})});var g2r,y2r,b2r=v(()=>{mR();Zt();sA();dx();g2r=5e4,y2r=Yl({name:"youtubeTranscription",description:"Get transcripts of YouTube videos when the user provides YouTube URLs",schema:Ct.object({}),isPlusOnly:!0,requiresUserMessageContent:!0,handler:async t=>{let{_userMessageContent:e}=t;if(typeof e!="string")return JSON.stringify({success:!1,message:"Invalid input: User message must be a string"});if(e.length>g2r)return JSON.stringify({success:!1,message:`Input too long: Maximum allowed length is ${g2r} characters`});let r=jRt(e);if(r.length===0)return JSON.stringify({success:!1,message:"No YouTube URLs found in the user prompt. URLs must be in the user prompt instead of the context notes."});let n=await Promise.all(r.map(async i=>{try{let a=await pc.getInstance().youtube4llm(i);return a.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){return console.error(`Error transcribing YouTube video ${i}:`,a),{url:i,success:!1,message:"An error occurred while transcribing the YouTube video"}}})),o=n.some(i=>i.success);return JSON.stringify({success:o,results:n,total_urls:r.length})}})});function hti(t){bd.getInstance().register({tool:dBr(t.getRoot()),metadata:{id:"getFileTree",displayName:"File Tree",description:"Browse vault file structure",category:"file",isAlwaysEnabled:!0,requiresVault:!0,customPromptInstructions:`For getFileTree:
</use_tool>`}})}function yti(){bd.getInstance().register({tool:tje,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_tool>`}})}function tX(t){let e=bd.getInstance(),r=ae(),n=e.getToolMetadata("getFileTree")!==void 0,o=t!==void 0,i=e.getToolMetadata("updateMemory")!==void 0,a=r.enableSavedMemory;(e.getAllTools().length===0||n!==o||i!==a)&&(e.clear(),e.registerAll(mti),t&&(hti(t),gti()),r.enableSavedMemory&&yti())}var mti,Dje=v(()=>{ot();Eft();fBr();Rft();mBr();Fft();vBr();h2r();yV();b2r();mti=[{tool:nje,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):
</use_tool>`}},{tool:oje,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:
</use_tool>`}},{tool:c2r,metadata:{id:"getCurrentTime",displayName:"Get Current Time",description:"Get the current time in any timezone",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For time queries (IMPORTANT: Always use UTC offsets, not timezone names):
</use_tool>`}},{tool:p2r,metadata:{id:"getTimeInfoByEpoch",displayName:"Get Time Info",description:"Convert epoch timestamp to human-readable format",category:"time",isAlwaysEnabled:!0}},{tool:f2r,metadata:{id:"getTimeRangeMs",displayName:"Get Time Range",description:"Convert time expressions to date ranges",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For time-based queries:
</use_tool>`}},{tool:m2r,metadata:{id:"convertTimeBetweenTimezones",displayName:"Convert Timezones",description:"Convert time between different timezones",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For timezone conversions:
</use_tool>`}},{tool:pBr,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:
-Decidebasedontheuser'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'tneed.
</use_tool>`}},{tool:Z1e,metadata:{id:"writeToFile",displayName:"Write to File",description:"Create or modify files in your vault",category:"file",requiresVault:!0,copilotCommands:["@composer"],customPromptInstructions:`For writeToFile:
`}},{tool:lBr,metadata:{id:"replaceInFile",displayName:"Replace in File",description:"Make targeted changes to existing files using SEARCH/REPLACE blocks",category:"file",requiresVault:!0,customPromptInstructions:`ForreplaceInFile:
`)}function Fje(t){let e=["find","search","look for","look up","my notes","in my vault","from my vault","check the web","search online","from the internet","current time","what time","timer","youtube","video","transcript"],r=t.toLowerCase();return e.some(n=>r.includes(n))}var omt,lJ,tmt,rmt,nmt,hU,Xle=v(()=>{_t();omt=50;lJ=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(`
`}],l=r.trim();return l.length>0&&u.push({id:"tool-descriptions",label:"Tool XML parameter descriptions",source:"src/LLMProviders/chainRunner/AutonomousAgentChainRunner.ts#generateToolDescriptions",content:`Availabletools:
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.
NOTE: Use individual XML parameter tags. For arrays, use JSON format like ["item1", "item2"].`}),u}enhanceUserMessage(e,r){returne}needsSpecialHandling(){return!1}},tmt=classextendslJ{isGPT5Model(){returnthis.modelName.includes("gpt-5")||this.modelName.includes("gpt5")}buildSystemPromptSections(e,r,n,o){leti=super.buildSystemPromptSections(e,r,n,o),a=n||[],s=a.includes("writeToFile")||a.includes("replaceInFile"),u=[];this.isGPT5Model()?u.push(`GPT-5 SPECIFIC RULES:
- Use maximum 2 tool calls initially, then provide an answer
- Call each tool ONCE per unique query
- For optional parameters: OMIT them entirely if not needed (don't pass empty strings/null)
- For localSearch: OMIT timeRange if not doing time-based search
Example localSearch without time:
<use_tool>
<name>localSearch</name>
<query>piano notes</query>
<salientTerms>["piano", "notes"]</salientTerms>
</use_tool>`):u.push("CRITICAL FOR GPT MODELS: You MUST ALWAYS include XML tool calls in your response. Do not just describe what you plan to do - you MUST include the actual XML tool call blocks."),s&&u.push(`\u{1F6A8} FILE EDITING WITH COMPOSER TOOLS - GPT SPECIFIC EXAMPLES \u{1F6A8}
When user asks you to edit or modify a file, you MUST:
1. Determine if it's a small edit (use replaceInFile) or major rewrite (use writeToFile)
2. Include the tool call immediately in your response
EXAMPLE 1 - User says "fix the typo 'teh' to 'the' in my note":
\u2705 CORRECT RESPONSE:
"I'll fix the typo in your note.
<use_tool>
<name>replaceInFile</name>
<path>path/to/note.md</path>
<diff>
------- SEARCH
teh
=======
the
+++++++ REPLACE
</diff>
</use_tool>"
EXAMPLE 2 - User says "add item 4 to the list":
\u2705 CORRECT RESPONSE:
"I'll add item 4 to your list.
<use_tool>
<name>replaceInFile</name>
<path>path/to/file.md</path>
<diff>
------- SEARCH
- Item 1
- Item 2
- Item 3
=======
- Item 1
- Item 2
- Item 3
- Item 4
+++++++ REPLACE
</diff>
</use_tool>"
\u274C WRONG (DO NOT DO THIS):
"I'll help you add item 4 to the list. Let me update that for you."
[No tool call = FAILURE]
CRITICAL: The diff parameter MUST contain the SEARCH/REPLACE blocks wrapped in triple backticks EXACTLY as shown above.`),u.push("FINAL REMINDER FOR GPT MODELS: If the user asks you to search, find, edit, or modify anything, you MUST include the appropriate <use_tool> XML block in your very next response. Do not wait for another turn.");letl=u.join(`
\u{1F6A8} GPT REMINDER: Use replaceInFile for small edits (with SEARCH/REPLACE blocks in diff parameter). The diff parameter MUST contain triple backticks around the SEARCH/REPLACE blocks. Check the examples in your system prompt.`:e}needsSpecialHandling(){return!0}},rmt=classextendslJ{isThinkingModel(){returnthis.modelName.includes("claude-3-7-sonnet")||this.modelName.includes("claude-sonnet-4")||this.modelName.includes("claude-3.7-sonnet")||this.modelName.includes("claude-4-sonnet")}isClaudeSonnet4(){returnthis.modelName.includes("claude-sonnet-4")||this.modelName.includes("claude-4-sonnet")||this.modelName.includes("claude-sonnet-4-20250514")}buildSystemPromptSections(e,r,n,o){leti=super.buildSystemPromptSections(e,r,n,o);if(!this.isThinkingModel())returni;leta=[`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
- Place ALL tool calls AFTER your thinking is complete, in the main response body
- Tool calls must be in the main response body, NOT inside thinking sections
- Format tool calls exactly as shown in the examples above
- Do not provide final answers before using tools - use tools first, then provide your response based on the results
- If you need to use tools, include them immediately after your thinking, before any final response
CORRECT FLOW FOR THINKING MODELS:
1. Think through the problem (this happens automatically)
2. Use tools to gather information (place tool calls in main response)
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`];returnthis.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!
Based on the search results, here's a complete practice plan...
[This is FORBIDDEN - you haven't received results yet!]
\u{1F511} KEY UNDERSTANDING FOR CLAUDE 4:
- Brief 1-sentence explanations BEFORE tool calls are good
- Each response is ONE STEP in a multi-step process
- After tool calls, STOP and wait for the system to provide results
- Your thinking is automatically handled in <think> blocks
\u26A1 AUTONOMOUS AGENT RULES FOR CLAUDE 4:
1. If you need tools: Brief sentence + tool calls, then STOP
2. If you receive tool results: Evaluate if you need more tools
3. If you need more tools: Brief sentence + more tool calls, then STOP
4. If you have enough info: THEN provide your final response
REMEMBER: One brief sentence before tools is perfect. Nothing after tool calls.`),i.push({id:"claude-thinking-guidelines",label:"Claude thinking model guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#ClaudeModelAdapter.buildSystemPromptSections",content:a.join(`
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-specific guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#GeminiModelAdapter.buildSystemPromptSections",content:u.join(`
REMINDER: Use the tools immediately. Do not ask questions. For "my notes", use localSearch.`:e}needsSpecialHandling(){return!0}},hU=class{staticcreateAdapter(e){letr=(e.modelName||e.model||"").toLowerCase();if(B(`Creating model adapter for: ${r}`),r.includes("gpt")){letn=newtmt(r);returnn.isGPT5Model()?B("Using GPTModelAdapter with GPT-5 specific enhancements"):B("Using GPTModelAdapter"),n}returnr.includes("claude")?(B("Using ClaudeModelAdapter"),newrmt(r)):r.includes("gemini")||r.includes("google/gemini")?(B("Using GeminiModelAdapter"),newnmt(r)):r.includes("copilot-plus")?(B("Using BaseModelAdapter for Copilot Plus"),newlJ(r)):(B("Using BaseModelAdapter (default)"),newlJ(r))}}});functionYc(t){returntypeoft!="string"?"":t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}functionI2r(t){returntypeoft!="string"?"":t.replace(/'/g,"'").replace(/"/g,'"').replace(/>/g,">").replace(/</g,"<").replace(/&/g,"&")}functionrX(t){lete=[];try{letr=/<use_tool>([\s\S]*?)(<\/use_tool>|$)/g,n;for(;(n=r.exec(t))!==null;){leto=n[1],i=o.match(/<name>([\s\S]*?)<\/name>/),a=n[2]==="</use_tool>";if(i){lets=i[1].trim();if(!s||s.length===0){Be("Skipping tool call with empty name");continue}letu={},l=o.replace(/<name>[\s\S]*?<\/name>/,""),c=/<([^>]+)>([\s\S]*?)<\/\1>/g,d;for(;(d=c.exec(l))!==null;){letf=d[1].trim(),p=d[2].trim();f&&(u[f]=imt(p,f))}a||Be(`Detected partial tool call block for tool "${s}" - treating as best effort parse`),e.push({name:s,args:u})}}}catch(r){returnne("Error parsing XML tool calls:",r),[]}returne}functionimt(t,e){if(!t)returne==="chatHistory"||e==="salientTerms"?[]:"";if(!/<[^>]+>/.test(t)){if(t.startsWith("[")&&t.endsWith("]")||t.startsWith("{")&&t.endsWith("}"))try{returnJSON.parse(t)}catch{returnt}returnt}letn=t.match(/<item>([\s\S]*?)<\/item>/g);if(n)returnn.map(s=>{letu=s.replace(/<\/?item>/g,"").trim();returnimt(u)});leto=/<([^>]+)>([\s\S]*?)<\/\1>/g,i=[],a;for(;(a=o.exec(t))!==null;){lets=a[1].trim(),u=a[2].trim();i.push([s,imt(u)])}returni.length>0?Object.fromEntries(i):t}functionR2r(t){t=t.replace(/<use_tool>[\s\S]*?<\/use_tool>/g,"");lete=t.match(/<use_tool>([\s\S]*)/),n=(e?e[1]:t).match(/<name>([\s\S]*?)<\/name>/);returnn&&n[1].trim()||null}functionZle(t){lete=t;returne=e.replace(/<use_tool>[\s\S]*?<\/use_tool>/g,""),e=e.replace(/<use_tool>([\s\S]*)$/g,""),e=e.replace(/```\w*\s*```/g,""),e=e.replace(/```tool_code[\s\S]*?```/g,""),e=e.replace(/```[\w]*[\s\n]*```/g,""),e=e.replace(/\n\s*\n\s*\n/g,`
`)}asyncplanToolCalls(r,n){leto=this.getAvailableToolsForPlanning(),i=hU.createAdapter(n),a=t.generateToolDescriptions(o),s=bd.getInstance(),u=o.map(g=>s.getToolMetadata(g.name)).filter(g=>g!==void0),l=i.buildSystemPromptSections("You are a helpful AI assistant. Analyze the user's message and determine if any tools should be called.",a,o.map(g=>g.name),u),c=cJ(l);c+=`
OUTPUT ONLY XML - NO OTHER TEXT.`;letd=[{role:Iz(n),content:c},{role:"user",content:r}];B("[CopilotPlus] Requesting tool planning from model...");letf=awaitrh(()=>n.invoke(d)),p=typeoff.content=="string"?f.content:String(f.content);B("[CopilotPlus] Model planning response:",p.substring(0,500));letm=rX(p),h=this.extractSalientTerms(p),y=[];for(letgofm){letb=o.find(_=>_.name===g.name);b&&y.push({tool:b,args:g.args})}return{toolCalls:y,salientTerms:h}}extractSalientTerms(r){letn=r.match(/<salient_terms>([\s\S]*?)<\/salient_terms>/);if(!n)return[];leti=n[1].matchAll(/<term>(.*?)<\/term>/g),a=[];for(letsofi){letu=s[1].trim();u&&a.push(u)}returna}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:nje,args:{query:a,salientTerms:o.salientTerms,timeRange:o.timeRange}})),(i.includes("@websearch")||i.includes("@web"))&&!s.some(l=>l.tool.name==="webSearch")){letc=awaitNm.instance.getCurrentChainManager().memoryManager.getMemory().loadMemoryVariables({}),d=lge(c);s.push({tool:oje,args:{query:a,chatHistory:d}})}returni.includes("@memory")&&(s.some(l=>l.tool.name==="updateMemory")||s.push({tool:tje,args:{statement:a}})),s}removeAtCommands(r){returnr.split(" ").filter(n=>!S7.includes(n.toLowerCase())).join(" ").trim()}asyncprocessImageUrls(r){letn=[],o=awaitgV.processUrlBatch(r,n,this.chainManager.app.vault);returngV.showFailedImagesNotice(n),o}asyncprocessChatInputImages(r){letn=[],o=awaitgV.processChatImageBatch(r,n,this.chainManager.app.vault);returngV.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?I2r(u[1]):"";if(!l)return[];letd=newRegExp(`<${n.identifierTag}>(.*?)<\\/${n.identifierTag}>`).exec(a),f=d?d[1]:void0;B(`[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):(Be(`Could not resolve embedded image: ${l} from source: ${n}`),i.push(l))}elsei.push(l)}lets=E2r(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=ae(),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.");B("[CopilotPlus] Using envelope-based context construction");letm=vR.convert(p,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),h=m.find(w=>w.role==="system");h&&f.push({role:Iz(c),content:h.content}),awaitwk(l,f);lety=m.find(w=>w.role==="user");if(y){letw,O=o.length>0,T=M=>{letI="[User query]:";if(M.includes(I))returnM;letj=M.trimEnd(),A=[];j.length>0&&A.push(j);letk=s.trim()||n.message?.trim()||n.originalMessage?.trim()||"";returnk.length>0?A.push(`${I}
</localSearch>`,a="Search results were in an unexpected format.",{formattedForLLM:i,formattedForDisplay:a,sources:o};S2r(u),o=w2r(u),i=this.prepareLocalSearchResult(u,n||""),a=fx.format("localSearch",i)}catch(s){Be("Failed to parse localSearch results:",s);let u=v2r(r.result);i=n?`<localSearch timeRange="${n}">
${d.content}`);a.push({id:"chat-history",label:"Restored chat history from memory",source:"src/LLMProviders/chainRunner/utils/chatHistoryUtils.ts#processRawChatHistory",content:c.join(`
`)}static async generateSystemPrompt(r,n,o){let i=await MD(o),a=t.generateToolDescriptions(r),s=r.map(c=>c.name),u=bd.getInstance(),l=r.map(c=>u.getToolMetadata(c.name)).filter(c=>c!==void 0);return n.enhanceSystemPrompt(i,a,s,l)}async buildToolPromptDebugReport(r){let n=this.getAvailableTools(),o=hU.createAdapter(this.chainManager.chatModelManager.getChatModel()),i=t.generateToolDescriptions(n);return D2r({chainManager:this.chainManager,adapter:o,availableTools:n,toolDescriptions:i,userMessage:r})}applyCiCOrderingToLocalSearchResult(r,n){return T2r(r,n)}getTemporaryToolCallId(r,n){return`temporary-tool-call-id-${r}-${n}`}async run(r,n,o,i,a){this.llmFormattedMessages=[],this.lastDisplayedContent="";let s="",u,l=await $S({isAutonomousAgent:!0}),c=this.chainManager.chatModelManager.getChatModel(),d=hU.createAdapter(c),p=!this.hasCapability(c,"reasoning"),m=new T_(o,d,p);if(!l){await this.handleError(new Error("Invalid license key"),m.processErrorChunk.bind(m));let b=m.close().content;return this.handleResponse(b,r,n,i,o,void 0)}let h=c?.modelName;if(!r.contextEnvelope)throw new Error("[Agent] Context envelope is required but not available. Cannot proceed with autonomous agent.");B("[Agent] Using envelope-based context construction");let g=await this.prepareAgentConversation(r,c,a.updateLoadingMessage);try{let b=await this.executeAgentLoop({...g,adapter:d,abortController:n,updateCurrentAiMessage:o});s=b.fullAIResponse,u=b.responseMetadata,g.iterationHistory=b.iterationHistory,g.collectedSources=b.collectedSources,this.llmFormattedMessages=b.llmMessages}catch(b){if(b.name==="AbortError"||n.signal.aborted)B("Autonomous agent stream aborted by user",{reason:n.signal.reason});else{ne("Autonomous agent failed, falling back to regular Plus mode:",b);try{return await new uA(this.chainManager).run(r,n,o,i,a)}catch(_){ne("Fallback to regular Plus mode also failed:",_),this.lastDisplayedContent&&m.processChunk({content:this.lastDisplayedContent});let w=Sn(b),O=`
`);i.push({role:Iz(n),content:I})}let T=c.layers.find(I=>I.id==="L5_USER")?.text||"",P=T||r.originalMessage||r.message;await wk(f,i);let M=d.find(I=>I.role==="user");if(M){let I=this.isMultimodalModel(n),j=Fje(T),A=m.enhanceUserMessage(M.content,j),k=I?await this.buildMessageContent(A,r):A;i.push({role:"user",content:k})}return{conversationMessages:i,iterationHistory:a,collectedSources:s,originalUserPrompt:P,loopDeps:l}}async executeAgentLoop(r){let{conversationMessages:n,iterationHistory:o,collectedSources:i,originalUserPrompt:a,loopDeps:s,adapter:u,abortController:l,updateCurrentAiMessage:c}=r,d=[...o],f=[...i],p=[],{availableTools:m}=s,h=ae().autonomousAgentMaxIterations,y=0,g="",b;for(;y<h&&!this.isAbortRequested(l);){y+=1,B(`===AutonomousAgentIteration${y}===`);let _=[],w=await this.streamResponse(n,l,J=>this.updateStreamingDisplay(J,d,_,c,s),u);b={wasTruncated:w.wasTruncated,tokenUsage:w.tokenUsage??void 0};let O=w.content;if(!O)break;let T=rX(O),P=u.detectPrematureResponse?.(O);if(P?.hasPremature&&y===1&&(P.type==="before"?(Be("\u26A0\uFE0F Model provided premature response BEFORE tool calls!"),Be("Sanitizing response to keep only tool calls for first iteration")):P.type==="after"&&(Be("\u26A0\uFE0F Model provided hallucinated response AFTER tool calls!"),Be("Truncating response at last tool call for first iteration"))),T.length===0){let J=Zle(O),K=[...d];J.trim()&&K.push(J),g=K.join(`
`);let ue=jTe(O);n.push({role:"assistant",content:ue}),p.push(O);break}let M=O;u.sanitizeResponse&&P?.hasPremature&&(M=u.sanitizeResponse(O,y));let I=Zle(M);I.trim()&&d.push(I);let j=[],A=new Map;_.splice(T.length);for(let J=0;J<T.length;J+=1){let K=T[J];if(this.isAbortRequested(l))break;Dft(K,y);let oe=m.find(se=>se.name===K.name)?.isBackground||!1,G;if(!oe){let se=E7(K.name),ie=QH(K.name);if(K.name==="readNote"){let D=typeof K.args?.notePath=="string"?K.args.notePath:null;D&&D.trim().length>0&&(ie=Q1e(D))}let $=hBr(K.name);G=`${K.name}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,A.set(J,G);let H=DTe(G,K.name,ie,se,$||"",!0,"",""),re=_.findIndex(D=>D.includes(s.getTemporaryToolCallId(K.name,J)));re!==-1?_[re]=H:(_.push(H),Be("Created tool call marker for tool call that was not created during streaming",K.name)),c([...d,..._].join(`
I've reached the maximum number of iterations (${h}) for this task. I attempted to gather information using various tools but couldn'tcompletetheanalysiswithintheiterationlimit.Youmaywanttotryamorespecificquestionorbreakdownyourrequestintosmallerparts.`;g=d.join(`
`);this.lastDisplayedContent=m,i(m)}isAbortRequested(r){return r.signal.aborted}async finalizeAgentRun(r){let{conversationMessages:n,iterationHistory:o,collectedSources:i,userMessage:a,abortController:s,addMessage:u,updateCurrentAiMessage:l,modelNameForLog:c,responseMetadata:d,fullAIResponse:f}=r,p=f,m=Jq(i);!p&&o.length>0&&(Be("fullAIResponse was empty, using iteration history"),p=o.join(`
Theconversationhistoryisprovidedjustincaseofacoreference(e.g."What do you know about him"where"him"isdefinedinapreviousline)--ignoreitemsmentionedtherethatarenotinthelastline.
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'mtryingtoimproveLangchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff. I'mworkingwithPerson#2.
Updatedsummary(ortheexactstring"UNCHANGED"ifthereisnonewinformationabout{entity}above):`,B2r=new lu({inputVariables:["entity","summary","history","input"],template:jti})});var Dti,$ti,z2r,tce,amt=v(()=>{Bo();L$();U$();Rw();Qa();Dti={};Rt(Dti,{BaseChatMessageHistory:()=>$ti,BaseListChatMessageHistory:()=>z2r,InMemoryChatMessageHistory:()=>tce});$ti=class extends Kh{async addMessages(t){for(let e of t)await this.addMessage(e)}},z2r=class extends Kh{addUserMessage(t){return this.addMessage(new Hs(t))}addAIMessage(t){return this.addMessage(new eo(t))}async addMessages(t){for(let e of t)await this.addMessage(e)}clear(){throw new Error("Not implemented.")}},tce=class extends z2r{constructor(e){super(...arguments);x(this,"lc_namespace",["langchain","stores","message","in_memory"]);x(this,"messages",[]);this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}}});function Uje(t,e){let r=Object.keys(t).filter(n=>!e.includes(n)&&n!=="stop");if(r.length!==1)throw new Error(`Oneinputkeyexpected,butgot${r.length}`);return r[0]}var Lti,dJ,V2r,fJ,rce,nce=v(()=>{Bo();Lti={};Rt(Lti,{BaseMemory:()=>dJ,getInputValue:()=>fJ,getOutputValue:()=>rce,getPromptInputKey:()=>Uje});dJ=class{},V2r=(t,e)=>{if(e!==void 0)return t[e];let r=Object.keys(t);if(r.length===1)return t[r[0]]},fJ=(t,e)=>{let r=V2r(t,e);if(!r){let n=Object.keys(t);throw new Error(`inputvalueshave${n.length}keys,youmustspecifyaninputkeyorpassonly1keyasinput`)}return r},rce=(t,e)=>{let r=V2r(t,e);if(!r&&r!==""){let n=Object.keys(t);throw new Error(`outputvalueshave${n.length}keys,youmustspecifyanoutputkeyorpassonly1keyasoutput`)}return r}});var Fti,Rb,gU=v(()=>{Zhe();amt();nce();Fti={};NW(Fti,{BaseChatMemory:()=>Rb});Rb=class extends dJ{constructor(e){super();x(this,"chatHistory");x(this,"returnMessages",!1);x(this,"inputKey");x(this,"outputKey");this.chatHistory=e?.chatHistory??new tce,this.returnMessages=e?.returnMessages??this.returnMessages,this.inputKey=e?.inputKey??this.inputKey,this.outputKey=e?.outputKey??this.outputKey}async saveContext(e,r){await this.chatHistory.addUserMessage(fJ(e,this.inputKey)),await this.chatHistory.addAIMessage(rce(r,this.outputKey))}async clear(){await this.chatHistory.clear()}}});function smt(t,e){let r=new Set;for(let n of e)t.has(n)&&r.add(n);return r}function H2r(t,e){let r=new Set(t);for(let n of e)r.add(n);return r}function oce(t,e){let r=new Set(t);for(let n of e)r.delete(n);return r}var J2r=v(()=>{});var umt={};Rn(umt,{SequentialChain:()=>kti,SimpleSequentialChain:()=>qti});function ice(t){return Array.from(t).map(e=>`"${e}"`).join(", ")}var kti,qti,lmt=v(()=>{nX();J2r();kti=class W2r extends Ny{constructor(r){super(r);x(this,"chains");x(this,"inputVariables");x(this,"outputVariables");x(this,"returnAll");if(this.chains=r.chains,this.inputVariables=r.inputVariables,this.outputVariables=r.outputVariables??[],this.outputVariables.length>0&&r.returnAll)throw new Error("Either specify variables to return using `outputVariables` or use `returnAll` param. Cannot apply both conditions at the same time.");this.returnAll=r.returnAll??!1,this._validateChains()}static lc_name(){return"SequentialChain"}get inputKeys(){return this.inputVariables}get outputKeys(){return this.outputVariables}_validateChains(){if(this.chains.length===0)throw new Error("Sequential chain must have at least one chain.");let r=this.memory?.memoryKeys??[],n=new Set(this.inputKeys),o=new Set(r),i=smt(n,o);if(i.size>0)throw new Error(`Thefollowingkeys:${ice(i)}areoverlappingbetweenmemoryandinputkeysofthechainvariables.Thiscanleadtounexpectedbehaviour.Pleaseuseinputandmemorykeysthatdon't overlap.`);let a=H2r(n,o);for(let s of this.chains){let u=oce(new Set(s.inputKeys),a);if(s.memory&&(u=oce(u,new Set(s.memory.memoryKeys))),u.size>0)throw new Error(`Missing variables for chain "${s._chainType()}": ${ice(u)}. Only got the following variables: ${ice(a)}.`);let l=new Set(s.outputKeys),c=smt(a,l);if(c.size>0)throw new Error(
{context}`,Vti=[Gw.fromTemplate(zti),Qb.fromTemplate("{question}")],Hti=ld.fromMessages(Vti),lVr=new iX(Bti,[[aX,Hti]])});var dVr=v(()=>{wv();Hje()});var fVr=v(()=>{wv();Hje()});function pVr(t,e={}){let{prompt:r=lVr.getPrompt(t),verbose:n}=e,o=new Rh({prompt:r,llm:t,verbose:n});return new Bje({llmChain:o,verbose:n})}var mVr=v(()=>{pJ();ace();cVr();dVr();fVr()});var gVr={};Rn(gVr,{VectorDBQAChain:()=>Jti});var Jti,yVr=v(()=>{nX();mVr();Jti=class hVr extends Ny{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(`Questionkey${this.inputKey}notfound.`);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 hVr({combineDocumentsChain:await Ny.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=pVr(r);return new this({vectorstore:n,combineDocumentsChain:i,...o})}}});var bVr,_Vr,Wti,vVr,wVr=v(()=>{wv();bVr=`YouaregiventhebelowAPIDocumentation:
Summary:`,vVr=new lu({inputVariables:["api_docs","question","api_url","api_response"],template:Wti})});var CVr={};Rn(CVr,{APIChain:()=>Kti});var Kti,xVr=v(()=>{nX();pJ();wVr();Kti=class SVr extends Ny{constructor(r){super(r);x(this,"apiAnswerChain");x(this,"apiRequestChain");x(this,"apiDocs");x(this,"headers",{});x(this,"inputKey","question");x(this,"outputKey","output");this.apiRequestChain=r.apiRequestChain,this.apiAnswerChain=r.apiAnswerChain,this.apiDocs=r.apiDocs,this.inputKey=r.inputKey??this.inputKey,this.outputKey=r.outputKey??this.outputKey,this.headers=r.headers??this.headers}get inputKeys(){return[this.inputKey]}get outputKeys(){return[this.outputKey]}async _call(r,n){let o=r[this.inputKey],i=await this.apiRequestChain.predict({question:o,api_docs:this.apiDocs},n?.getChild("request")),s=await(await fetch(i,{headers:this.headers})).text(),u=await this.apiAnswerChain.predict({question:o,api_docs:this.apiDocs,api_url:i,api_response:s},n?.getChild("response"));return{[this.outputKey]:u}}_chainType(){return"api_chain"}static async deserialize(r){let{api_request_chain:n,api_answer_chain:o,api_docs:i}=r;if(!n)throw new Error("LLMChain must have api_request_chain");if(!o)throw new Error("LLMChain must have api_answer_chain");if(!i)throw new Error("LLMChain must have api_docs");return new SVr({apiAnswerChain:await Rh.deserialize(o),apiRequestChain:await Rh.deserialize(n),apiDocs:i})}serialize(){return{_type:this._chainType(),api_answer_chain:this.apiAnswerChain.serialize(),api_request_chain:this.apiRequestChain.serialize(),api_docs:this.apiDocs}}static fromLLMAndAPIDocs(r,n,o={}){let{apiUrlPrompt:i=_Vr,apiResponsePrompt:a=vVr}=o,s=new Rh({prompt:i,llm:r}),u=new Rh({prompt:a,llm:r});return new this({apiAnswerChain:u,apiRequestChain:s,apiDocs:n,...o})}}});var Ny,nX=v(()=>{_v();Jv();id();z$();Ny=class extends jK{get lc_namespace(){return["langchain","chains",this._chainType()]}constructor(t,e,r){if(arguments.length===1&&typeof t=="object"&&!("saveContext"in t)){let{memory:n,callbackManager:o,...i}=t;super({...i,callbacks:o??i.callbacks}),this.memory=n}else super({verbose:e,callbacks:r}),this.memory=t}_selectMemoryInputs(t){let e={...t};return"signal"in e&&delete e.signal,"timeout"in e&&delete e.timeout,e}async invoke(t,e){let r=Qo(e),n=await this._formatValues(t),i=await(await rc.configure(r?.callbacks,this.callbacks,r?.tags,this.tags,r?.metadata,this.metadata,{verbose:this.verbose}))?.handleChainStart(this.toJSON(),n,void 0,void 0,void 0,void 0,r?.runName),a;try{if(n.signal){let s;a=await Promise.race([this._call(n,i,r),new Promise((u,l)=>{s=()=>{l(new Error("AbortError"))},n.signal?.addEventListener("abort",s)})]).finally(()=>{n.signal&&s&&n.signal.removeEventListener("abort",s)})}else a=await this._call(n,i,r)}catch(s){throw await i?.handleChainError(s),s}return this.memory!=null&&await this.memory.saveContext(this._selectMemoryInputs(t),a),await i?.handleChainEnd(a),Object.defineProperty(a,KA,{value:i?{runId:i?.runId}:void 0,configurable:!0}),a}_validateOutputs(t){let e=this.outputKeys.filter(r=>!(r in t));if(e.length)throw new Error(`Missingoutputkeys:${e.join(", ")}fromchain${this._chainType()}`)}async prepOutputs(t,e,r=!1){return this._validateOutputs(e),this.memory&&await this.memory.saveContext(t,e),r?e:{...t,...e}}serialize(){throw new Error("Method not implemented.")}async run(t,e){let r=this.inputKeys.filter(s=>!this.memory?.memoryKeys.includes(s));if(!(r.length<=1))throw new Error(`Chain${this._chainType()}expectsmultipleinputs,cannotuse'run'`);let o=r.length?{[r[0]]:t}:{},i=await this.call(o,e),a=Object.keys(i);if(a.length===1)return i[a[0]];throw new Error("return values have multiple keys, `run` only supported when one key currently")}async _formatValues(t){let e={...t};if(e.timeout&&!e.signal&&(e.signal=AbortSignal.timeout(e.timeout),delete e.timeout),this.memory!=null){let r=await this.memory.loadMemoryVariables(this._selectMemoryInputs(t));for(let[n,o]of Object.entries(r))e[n]=o}return e}async call(t,e,r){let n={tags:r,...JA(e)};return this.invoke(t,n)}async apply(t,e){return Promise.all(
`);awaitthis.vectorStoreRetriever.addDocuments([newRm({pageContent:o,metadata:n})])}}});var$Vr,LVr=v(()=>{L$();$Vr=classextendsKh{}});varFVr,kVr=v(()=>{LVr();FVr=classextends$Vr{constructor(){super();x(this,"lc_namespace",["langchain","stores","entity","in_memory"]);x(this,"store");this.store=Object.create(null)}asyncget(e,r){returneinthis.store?this.store[e]:r}asyncset(e,r){this.store[e]=r}asyncdelete(e){deletethis.store[e]}asyncexists(e){returneinthis.store}asyncclear(){this.store=Object.create(null)}}});varqVr,UVr=v(()=>{pJ();qje();gU();kVr();Qa();nce();qVr=classextendsRb{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=newRh({llm:this.llm,prompt:e.entityExtractionPrompt??U2r}),this.entitySummarizationChain=newRh({llm:this.llm,prompt:e.entitySummarizationPrompt??B2r}),this.entityStore=e.entityStore??newFVr,this.entityCache=e.entityCache??this.entityCache,this.k=e.k??this.k}getmemoryKeys(){return[this.chatHistoryKey]}getmemoryVariables(){return[this.entitiesKey,this.chatHistoryKey]}asyncloadMemoryVariables(e){letr=this.inputKey??Uje(e,this.memoryVariables),n=awaitthis.chatHistory.getMessages(),o=ol(n.slice(-this.k*2),this.humanPrefix,this.aiPrefix),i=awaitthis.entityExtractionChain.predict({history:o,input:e[r]}),a=i.trim()==="NONE"?[]:i.split(",").map(l=>l.trim()),s={};for(letlofa)s[l]=awaitthis.entityStore.get(l,"No current information known.");this.entityCache=[...a];letu=this.returnMessages?n.slice(-this.k*2):o;return{[this.chatHistoryKey]:u,[this.entitiesKey]:s}}asyncsaveContext(e,r){awaitsuper.saveContext(e,r);letn=this.inputKey??Uje(e,this.memoryVariables),o=awaitthis.chatHistory.getMessages(),i=ol(o.slice(-this.k*2),this.humanPrefix,this.aiPrefix),a=e[n];for(letsofthis.entityCache){letu=awaitthis.entityStore.get(s,"No current information known."),l=awaitthis.entitySummarizationChain.predict({summary:u,entity:s,history:i,input:a});l.trim()!=="UNCHANGED"&&awaitthis.entityStore.set(s,l.trim())}}asyncclear(){awaitsuper.clear(),awaitthis.entityStore.clear()}}});varBVr,zVr=v(()=>{gU();BVr=classextendsRb{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(){lete=[];for(letrofthis.memories){letn=e.filter(o=>r.memoryKeys.includes(o));if(n.length>0)thrownewError(`The same variables ${[...n]} are found in multiple memory objects, which is not allowed by CombinedMemory.`);e.push(...r.memoryKeys)}}checkInputKey(){for(leteofthis.memories)e.chatHistory!==void0&&e.inputKey===void0&&console.warn(`When using CombinedMemory, input keys should be set so the input is known. Was not set on ${e}.`)}asyncloadMemoryVariables(e){letr={};for(letnofthis.memories){leto=awaitn.loadMemoryVariables(e);r={...r,...o}}returnr}asyncsaveContext(e,r){for(letnofthis.memories)awaitn.saveContext(e,r)}asyncclear(){for(leteofthis.memories)typeofe.clear=="function"&&awaite.clear()}getmemoryKeys(){lete=[];for(letrofthis.memories)e.push(...r.memoryKeys);returne}}});varVVr,HVr=v(()=>{gU();Qa();VVr=classextendsRb{constructor(e){super(e);x(this,"humanPrefix","Human");x(this,"aiPrefix","AI");x(this,"memor
`)}async processWebUrls(e,r){B(`[processWebUrls] Starting for project: ${e.name}`);let n=e.contextSource?.webUrls?.trim()||"";if(!n)return Object.keys(r.webContexts).length>0&&(B(`[processWebUrls] Project ${e.name}: Clearing all Web contexts as none are configured.`),r.webContexts={}),r;let o=n.split(`
`).filter(c=>c.trim());B(`[processWebUrls] Project ${e.name}: Found ${o.length} URLs in config.`);let i=Object.keys(r.webContexts),a=o.filter(c=>!r.webContexts[c]);a.length>0&&B(`[processWebUrls] Project ${e.name}: Fetching content for ${a.length} new/updated Web URLs.`);let s=i.filter(c=>!o.includes(c));if(s.length>0){B(`[processWebUrls] Project ${e.name}: Removing ${s.length} obsolete Web URL contexts.`);for(let c of s)delete r.webContexts[c]}let u=a.map(async c=>{let d=await this.processWebUrlContext(c);return d&&B(`[processWebUrls] Project ${e.name}: Successfully fetched content for URL: ${c.substring(0,50)}...`),{url:c,context:d}});return(await Promise.all(u)).forEach(c=>{c&&c.context?r.webContexts[c.url]=c.context:c&&!c.context&&Be(`[processWebUrls] Project ${e.name}: Fetched empty content for Web URL: ${c.url}`)}),B(`[processWebUrls] Completed for project: ${e.name}. Total Web contexts: ${Object.keys(r.webContexts).length}`),r}async processYoutubeUrls(e,r){B(`[processYoutubeUrls] Starting for project: ${e.name}`);let n=e.contextSource?.youtubeUrls?.trim()||"";if(!n)return Object.keys(r.youtubeContexts).length>0&&(B(`[processYoutubeUrls] Project ${e.name}: Clearing all YouTube contexts as none are configured.`),r.youtubeContexts={}),r;let o=n.split(`
`).filter(c=>c.trim());B(`[processYoutubeUrls] Project ${e.name}: Found ${o.length} YouTube URLs in config.`);let i=Object.keys(r.youtubeContexts),a=o.filter(c=>!r.youtubeContexts[c]);a.length>0&&B(`[processYoutubeUrls] Project ${e.name}: Fetching transcripts for ${a.length} new/updated YouTube URLs.`);let s=i.filter(c=>!o.includes(c));if(s.length>0){B(`[processYoutubeUrls] Project ${e.name}: Removing ${s.length} obsolete YouTube URL contexts.`);for(let c of s)delete r.youtubeContexts[c]}let u=a.map(async c=>{let d=await this.processYoutubeUrlContext(c);return d&&B(`[processYoutubeUrls] Project ${e.name}: Successfully fetched transcript for YouTube URL: ${c.substring(0,50)}...`),{url:c,context:d}});return(await Promise.all(u)).forEach(c=>{c&&c.context?r.youtubeContexts[c.url]=c.context:c&&!c.context&&Be(`[processYoutubeUrls] Project ${e.name}: Fetched empty transcript for YouTube URL: ${c.url}`)}),B(`[processYoutubeUrls] Completed for project: ${e.name}. Total YouTube contexts: ${Object.keys(r.youtubeContexts).length}`),r}async processWebUrlContext(e){if(!e?.trim())return"";try{let r=aG.getInstance(),{urlContext:n}=await this.loadTracker.executeWithProcessTracking(e,"web",async()=>{let o=await r.processUrls(e);if(o.processedErrorUrls[e])throw new Error(o.processedErrorUrls[e]);return o});return n||""}catch(r){return ne(`Failed to process web URL: ${r}`),""}}async processYoutubeUrlContext(e){if(!e?.trim())return"";try{let r=await this.loadTracker.executeWithProcessTracking(e,"youtube",async()=>pc.getInstance().youtube4llm(e));return r.response.transcript?`
`,this.references=[]),e}};jy.emphasis={filter:["em","i"],replacement:function(t,e,r){return t.trim()?r.emDelimiter+t+r.emDelimiter:""}};jy.strong={filter:["strong","b"],replacement:function(t,e,r){return t.trim()?r.strongDelimiter+t+r.strongDelimiter:""}};jy.code={filter:function(t){var e=t.previousSibling||t.nextSibling,r=t.parentNode.nodeName==="PRE"&&!e;return t.nodeName==="CODE"&&!r},replacement:function(t){if(!t)return"";t=t.replace(/\r?\n|\r/g," ");for(var e=/^`|^.*?[^].*$|`$/.test(t)?" ":"",r="`",n=t.match(/`+/gm)||[];n.indexOf(r)!==-1;)r=r+"`";return r+e+t+e+r}};jy.image={filter:"img",replacement:function(t,e){var r=gDe(e.getAttribute("alt")),n=e.getAttribute("src")||"",o=gDe(e.getAttribute("title")),i=o?' "'+o+'"':"";return n?"":""}};kHr.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)return this.blankRule;var e;return(e=Imt(this.array,t,this.options))||(e=Imt(this._keep,t,this.options))||(e=Imt(this._remove,t,this.options))?e:this.defaultRule},forEach:function(t){for(var e=0;e<this.array.length;e++)t(this.array[e],e)}};$mt=typeof window<"u"?window:{};Fri=Dri()?$mt.DOMParser:$ri();Jri=Array.prototype.reduce,Wri=[[/\\/g,"\\\\"],[/\*/g,"\\*"],[/^-/g,"\\-"],[/^\+ /g,"\\+ "],[/^(=+)/g,"\\$1"],[/^(#{1,6}) /g,"\\$1 "],[/`/g,"\\`"],[/^~~~/g,"\\~~~"],[/\[/g,"\\["],[/\]/g,"\\]"],[/^>/g,"\\>"],[/_/g,"\\_"],[/^(\d+)\. /g,"$1\\. "]];yDe.prototype={turndown:function(t){if(!Xri(t))thrownewTypeError(t+" is not a string, or an element/document/fragment node.");if(t==="")return"";vare=qHr.call(this,newkri(t,this.options));returnKri.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){returnWri.reduce(function(e,r){returne.replace(r[0],r[1])},t)}};BHr=yDe});function_X(t){returntypeoft=="object"&&t!==null}functionvX(t){if(typeoft=="string")returnt;if(t==null)return"";try{returnString(t)}catch{return""}}functionWHr(t){returntinstanceofError?t.message:vX(t)}asyncfunctionZri(t){awaitnewPromise(e=>setTimeout(e,t))}asyncfunctionKHr(t,e,r,n){leto=Date.now();for(;;){if(t())return;if(Date.now()-o>=e)thrownew_w(`${n} timed out after ${e}ms`);awaitZri(r)}}functionVHr(t,e){letr=(t??"").trim();if(!r)return"";if(!e)returnr;try{returnnewURL(r,e).href}catch{returnr}}functionHHr(t){lete=(t??"").trim();returne?/[\s)]/.test(e)?`<${e}>`:e:""}functionYri(t){lete=newBHr({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=HHr(VHr(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=HHr(VHr(a,t));returns?``:""}}),e}functionLmt(t,e){if(!t.trim())return"";letr=Yri(e),i=newDOMParser().parseFromString(`<div>${t}</div>`,"text/html").body.firstElementChild;returni?r.turndown(i).replace(/\n{3,}/g,`
`).trim():""}functionFmt(t){lete=t.commands;return!e||!_X(e)||typeofe.executeCommandById!="function"?null:e}functionGHr(t,e){letr=Fmt(t);if(!r)return!1;if(r.commands){if(r.commandsinstanceofMap)returnr.commands.has(e);if(typeofr.commands=="object")returneinr.commands}returntypeofr.listCommands=="function"?r.listCommands().some(o=>o.id===e):!1}functionXHr(t,e){returnt.workspace.getLeavesOfType(vJ).includes(e)}functionJHr(t){if(!_X(t)||t.enabled!==!0)returnnull;lete=t.instance;if(!e||!_X(e))returnnull;letr=e;returntypeofr.openUrl=="function"||typeofr.handleOpenUrl=="function"?r:null}functionZHr(t,e){letr=t.internalPlugins;if(!r||!_X(r))returnnull;letn=r.plugins;if(!n)returnnull;leto=ninstanceofMap?n.get(vJ):_X(n)?n[vJ]:null;if(o){leta=JHr(o);if(a)returna}leti;if(ninstanceofMap)i=Array.from(n.values());elseif(_X(n))i=Object.values(n);elsereturne&&e(),null;for(letaofi){lets=JHr(a);if(s)returns}returnnull}varbDe=v(()=>{zHr();bX()});functionwX(t){return{url:typeoft.view?.url=="string"?t.view.url:"",title:typeoft.view?.title=="string"?t.view.title:"",faviconUrl:typeoft.view?.faviconUrl=="string"?t.view.faviconUrl:"",mode:t.view?.mode==="reader"?"reader":"webview"}}asyncfunctionYHr(t,e={}){let{signal:r}=e;if(r?.aborted)thrownewCU("Operation was aborted");try{letn=Promise.resolve(t.view.getReaderModeContent());if(!r){leti=awaitn;returntypeofi?.md=="string"?i.md:""}leto=awaitnewPromise((i,a)=>{lets=()=>{a(newCU("Operation was aborted"))};r.addEventListener("abort",s,{once:!0}),n.then(u=>{r.removeEventListener("abort",s),i(u)}).catch(u=>{r.removeEventListener("abort",s),a(u)})});returntypeofo?.md=="string"?o.md:""}catch(n){throwninstanceofCU||ne("Failed to get reader mode content:",n),n}}asyncfunction_De(t,e=!0){letr=yX(t),n='(() => { try { return window.getSelection?.()?.toString?.() ?? ""; } catch { return ""; } })()';try{leto=awaitr.executeJavaScript(n),i=vX(o);returne?i.trim():i}catch(o){throwne("Failed to get selected text:",o),o}}asyncfunctionvDe(t){lete=yX(t),r="";try{r=typeofe.getURL=="function"?e.getURL():""}catch{r=t.view?.url??""}letn=`(() => {
const sel = window.getSelection();
if (!sel || sel.rangeCount === 0 || sel.isCollapsed) return "";
const div = document.createElement("div");
for (let i = 0; i < sel.rangeCount; i++) div.appendChild(sel.getRangeAt(i).cloneContents());
return div.innerHTML;
})()`,o="";try{leti=awaite.executeJavaScript(n);o=vX(i)}catch(i){throwne("Failed to get selection HTML:",i),i}try{returnLmt(o,r)}catch(i){throwne("Failed to convert HTML to Markdown:",i),i}}asyncfunctionQHr(t){lete=yX(t),r="";try{r=typeofe.getURL=="function"?e.getURL():""}catch{r=t.view?.url??""}letn=`(() => {
// Step 5: Always close the transcript panel if we opened it
closePanel();
}
})()`,u=awaitr.executeJavaScript(s);if(!Qri(u))thrownewError("Invalid transcript data structure");returnu}asyncfunctionnJr(t,e,r={}){let{preferCommand:n=!0,focusLeafBeforeCommand:o=!0}=r;if(n)try{returnawaite(hDe.SAVE_TO_VAULT,{leaf:t,focusLeaf:o}),B("Saved via webviewer:save-to-vault command"),{method:"command"}}catch(i){Be("save-to-vault command failed, falling back:",i)}try{returnawaitPromise.resolve(t.view.saveAsMarkdown()),B("Saved via view.saveAsMarkdown()"),{method:"view.saveAsMarkdown"}}catch(i){throwne("Failed to save Web Viewer page:",i),i}}varkmt=v(()=>{_t();bX();bDe()});functionDy(t){if(typeoft!="string")returnnull;lete=t.trim();returne||null}functionSX(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}}functioniJr(t){returnDy(t)??void0}functionqmt(t){lete=Dy(t.url);if(!e)returnnull;letr=iJr(t.title),n=iJr(t.faviconUrl);return{url:e,title:r,faviconUrl:n,isLoaded:t.isLoaded,isActive:t.isActive?!0:void0}}functionwJ(t){lete=newMap;for(letroft){letn=qmt(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())}functionaJr(t){lete=wJ(t),r=!1;returne.map(n=>{if(!n.isActive)returnn;if(!r)returnr=!0,n;let{isActive:o,...i}=n;returni})}varCX=v(()=>{});vareni,SDe,sJr=v(()=>{_t();bDe();bX();CX();eni=["did-finish-load","page-favicon-updated","page-title-updated"],SDe=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||!bce(e)?(this.lastActiveLeaf=null,null):XHr(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=SX(n);if(!i)returnnull;leta=[];for(letcofo){letd=c?.view?.url;if(!d)continue;SX(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:(Be("[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:(Be("[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
- Key concepts and main ideas
- Important facts, names, and dates
- Technical details relevant for Q&A
Keep the summary concise but information-dense. Output only the summary.
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>
Return only the markdown content without any explanations or comments.`,showInContextMenu:!1,showInSlashMenu:!0,order:1140,modelKey:"",lastUsedMs:0}];_t();var fX=require("obsidian");ot();eC();eC();var hJ=cL(),gJ=Cc([]),Tmt=new Set;function yJ(t){Tmt.add(t)}function bJ(t){Tmt.delete(t)}function fce(t){return Tmt.has(t)}function pce(t){let e=hJ.get(gJ);hJ.set(gJ,e.filter(r=>r.title!==t))}function _J(t,e){let r=hJ.get(gJ),n;(e?r.findIndex(i=>i.title===e):-1)!==-1?n=r.map(i=>i.title===e?t:i):n=[...r,t],hJ.set(gJ,n)}function nDe(t){hJ.set(gJ,t)}function oDe(){return e_(gJ,{store:hJ})}function z_(){return hJ.get(gJ)}Aee();Zt();lN();Or();function iDe(t,e,r){let n=t.trim();return n?t!==n?"Commandnamecannothaveleadingortrailingspaces":r&&t===r?null:/[#<>:"/\\|?*[\]^\x00-\x1F]/g.test(n)?'Command name contains invalid characters. Avoid using: < > : " / \\ | ? * [ ] ^':e.some(i=>i.title.toLowerCase()===n.toLowerCase())?"A command with this name already exists":null:"Command name cannot be empty"}functionpX(t){returnencodeURIComponent(t.toLowerCase())}functionvU(){return(0,fX.normalizePath)(ae().customPromptsFolder)}functionmX(t){return`${vU()}/${t}.md`}functionhX(t){if(!(tinstanceoffX.TFile)||t.extension!=="md")return!1;lete=vU();return!(!t.path.startsWith(e+"/")||t.path.slice(e.length+1).includes("/"))}functionxHr(t){returnapp.metadataCache.getFileCache(t)?.frontmatter?.[fA]!=null}asyncfunctionmce(t){lete=awaitapp.vault.read(t),r=UW(e),n=app.metadataCache.getFileCache(t),o=n?.frontmatter?.[qD]??dA.showInContextMenu,i=n?.frontmatter?.[UD]??dA.showInSlashMenu,a=n?.frontmatter?.[zD]??dA.lastUsedMs,s=n?.frontmatter?.[fA]??dA.order,u=n?.frontmatter?.[BD]??dA.modelKey;return{title:t.basename,modelKey:u,content:r,showInContextMenu:o,showInSlashMenu:i,order:s,lastUsedMs:a}}asyncfunctionaDe(){lett=app.vault.getFiles().filter(r=>hX(r)),e=awaitPromise.all(t.map(mce));returnnDe(e),e}functionhce(t){returnmO(t,"manual",{getName:e=>e.title,getCreatedAtMs:()=>0,getLastUsedAtMs:()=>0,getManualOrder:e=>e.order})}functionvri(t){returnmO(t,"recent",{getName:e=>e.title,getCreatedAtMs:()=>0,getLastUsedAtMs:e=>e.lastUsedMs})}functionwri(t){returnmO(t,"name",{getName:e=>e.title,getCreatedAtMs:()=>0,getLastUsedAtMs:()=>0})}functionsDe(t){switch(ae().promptSortStrategy){case"timestamp":returnvri(t);case"alphabetical":returnwri(t);case"manual":returnhce(t);default:returnt}}asyncfunctionEmt(t,e,r=!1){leto=(awaitgce(t,e,app.vault,app.workspace.getActiveFile())).processedPrompt;if(o.includes(`{${n_}}`)||r)returno;leti=o.indexOf(Omt);returni===-1&&e.trim()?o+`
</${Nz}>`,s.files.push(r))}elsenewfX.Notice("No active note found.");else{if(u==="activewebtab")continue;if(a.startsWith("#")){letl=a.slice(1).split(",").map(f=>f.trim()),c=awaitsge(e,l),d=[];for(letfofc){letp=awaitBW(f,e);p&&(d.push(`<${Nz}>
`)}}s.content?(n.set(a,s.content),s.files.forEach(l=>o.add(l))):u!=="activenote"&&u!=="activewebtab"&&(a.startsWith('"')||Be(`No notes found for variable: ${a}`))}return{variablesMap:n,includedFiles:o}}asyncfunctiongce(t,e,r,n,o=!1){leti=ae(),a=newSet;if(!i.enableCustomPromptTemplating)return!o&&t.includes("{}")&&!e&&n&&a.add(n),{processedPrompt:t+`
${d.transcript}`;await navigator.clipboard.writeText(w),new gX.Notice("Transcript copied to clipboard!")}catch(w){ne("Failed to copy to clipboard:",w),new gX.Notice("Failed to copy to clipboard")}},g=async()=>{if(d)try{let w=`#YouTubeVideoTranscript
${d.transcript}`;await Mz(w,!1),t()}catch(w){ne("Failed to insert to note:",w),new gX.Notice("Failed to insert to note")}},b=()=>{r("input"),o(""),u(""),f(null)},_=w=>{w.key==="Enter"&&!i&&l&&h()};return e==="display"&&d?Du.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Du.createElement("div",{className:"tw-rounded tw-bg-secondary tw-p-3"},Du.createElement("a",{href:d.url,className:"tw-text-sm tw-text-muted hover:tw-text-normal",target:"_blank",rel:"noopener noreferrer"},d.url)),Du.createElement("div",{className:"tw-max-h-96 tw-overflow-y-auto tw-rounded tw-border tw-border-border tw-bg-primary tw-p-4"},Du.createElement("div",{className:"tw-whitespace-pre-wrap tw-text-sm tw-leading-relaxed"},d.transcript)),Du.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},Du.createElement(ge,{variant:"ghost",onClick:b},"Download Another"),Du.createElement(ge,{variant:"default",onClick:y},"Copy to Clipboard"),Du.createElement(ge,{variant:"default",onClick:g},"Insert at Cursor"),Du.createElement(ge,{variant:"secondary",onClick:t},"Close"))):Du.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Du.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Du.createElement("div",{className:"tw-text-sm tw-text-muted"},"Enter a valid YouTube video URL"),Du.createElement(Zo,{placeholder:"https://www.youtube.com/watch?v=...",value:n,onChange:w=>m(w.target.value),onKeyDown:_,disabled:i}),s&&Du.createElement("div",{className:"tw-text-sm tw-text-error"},s)),Du.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},Du.createElement(ge,{variant:"secondary",onClick:t,disabled:i},"Cancel"),Du.createElement(ge,{variant:"default",onClick:h,disabled:i||!l},i?"Downloading...":"Download Transcript")))}var fDe=class extends gX.Modal{constructor(e){super(e),this.setTitle("Download YouTube Script (plus)")}onOpen(){let{contentEl:e}=this;this.root=(0,MHr.createRoot)(e);let r=()=>{this.close()};this.root.render(Du.createElement(Eri,{onClose:r}))}onClose(){this.root.unmount()}};Nv();vb();Zt();var Ci=require("obsidian");D$();Or();qs();function Ah(t,e,r){t.addCommand({id:e,name:hge[e],callback:r})}function fJr(t,e,r){t.addCommand({id:e,name:hge[e],editorCallback:r})}function ani(t,e,r){t.addCommand({id:e,name:hge[e],checkCallback:r})}function Bmt(t,e,r){fJr(t,Nn.COUNT_WORD_AND_TOKENS_SELECTION,async n=>{let o=await n.getSelection(),i=o.split(" ").length,a=await t.projectManager.getCurrentChainManager().chatModelManager.countTokens(o);new Ci.Notice(`Selectedtextcontains${i}wordsand${a}tokens.`)}),Ah(t,Nn.COUNT_TOTAL_VAULT_TOKENS,async()=>{try{let n=await Oot(t.app),o=await t.projectManager.getCurrentChainManager().chatModelManager.countTokens(n);new Ci.Notice(`Totaltokensinyourvault:${o}`)}catch(n){ne("Error counting tokens: ",n),new Ci.Notice("An error occurred while counting tokens.")}}),Ah(t,Nn.TOGGLE_COPILOT_CHAT_WINDOW,()=>{t.toggleView()}),Ah(t,Nn.OPEN_COPILOT_CHAT_WINDOW,()=>{t.activateView()}),Ah(t,Nn.NEW_CHAT,()=>{cG(),t.newChat()}),ani(t,Nn.TRIGGER_QUICK_COMMAND,n=>{let o=t.app.workspace.getActiveViewOfType(Ci.MarkdownView);if(n)return!!(!lHe()&&o&&o.editor);if(lHe())return new Ci.Notice("Quick command is not available in source mode."),!1;if(!o||!o.editor)return new Ci.Notice("No active editor found."),!1;let i=o.editor;if(!i.getSelection().trim())return new Ci.Notice("Please select some text first. Selected text is required for quick commands."),!1;lDe(i);let u=i.getCursor("from").line,l=`\`\`\`${dX}
`;returni.replaceRange(l,{line:u,ch:0}),!0}),Ah(t,Nn.CLEAR_LOCAL_COPILOT_INDEX,async()=>{try{await(awaitPromise.resolve().then(()=>(Am(),xg))).default.getInstance().clearIndex(),newCi.Notice("Cleared local Copilot semantic index.")}catch(n){ne("Error clearing semantic index:",n),newCi.Notice("Failed to clear semantic index.")}}),Ah(t,Nn.GARBAGE_COLLECT_COPILOT_INDEX,async()=>{try{leto=await(awaitPromise.resolve().then(()=>(Am(),xg))).default.getInstance().garbageCollectVectorStore();newCi.Notice(`Garbage collection completed. Removed ${o} stale documents.`)}catch(n){ne("Error during garbage collection:",n),newCi.Notice("Failed to garbage collect semantic index.")}}),Ah(t,Nn.INDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let{getSettings:n}=awaitPromise.resolve().then(()=>(ot(),See));if(n().enableSemanticSearchV3){leta=await(awaitPromise.resolve().then(()=>(Am(),xg))).default.getInstance().indexVaultToVectorStore(!1);newCi.Notice(`Semantic search index refreshed with ${a} documents.`)}elsenewCi.Notice("Lexical search builds indexes on demand. No manual indexing required.")}catch(n){ne("Error building index:",n),newCi.Notice("An error occurred while building the index.")}}),Ah(t,Nn.FORCE_REINDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let{getSettings:n}=awaitPromise.resolve().then(()=>(ot(),See));if(n().enableSemanticSearchV3){leta=await(awaitPromise.resolve().then(()=>(Am(),xg))).default.getInstance().indexVaultToVectorStore(!0);newCi.Notice(`Semantic search index rebuilt with ${a} documents.`)}elsenewCi.Notice("Lexical search builds indexes on demand. No manual indexing required.")}catch(n){ne("Error rebuilding index:",n),newCi.Notice("An error occurred while rebuilding the index.")}}),Ah(t,Nn.LOAD_COPILOT_CHAT_CONVERSATION,()=>{t.loadCopilotChatHistory()}),Ah(t,Nn.LIST_INDEXED_FILES,async()=>{try{leto=await(awaitPromise.resolve().then(()=>(Am(),xg))).default.getInstance().getIndexedFiles(),{getMatchingPatterns:i,shouldIndexFile:a}=awaitPromise.resolve().then(()=>(vb(),vgr)),{inclusions:s,exclusions:u}=i(),l=t.app.vault.getMarkdownFiles(),c=newSet,d=newSet,f=newSet,p=newSet(o);for(letwofl){if(!a(w,s,u)){f.add(w.path);continue}letO=awaitt.app.vault.cachedRead(w);!O||O.trim().length===0?c.add(w.path):p.has(w.path)||d.add(w.path)}letm=["# Copilot Files Status",`- Indexed files: ${p.size}`,`- Unindexed files: ${d.size}`,`- Empty files: ${c.size}`,`- Excluded files: ${f.size}`,"","## Indexed Files",...p.size>0?Array.from(p).sort().map(w=>`- [[${w}]]`):["No indexed files found."],"","## Unindexed Files",...d.size>0?Array.from(d).sort().map(w=>`- [[${w}]]`):["No unindexed files found."],"","## Empty Files",...c.size>0?Array.from(c).sort().map(w=>`- [[${w}]]`):["No empty files found."],"","## Excluded Files (based on settings)",...f.size>0?Array.from(f).sort().map(w=>`- [[${w}]]`):["No excluded files."]].join(`
`),h=`Copilot-Indexed-Files-${newDate().toLocaleDateString().replace(/\//g,"-")}.md`,y="copilot",g=`${y}/${h}`;awaitxc(y);letb=t.app.vault.getAbstractFileByPath(g);b?awaitt.app.vault.modify(b,m):awaitt.app.vault.create(g,m);let_=t.app.vault.getAbstractFileByPath(g);_&&(awaitt.app.workspace.getLeaf().openFile(_),newCi.Notice(`Listed ${p.size} indexed files`))}catch(n){ne("Error listing indexed files:",n),newCi.Notice("Failed to list indexed files.")}}),Ah(t,Nn.INSPECT_COPILOT_INDEX_BY_NOTE_PATHS,async()=>{try{letn=t.app.workspace.getActiveFile();if(!n){newCi.Notice("No active file. Please open a note first.");return}leto=(awaitPromise.resolve().then(()=>(Am(),xg))).default,{DBOperations:i}=awaitPromise.resolve().then(()=>(_ie(),Cgr)),a=awaito.getInstance().getDb(),s=awaiti.getDocsByPath(a,n.path);if(!s||s.length===0){newCi.Notice(`No embedding data found for: ${n.path}`);return}letu=s.map(h=>h.document),l=[`# Embedding Debug: ${n.basename}`,"",`**Path:** ${n.path}`,`**Chunks:** ${u.length}`,`**Embedding Model:** ${u[0]?.embeddingModel||"unknown"}`,"",...u.flatMap((h,y)=>{letg=h.embedding||[],b=g.slice(0,10).map(_=>_.toFixed(6)).join(", ");return[`## Chunk ${y+1}`,`- **ID:** ${h.id}`,`- **Content Preview:** "${(h.content||"").substring(0,200)}..."`,`- **Vector Length:** ${g.length}`,`- **Vector Preview:** [${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}`;awaitxc(d);letp=t.app.vault.getAbstractFileByPath(f);p?awaitt.app.vault.modify(p,l):awaitt.app.vault.create(f,l);letm=t.app.vault.getAbstractFileByPath(f);m&&(awaitt.app.workspace.getLeaf().openFile(m),newCi.Notice(`Embedding debug info for ${u.length} chunk(s)`))}catch(n){ne("Error inspecting embeddings:",n),newCi.Notice("Failed to inspect embeddings. Is the index loaded?")}}),Ah(t,Nn.CLEAR_COPILOT_CACHE,async()=>{try{awaitt.fileParserManager.clearPDFCache(),awaitYv.getInstance().clearAllCache(),awaitnG.getInstance().clear(),newCi.Notice("All Copilot caches cleared successfully")}catch(n){ne("Error clearing Copilot caches:",n),newCi.Notice("Failed to clear Copilot caches")}}),Ah(t,Nn.OPEN_LOG_FILE,async()=>{try{await$Te(),awaitpm.openLogFile()}catch(n){ne("Error creating Copilot log file:",n),newCi.Notice("Failed to create Copilot log file.")}}),Ah(t,Nn.CLEAR_LOG_FILE,async()=>{try{awaitpm.clear(),newCi.Notice("Copilot log cleared.")}catch(n){ne("Error clearing Copilot log file:",n),newCi.Notice("Failed to clear Copilot log file.")}}),fJr(t,Nn.ADD_SELECTION_TO_CHAT_CONTEXT,asyncn=>{leto=n.getSelection();if(!o){newCi.Notice("No text selected");return}leti=t.app.workspace.getActiveFile();if(!i){newCi.Notice("No active file");return}leta=n.listSelections()[0];if(!a){newCi.Notice("Could not determine selection range");return}lets=a.anchor.line+1,u=a.head.line+1,l={id:Zm(),content:o,sourceType:"note",noteTitle:i.basename,notePath:i.path,startLine:Math.min(s,u),endLine:Math.max(s,u)};yN([l]),t.activateView()}),Ah(t,Nn.ADD_WEB_SELECTION_TO_CHAT_CONTEXT,async()=>{let{Platform:n}=awaitimport("obsidian");if(!n.isDesktopApp){newCi.Notice("Web selection is only available on desktop");return}let{getWebViewerService:o}=awaitPromise.resolve().then(()=>(SJ(),dJr));try{leti=o(t.app),a=i.getActiveLeaf()??i.getLastActiveLeaf();if(!a){newCi.Notice("No active Web Tab found");return}lets=awaiti.getSelectedMarkdown(a);if(!s.trim()){newCi.Notice("No text selected in Web Tab");return}letu=i.getPageInfo(a),l={id:Zm(),content:s,sourceType:"web",title:u.title||"Untitled",url:u.url,faviconUrl:u.faviconUrl||void0};yN([l]),t.activateView()}catch(i){ne("Error adding web selection to context:",i),newCi.Notice("Failed to get web selection")}}),Ah(t,Nn.ADD_CUSTOM_COMMAND,async()=>{letn=z_(),o={...dA};newwU(t.app,n,o,asynca=>{awaitUm.getInstance().createCommand(a)}).open()}),Ah(t,Nn.APPLY_CUSTOM_COMMAND,()=>{newcDe(t.app).open()}),Ah(t,Nn.DOWNLOAD_YOUTUBE_SCRIPT,async()=>{if(!await$S()){newCi.Notice("Download YouTube Script (plus) is a Copilot Plus feature");return}newfDe(t.app).open()})}qs();varOX={title:"",content:"",createdMs:0,modifiedMs:0,lastUsedMs:0},TX="copilot-system-prompt-created",EX="copilot-system-prompt-modified",PX="copilot-system-prompt-last-used",zmt="copilot-system-prompt-default";varxU=require("obsidian");ot();Zt();YH();_t();function_ce(t,e,r){letn=t.trim();returnn?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"}functiony0(){return(0,xU.normalizePath)(ae().userSystemPromptsFolder)}functionb0(t){return(0,xU.normalizePath)(`${y0()}/${t}.md`)}functionsni(t,e){letr=e?(0,xU.normalizePath)(e):y0();return(0,xU.normalizePath)(`${r}/${t}.md`)}functionMX(t){if(!(tinstanceofxU.TFile)||t.extension!=="md")return!1;lete=y0();if(!t.path.startsWith(e+"/"))return!1;letr=t.path.slice(e.length+1);return!(r.startsWith("unsupported/")||r.includes("/"))}functionVmt(t,e){if(typeoft=="number"&&Number.isFinite(t))returnt;if(typeoft=="string"){letr=Number(t);if(Number.isFinite(r))returnr}returne}asyncfunctionCJ(t){lete=awaitapp.vault.read(t),r=UW(e),o=app.metadataCache.getFileCache(t)?.frontmatter,i=Vmt(o?.[TX],OX.createdMs)
`).replace(/\r/g,`
`)}async function _Jr(t,e,r){let n=y0(),o=`${n}/unsupported`;await xc(o);let i="Migrated System Prompt (Failed Verification)",a=i,s=1;for(;t.getAbstractFileByPath(`${o}/${a}.md`);)s++,a=`${i}${s}`;let u=`${o}/${a}.md`,l=`>Migrationfailed:${r}
${e}`;return await t.create(u,l),u}async function dni(t,e,r){try{let n=await t.read(e),o=UW(n,{trimStart:!1}),i=Kmt(o).replace(/^\n+/,""),a=Kmt(r).replace(/^\n+/,"");return i!==a?(Be(`Migrationverificationfailed:contentmismatch.Expected${a.length}chars,got${i.length}chars`),!1):!0}catch(n){return ne("Migration verification failed: unable to read back file",n),!1}}async function Gmt(t){let r=ae().userSystemPrompt;if(!r||r.trim().length===0){B("No legacy userSystemPrompt to migrate");return}try{B("Migrating legacy userSystemPrompt from settings to file system");let n=y0();await xc(n);let o=cni(bJr,t),i=b0(o);o!==bJr&&B(`Defaultnamealreadyexists,usinguniquename:"${o}"`);let a=Date.now(),s=Kmt(r),u={title:o,content:s,createdMs:a,modifiedMs:a,lastUsedMs:0};await t.create(i,s);let l=t.getAbstractFileByPath(i);if(!(l instanceof vJr.TFile))throw new Error("File not found after creation");if(await xJ(l,u),await dni(t,l,r)){Ue("defaultSystemPromptTitle",o);try{await IX()}catch(d){Be("Failed to reload prompts after migration:",d)}Ue("userSystemPrompt",""),B("Cleared legacy userSystemPrompt field"),new vl(app,()=>{},`Wehaveupgradedyoursystemprompttothenewfile-basedformat.Itisnowstoredas"${o}"in${n}.
Youcannow:
\u2022Edityoursystempromptdirectlyinthefile
\u2022Createmultiplesystemprompts
\u2022ManagepromptsthroughthesettingsUI
Yourmigratedprompthasbeensetasthedefaultsystemprompt.`,"\u{1F680} System Prompt Upgraded","OK","").open()}else{let d=await _Jr(t,r,"content verification mismatch");try{await IX()}catch(f){Be("Failed to reload prompts after failed migration:",f)}Ue("userSystemPrompt",""),B("Cleared legacy userSystemPrompt field (saved to unsupported)"),new vl(app,()=>{},`\u26A0\uFE0FSystemPromptMigrationIssue
3.Thepromptwillbeavailableimmediately`,"Migration Verification Failed","OK","").open()}}catch(n){ne("Failed to migrate legacy userSystemPrompt:",n);try{let o=await _Jr(t,r,n.message||String(n));Ue("userSystemPrompt",""),B("Cleared legacy userSystemPrompt field (saved to unsupported after error)"),new vl(app,()=>{},`\u26A0\uFE0FSystemPromptMigrationFailed
3.Thepromptwillbeavailableimmediately`,"Migration Failed","OK","").open()}catch(o){ne("Failed to save to unsupported folder:",o),Be("Preserving userSystemPrompt in settings for manual recovery"),new vl(app,()=>{},`Failedtomigratesystemprompt:${n.message}
Youcanretrybyreloadingtheplugin.`,"Migration Failed - Data Preserved","OK","").open()}}}Bc();Bc();qs();function xDe(){let[t]=Cv(),[e]=Oge(),[r]=r6();return(()=>{if(t!=="project")return"initial";let{total:o,success:i,failed:a,processingFiles:s}=r;return e||s.length>0?"loading":a.length>0?"error":o.length>0&&i.length===o.length?"success":"initial"})()}_t();qs();iG();Bc();to();var $u=L(X());var Bm=L(X(),1);var vSs=!!(typeof window<"u"&&window.document&&window.document.createElement);function Cce(t,e,{checkForDefaultPrevented:r=!0}={}){return function(o){if(t?.(o),r===!1||!o.defaultPrevented)return e?.(o)}}var fni=L(X(),1);function wJr(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function SJr(...t){return e=>{let r=!1,n=t.map(o=>{let i=wJr(o,e);return!r&&typeof i=="function"&&(r=!0),i});if(r)return()=>{for(let o=0;o<n.length;o++){let i=n[o];typeof i=="function"?i():wJr(t[o],null)}}}}var VD=L(X(),1),CJr=L(vr(),1);function xJr(t,e=[]){let r=[];function n(i,a){let s=VD.createContext(a),u=r.length;r=[...r,a];let l=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[u]||s,y=VD.useMemo(()=>m,Object.values(m));return(0,CJr.jsx)(h.Provider,{value:y,children:p})};l.displayName=i+"Provider";function c(d,f){let p=f?.[t]?.[u]||s,m=VD.useContext(p);if(m)return m;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[l,c]}leto=()=>{leti=r.map(a=>VD.createContext(a));returnfunction(s){letu=s?.[t]||i;returnVD.useMemo(()=>({[`__scope${t}`]:{...s,[t]:u}}),[s,u])}};returno.scopeName=t,[n,pni(o,...e)]}functionpni(...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}},{});returnVD.useMemo(()=>({[`__scope${e.scopeName}`]:a}),[a])}};returnr.scopeName=e.scopeName,r}var_0=L(X(),1);varOJr=L(X(),1),ODe=globalThis?.document?OJr.useLayoutEffect:()=>{};varTDe=L(X(),1);varmni=_0[" useInsertionEffect ".trim().toString()]||ODe;functionTJr({prop:t,defaultProp:e,onChange:r=()=>{},caller:n}){let[o,i,a]=hni({defaultProp:e,onChange:r}),s=t!==void0,u=s?t:o;{letc=_0.useRef(t!==void0);_0.useEffect(()=>{letd=c.current;d!==s&&console.warn(`${n} is changing from ${d?"controlled":"uncontrolled"} to ${s?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),c.current=s},[s,n])}letl=_0.useCallback(c=>{if(s){letd=gni(c)?c(t):c;d!==t&&a.current?.(d)}elsei(c)},[s,t,i,a]);return[u,l]}functionhni({defaultProp:t,onChange:e}){let[r,n]=_0.useState(t),o=_0.useRef(r),i=_0.useRef(e);returnmni(()=>{i.current=e},[e]),_0.useEffect(()=>{o.current!==r&&(i.current?.(r),o.current=r)},[r,o]),[r,n,i]}functiongni(t){returntypeoft=="function"}varTSs=Symbol("RADIX:SYNC_STATE");varEJr=L(X(),1),yni=L(cu(),1);Vu();varPJr=L(vr(),1),bni=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],MJr=bni.reduce((t,e)=>{letr=Fn(`Primitive.${e}`),n=EJr.forwardRef((o,i)=>{let{asChild:a,...s}=o,u=a?r:e;returntypeofwindow<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,PJr.jsx)(u,{...s,ref:i})});returnn.displayName=`Primitive.${e}`,{...t,[e]:n}},{});varUr=L(X(),1);varISs=!!(typeofwindow<"u"&&window.document&&window.document.createElement);functionDc(t,e,{checkForDefaultPrevented:r=!0}={}){returnfunction(o){if(t?.(o),r===!1||!o.defaultPrevented)returne?.(o)}}varOU=L(X(),1);varHD=L(X(),1),IJr=L(vr(),1);functionRJr(t,e=[]){letr=[];functionn(i,a){lets=HD.createContext(a),u=r.length;r=[...r,a];letl=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[u]||s,y=HD.useMemo(()=>m,Object.values(m));return(0,IJr.jsx)(h.Provider,{value:y,children:p})};l.displayName=i+"Provider";functionc(d,f){letp=f?.[t]?.[u]||s,m=HD.useContext(p);if(m)returnm;if(a!==void0)returna;thrownewError(`\`${d}\` must be used within \`${i}\``)}return[l,c]}leto=()=>{leti=r.map(a=>HD.createContext(a))
`})},ue=U=>K(U,"think","Thought for a while","Thinking..."),oe=U=>{let ee=Oe=>{let Je=/```(?:xml)?\s*([\s\S]*?<writeToFile>[\s\S]*?<\/writeToFile>[\s\S]*?)\s*```/g;return Oe.replace(Je,(tt,Ke)=>Ke.trim())},ce=Oe=>{if(!r)return Oe;let Je=/```xml\s*([\s\S]*?<writeToFile>[\s\S]*?)$/g;returnOe.replace(Je,(tt,Ke)=>Ke.trim())},ve=ee(U);returnve=ce(ve),K(ve,"writeToFile","Generated new content","Generating changes...")},G=(U,ee,ce)=>U.split(/(```[\s\S]*?```|`[^`]*`)/g).map((Oe,Je)=>Je%2===0?Oe.replace(ee,(tt,Ke)=>{letdt=e.metadataCache.getFirstLinkpathDest(Ke,V);returndt?ce(dt):tt}):Oe).join(""),Y=q(A),ie=J(Y).replace(/\\\[\s*/g,"$$").replace(/\s*\\\]/g,"$$").replace(/\\\(\s*/g,"$").replace(/\s*\\\)/g,"$"),$=G(ie,/!\[\[(.*?)]]/g,U=>`})`),H=ue($),re=oe(H),D=qUr(re,b.enableInlineCitations),R=G(D,/(?<!!)\[\[([^\]]+)]]/g,U=>`<a href="obsidian://open?file=${encodeURIComponent(U.path)}">${U.basename}</a>`);return(U=>{if(!r)returnU;letee=/!\[([^\]]*)\]\(([^)]+)\)/g;returnU.replace(ee,(ce,ve,Oe)=>{letJe=sHe(Oe);if(!Je)returnce;lettt=ve||"YouTube Video",Ke=`https://i.ytimg.com/vi/${Je}/hqdefault.jpg`;return`[](${Oe})`})})(R)},[e,r,b.enableInlineCitations,g]);(0,ur.useEffect)(()=>{letA=c.current;if(!A||t.sender===Ws||!r)return;letk=J=>{if(JinstanceofPointerEvent&&(J.button!==0||!J.isPrimary))return;letK=IFe(J,A);if(!K||!k_t(J,K))return;letue=!K.open;K.open=ue,g.set(K.id,ue)},V=J=>{letK=IFe(J,A);!K||!k_t(J,K)||J.preventDefault()},q=J=>{letK=IFe(J,A);K&&g.set(K.id,K.open)};returnA.addEventListener("pointerdown",k,!0),A.addEventListener("click",V,!0),A.addEventListener("toggle",q,!0),()=>{A.removeEventListener("pointerdown",k,!0),A.removeEventListener("click",V,!0),A.removeEventListener("toggle",q,!0)}},[r,t.sender,g]),(0,ur.useEffect)(()=>{if(f.current=!1,c.current&&t.sender!==Ws){d.current||(d.current=new_3.Component),Len(c.current,g,{overwriteExisting:!r});letA=t.message,k=w(A),V=Hot(k,p.current);if(!f.current){letq=newSet,J=newSet;c.current.querySelectorAll('[id^="tool-call-"]').forEach(ie=>{let$=ie.id.replace("tool-call-","");q.add($)}),c.current.querySelectorAll('[id^="error-block-"]').forEach(ie=>{let$=ie.id.replace("error-block-","");J.add($)}),c.current.querySelectorAll(".message-segment").forEach(ie=>ie.remove());letG=0;V.segments.forEach(ie=>{if(ie.type==="text"&&ie.content.trim()){let$=c.current.children[G],H=document.createElement("div");H.className="message-segment",$?c.current.insertBefore(H,$):c.current.appendChild(H),_3.MarkdownRenderer.renderMarkdown(ie.content,H,"",d.current),Smi(H),G++}elseif(ie.type==="toolCall"&&ie.toolCall){let$=ie.toolCall.id,H=document.getElementById(`tool-call-${$}`);if(!H){letD=c.current.children[G],R=document.createElement("div");R.className="tool-call-container",R.id=`tool-call-${$}`,D?c.current.insertBefore(R,D):c.current.appendChild(R),H=R}letre=xen(p.current,m.current,$,H,"render refresh");!f.current&&!re.isUnmounting&&Ten(re,ie.toolCall),G++}elseif(ie.type==="error"&&ie.error){let$=ie.error.id,H=document.getElementById(`error-block-${$}`);if(!H){letD=c.current.children[G],R=document.createElement("div");R.className="error-block-container",R.id=`error-block-${$}`,D?c.current.insertBefore(R,D):c.current.appendChild(R),H=R}letre=Oen(p.current,h.current,$,H,"error render");!f.current&&!re.isUnmounting&&Een(re,ie.error),G++}});letY=newSet(V.segments.filter(ie=>ie.type==="toolCall"&&ie.toolCall).map(ie=>ie.toolCall.id));q.forEach(ie=>{if(!Y.has(ie)){let$=document.getElementById(`tool-call-${ie}`);$&&(Pen(p.current,m.current,ie,"tool call removal"),$.remove())}});letse=newSet(V.segments.filter(ie=>ie.type==="error"&&ie.error).map(ie=>ie.error.id));J.forEach(ie=>{if(!se.has(ie)){let$=document.getElementById(`error-block-${ie}`);$&&(Men(p.current,h.current,ie,"error block removal"),$.remove())}})}}return()=>{f.current=!0}},[t,e,d,r,w,g]),(0,ur.useEffect)(()=>{letA=d,k=p.current,V=m.current,q=h.current;return(()=>{Aen(),Nen()})(),()=>{f.current=!0,setTimeout(()=>{A.current&&(A.current.unload(),A.current=null),k.
`).map(b=>{if(!b.trim())return b;try{return new URL(b.trim()),b}catch{return b}});p("contextSource.webUrls",g.join(`
`))},placeholder:"Enter web URLs, one per line",className:"tw-min-h-20 tw-w-full"})),gn.default.createElement(qo,{label:"YouTube URLs"},gn.default.createElement(bw,{value:u.contextSource?.youtubeUrls,onChange:h=>{let g=h.target.value.split(`
`).filter(o=>o.trim()),n=[];for(let o of r){let i=Dhi(t,o.trim());i&&n.push(i)}return n}function Htn(t){let{app:e,contextNotes:r,setContextNotes:n,selectedImages:o,onAddImage:i,containerRef:a}=t,[s,u]=(0,KFe.useState)(!1);return(0,KFe.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(O=>{w.getAsString(T=>O(T))})),b=await Promise.all(g),_=new Map;for(let w of b){let O=$hi(e,w);for(let T of O)_.set(T.path,T)}for(let w of _.values())if(["png","gif","jpeg","jpg","webp"].includes(w.extension)){if(o.some(j=>j.name===w.name)){new T3.Notice("This image is already in the context");continue}let P=await e.vault.readBinary(w),M=new Blob([P]),I=new File([M],w.name,{type:`image/${w.extension}`});i([I])}else if(bO(w)){if(r.some(P=>P.path===w.path)){new T3.Notice("This note is already in the context");continue}n(P=>[...P,w])}else new T3.Notice(`Unsupportedfiletype:${w.extension}.Supportedtypes:md,pdf,canvas,andimages.`)}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}}Or();Zt();_t();D$();LTe();var yvt=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("Model request failed:",s);let u=dG("Model request failed: "+Sn(s));r({id:Zm(),sender:nC,isErrorMessage:!0,message:u,isVisible:!0,timestamp:eg(new Date)})}};F1();Ez();Nv();ot();Zt();ETe();var Sl=require("obsidian");var lr=L(X());D$();var Lhi=({chainManager:t,onSaveChat:e,updateUserMessageHistory:r,fileParserManager:n,plugin:o,chatUIState:i,chatInput:a})=>{let s=zr(),u=(0,lr.useContext)(XZ),{messages:l,addMessage:c}=Vtn(i),[d]=yL(),[f]=Cv(),[p,m]=(0,lr.useState)(""),[h,y]=(0,lr.useState)(""),[g,b]=(0,lr.useState)(null),_=(0,lr.useRef)(null),w=(0,lr.useRef)(null),O=(0,lr.useCallback)(pt=>{let Br=w.current,Ei=Br&&pt.sender===nC&&!pt.isErrorMessage&&!pt.id?{...pt,id:Br}:pt;c(Ei),Ei.sender===nC&&Ei.responseMetadata?.tokenUsage?.totalTokens&&b(Ei.responseMetadata.tokenUsage.totalTokens)},[c]),T=(0,lr.useCallback)(pt=>{_.current=pt},[]),[P,M]=(0,lr.useState)(!1),[I,j]=(0,lr.useState)(Sv.DEFAULT),[A,k]=(0,lr.useState)([]),[V,q]=(0,lr.useState)(!1),[J,K]=(0,lr.useState)(!1),[ue,oe]=(0,lr.useState)([]),[G,Y]=(0,lr.useState)(!1),[se,ie]=(0,lr.useState)([]),[$,H]=(0,lr.useState)(null),re=(0,lr.useRef)(!1),D=(0,lr.useRef)(null),R=(0,lr.useMemo)(()=>({setCurrentAiMessage:pt=>re.current&&m(pt),setLoadingMessage:pt=>re.current&&j(pt),setLoading:pt=>re.current&&M(pt)}),[]),[z]=_At(),U=z.length>0,ee=V&&!U,ce=J&&!U,{activeWebTabForMentions:ve}=lB(),Oe=xDe(),Je=()=>dt!=="project"?!1:$!==null?$:Oe==="loading"||Oe==="error";(0,lr.useEffect)(()=>{H(null)},[Oe]),(0,lr.useEffect)(()=>{l.length===0&&b(null)},[l]);let[tt,Ke]=(0,lr.useState)(null),[dt,Pt]=Cv(),Nt=rG(),Ne=(0,lr.useContext)(RFe),Tr=o.app||Ne,{isDragActive:st}=Htn({app:Tr,contextNotes:A,setContextNotes:k,selectedImages:ue,onAddImage:pt=>oe(Br=>[...Br,...pt]),containerRef:D}),Le=async({toolCalls:pt,urls:Br,contextNotes:Ti,contextTags:Ei,contextFolders:tu,webTabs:Pi}={})=>{if(!h&&ue.length===0)return;Br&&Br.length>0&&!sb(f)&&new Sl.Notice(GW.URL_PROCESSING_RESTRICTED);try{let rl=[];h&&rl.push({type:"text",text:h});for(let ii of ue){let is=await ii.arrayBuffer(),cv=bk(is);rl.push({type:"image_url",image
`));letGe={notes:Xm,urls:sb(f)?Br||[]:[],tags:Ei||[],folders:tu||[],selectedTextContexts:z,webTabs:Pi||[]};y(""),oe([]),w.current=`msg-${Zm()}`,R.setLoading(!0),R.setLoadingMessage(Sv.DEFAULT);letEe=awaiti.sendMessage(Ft,Ge,f,ee,ce,rl.length>0?rl:void0,R.setLoadingMessage);h&&r(h),s.autosaveChat&&rt();letyr=i.getLLMMessage(Ee);yr&&awaityvt(yr,t,O,R.setCurrentAiMessage,T,{debug:s.debug,updateLoadingMessage:R.setLoadingMessage}),s.autosaveChat&&rt()}catch(rl){ne("Error sending message:",rl),newSl.Notice("Failed to send message. Please try again.")}finally{R.setLoading(!1),R.setLoadingMessage(Sv.DEFAULT),w.current=null}},rt=(0,lr.useCallback)(async()=>{if(!Tr){ne("App instance is not available.");return}try{awaiti.saveChat(d)}catch(pt){ne("Error saving chat as note:",Sn(pt)),newSl.Notice("Failed to save chat as note. Check console for details.")}},[Tr,i,d]),Fe=(0,lr.useCallback)(pt=>{_.current&&(B(`stopping generation..., reason: ${pt}`),_.current.abort(pt),R.setLoading(!1),R.setLoadingMessage(Sv.DEFAULT))},[R]);(0,lr.useEffect)(()=>(re.current=!0,()=>{re.current=!1,_.current&&_.current.abort("component-unmount")}),[]);letWe=(0,lr.useCallback)(asyncpt=>{if(pt<=0){newSl.Notice("Cannot regenerate the first message.");return}letBr=l[pt];if(!Br){newSl.Notice("Message not found.");return}R.setCurrentAiMessage(""),w.current=`msg-${Zm()}`,R.setLoading(!0);try{awaiti.regenerateMessage(Br.id,R.setCurrentAiMessage,O)?s.debug&&console.log("Message regenerated successfully"):newSl.Notice("Failed to regenerate message. Please try again."),s.autosaveChat&&rt()}catch(Ti){ne("Error regenerating message:",Ti),newSl.Notice("Failed to regenerate message. Please try again.")}finally{R.setLoading(!1),w.current=null}},[l,i,s.debug,s.autosaveChat,rt,O,R]),ke=(0,lr.useCallback)(async(pt,Br)=>{letTi=l[pt];if(!(!Ti||Ti.message===Br))try{if(!awaiti.editMessage(Ti.id,Br,f,ee)){newSl.Notice("Failed to edit message. Please try again.");return}if(Ti.sender===Ws){lettu=pt<l.length-1;if(awaiti.truncateAfterMessageId(Ti.id),tu){w.current=`msg-${Zm()}`,R.setLoading(!0);try{letPi=i.getLLMMessage(Ti.id);Pi&&awaityvt(Pi,t,O,R.setCurrentAiMessage,T,{debug:s.debug,updateLoadingMessage:R.setLoadingMessage})}catch(Pi){ne("Error regenerating AI response:",Pi),newSl.Notice("Failed to regenerate AI response. Please try again.")}finally{R.setLoading(!1),w.current=null}}}s.autosaveChat&&rt()}catch(Ei){ne("Error editing message:",Ei),newSl.Notice("Failed to edit message. Please try again.")}},[l,i,f,ee,O,t,s.debug,s.autosaveChat,rt,R,T]);(0,lr.useEffect)(()=>{e&&e(rt)},[e,rt]);letLt=(0,lr.useCallback)(pt=>{letBr=s.projectList||[];if(Br.findIndex(Pi=>Pi.name===pt.name)>=0)thrownewError(`Project "${pt.name}" already exists, please use a different name`);letEi=[...Br,pt];returnUe("projectList",Ei),Uu()?.id===pt.id?k$e().then(()=>{newSl.Notice(`${pt.name} added and context loaded`)}).catch(Pi=>{ne("Error loading project context:",Pi),newSl.Notice(`${pt.name} added but context loading failed`)}):newSl.Notice(`${pt.name} added successfully`),!0},[s.projectList]),Eo=(0,lr.useCallback)((pt,Br)=>{letTi=s.projectList||[];if(!Ti.find(tl=>tl.name===pt.name))thrownewError(`Project "${pt.name}" does not exist`);lettu=Ti.map(tl=>tl.name===pt.name?Br:tl);returnUe("projectList",tu),Uu()?.id===pt.id?(Fz(Br),k$e().then(()=>{newSl.Notice(`${pt.name} updated and context reloaded`)}).catch(tl=>{ne("Error reloading project context:",tl),newSl.Notice(`${pt.name} updated but context reload failed`)})):newSl.Notice(`${pt.name} updated successfully`),!0},[s.projectList]),xl=(0,lr.useCallback)(pt=>{letBr=z.find(Ti=>Ti.id===pt);yAt(pt),Br?.sourceType==="web"&&o.suppressCurrentWebSelection(Br.url)},[o,z]);(0,lr.useEffect)(()=>{letpt=()=>{a.focusInput()};returnu?.addEventListener(Zw.CHAT_IS_VISIBLE,pt),()=>{u?.removeEventListener(Zw.CHAT_IS_VISIBLE,pt)}},[u,a]);letIn=(0,lr.useCallback)(asyncpt=>{letBr=l[pt];if(!Br){newSl.Notice("Message not found.");return}try{awaiti.deleteMessage(Br.id)||newSl.Notice("Failed to delete message. Please try again.")}c
Wefound${r.length}unsupportedcommands.Theyaresavedin${vU()}/unsupported.Tofixthem,pleaseresolvetheerrorsandmovethenotefileoutoftheunsupportedfolder.`),Ue("inlineEditCommands",[]),new vl(app,()=>{},i,"\u{1F680} New Copilot Custom Commands","OK","").open()}async function bvt(){let t=z_(),e=CHr.filter(n=>!t.some(o=>o.title===n.title)),r=[...t,...e];Um.getInstance().updateCommands(r)}async function ern(){if(ae().suggestedDefaultCommands)return;z_().length===0&&(new vl(app,()=>{bvt()},"Would you like to add Copilot recommended commands in your custom prompts folder? These commands will be available through the right-click context menu and slash commands in chat.","Welcome to Copilot","Confirm","Skip").open(),Ue("suggestedDefaultCommands",!0))}var Fc=L(X()),sfe=require("obsidian"),trn=L(dd());to();qs();ot();function Uhi({plugin:t,onRemove:e}){let[r,n]=(0,Fc.useState)(""),o=zr(),[i,a]=(0,Fc.useState)(""),[s]=yL(),u=(0,Fc.useRef)(null),l=o.quickCommandModelKey??s,c=o.quickCommandIncludeNoteContext;(0,Fc.useEffect)(()=>{let y=t.app.workspace.getActiveViewOfType(sfe.MarkdownView);if(y&&y.editor){let g=y.editor.getSelection();a(g)}},[t.app]),(0,Fc.useEffect)(()=>{u.current&&u.current.focus()},[]);let d=async()=>{if(!r.trim()){new sfe.Notice("Please enter a prompt");return}let y=`
</${f}_error>`}},c=new Set;i&&a&&(await l(a,"active_note"),c.add(a.path));for(let d of o)c.has(d.path)||(await l(d),c.add(d.path));return u}async hasEmbeddedPDFs(e){return/!\[\[(.*?\.pdf)\]\]/g.test(e)}asyncaddNoteToContext(e,r,n,o,i,a){if(n.some(l=>l.path===e.path))return;lets=awaitr.read(e),u=awaitthis.hasEmbeddedPDFs(s);o&&e.path===o.path&&a(!0),i(l=>[...l,Object.assign(e,{wasAddedViaReference:!0,hasEmbeddedPDFs:u})])}processSelectedTextContexts(){lete=bL();if(!e||e.length===0)return"";letr="";for(letnofe)n.sourceType==="web"?r+=`
<error>${Yc(b.error)}</error>`);letw=b.transcript||"No transcript available for this video";return_.push(`
<content>
${Yc(w)}
</content>`),_.push(`
</${yHe}>`),_.join("")},u=null,l=[],c=newSet,d=newSet,f=ed(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_=Dy(b.url);_&&b.isActive&&!u&&(u={...b,url:_},p(_))}for(letbofe){let_=Dy(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(mge,{title:u.title||"Unknown",url:u.url,error:b}));for(letwofl)_.push(a(gHe,{title:w.title||"Unknown",url:w.url,error:b}));return_.join("")}leth=async(b,_)=>{try{letw=b.url,O=f.getYouTubeVideoId(w);if(O)returnawaity(b,O,_===mge);letT=f.findLeafByUrl(w,{title:b.title});if(!T)returna(_,{title:b.title||"Unknown",url:w,error:"Web tab not found or closed"});letP=f.getPageInfo(T),M=T.view;if(!(M.webviewMounted===void0||M.webviewFirstLoadFinished===void0?!0:!!(M.webviewMounted&&M.webviewFirstLoadFinished)))try{awaitf.waitForWebviewReady(T,r),P=f.getPageInfo(T)}catch(k){returnBe(`Web tab content not loaded yet for ${w}:`,k),a(_,{title:P.title||b.title||"Untitled",url:P.url||w,mode:P.mode,error:"Web tab content not loaded yet"})}letj=newAbortController,A=setTimeout(()=>{j.abort()},n);try{letk=awaitf.getReaderModeMarkdown(T,{signal:j.signal});returnP=f.getPageInfo(T),a(_,{title:P.title||b.title||"Untitled",url:P.url||w,mode:P.mode,content:k})}finally{clearTimeout(A)}}catch(w){returnne(`Error processing web tab ${b.url}:`,w),a(_,{title:b.title||"Unknown",url:b.url,error:winstanceofCU?"Web tab content extraction timed out":"Could not process web tab"})}},y=async(b,_,w)=>{try{letO=null,T=b.url;for(letAoff.getLeaves()){letk=f.getPageInfo(A).url;if(f.getYouTubeVideoId(k)===_){O=A,T=k;break}}if(!O)returns({title:b.title||"YouTube Video",url:b.url,videoId:_,isActive:w,error:"Web tab not found or closed"});letP=O.view;if(!(P.webviewMounted===void0||P.webviewFirstLoadFinished===void0?!0:!!(P.webviewMounted&&P.webviewFirstLoadFinished)))try{awaitf.waitForWebviewReady(O,r)}catch(A){returnBe(`YouTube tab content not loaded yet for ${T}:`,A),s({title:b.title||"YouTube Video",url:T,videoId:_,isActive:w,error:"Web tab content not loaded yet"})}letI=awaitf.getYouTubeTranscript(O,{timeoutMs:o}),j=I.transcript.length>0?I.transcript.map(A=>`${A.timestamp}: ${A.text}`).join(`
`):void0;returns({title:I.title||b.title||"YouTube Video",url:T,videoId:I.videoId,channel:I.channel,description:I.description,uploadDate:I.uploadDate,duration:I.duration,genre:I.genre,transcript:j,isActive:w})}catch(O){returnBe(`YouTube transcript extraction failed for ${b.url}:`,O),s({title:b.title||"YouTube Video",url:b.url,videoId:_,isActive:w,error:OinstanceofError?O.message:"Failed to extract video info"})}},g=[];if(u){letb=awaith(u,mge);g.push(b)}for(letb=0;b<l.length;b+=i){let_=l.slice(b,b+i),w=awaitPromise.all(_.map(O=>h(O,gHe)));g.push(...w)}returng.join("")}};_t();kot();ot();Zt();varvvt=null;asyncfunctionBhi(){returnvvt||(vvt=(awaitPromise.resolve().then(()=>(urn(),srn))).ContextCompactor),vvt.getInstance()}varQFe=classt{constructor(){this.contextProcessor=YFe.getInstance(),this.mention=aG.getInstance(),this.promptContextEngine=ZFe.getInstance()}staticgetInstance(){returnt.instance||(t.instance=newt),t.instance}asyncprocessMessageContext(e,r,n,o,i,a,s,u,l=[],c){try{B(`[ContextManager] Processing context for message ${e.id}`);letd=e.originalMessage||e.message,{processedPrompt:f,includedFiles:p}=awaitgce(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(H=>H.path),...l.map(H=>H.path),...h]),_=newSet,O=(e.context?.notes||[]).filter(H=>!h.has(H.path));i&&o!=="project"&&a&&!b.has(a.path)&&!O.some(H=>H.path===a.path)&&O.push(a);letT=awaitthis.contextProcessor.processContextNotes(b,r,n,O,i,a,o);O.forEach(H=>{b.add(H.path),_.add(H.path)});letP=e.context?.tags||[],M="",I=[];if(P.length>0){letre=sge(n,P).filter(D=>!b.has(D.path));re.length>0&&(M=awaitthis.contextProcessor.processContextNotes(newSet,r,n,re,!1,null,o),re.forEach(D=>{b.add(D.path),_.add(D.path),I.push(D.path)}))}letj=e.context?.folders||[],A="",k=[];if(j.length>0){letre=j.flatMap(D=>Eee(n,D)).filter(D=>!b.has(D.path));re.length>0&&(A=awaitthis.contextProcessor.processContextNotes(newSet,r,n,re,!1,null,o),re.forEach(D=>{b.add(D.path),_.add(D.path),k.push(D.path)}))}letV=this.contextProcessor.processSelectedTextContexts(),q=e.context?.webTabs||[],J=awaitthis.contextProcessor.processContextWebTabs(q),K=m+T+M+A+g.urlContext+V+J,ue=f+K,Y=(o==="project"?1e6:ae().autoCompactThreshold)*4,se=!1,ie=K;if(ue.length>Y){c?.(Sv.COMPACTING);letre=await(awaitBhi()).compact(K);re.wasCompacted&&(ie=re.content,ue=f+ie,se=!0,B(`[ContextManager] Compacted context: ${re.originalCharCount} -> ${re.compactedCharCount} chars`)),c?.(Sv.DEFAULT)}B(`[ContextManager] Successfully processed context for message ${e.id}`);let$=se?this.buildCompactedEnvelope({chainType:o,message:e,systemPrompt:u||"",processedUserMessage:f,compactedContext:ie,compactedPaths:Array.from(_)}):this.buildPromptContextEnvelope({chainType:o,message:e,systemPrompt:u||"",processedUserMessage:f,l2PreviousContext:m,noteContextAddition:T,tagContextAddition:M,tagNotePaths:I,folderContextAddition:A,folderNotePaths:k,urlContext:g.urlContext,selectedText:V,webTabContext:J});return{processedContent:ue,contextEnvelope:$}}catch(d){returnB(`[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;B(`[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),B(`[ContextManager] Completed context reprocessing for message ${e}`)}buildL2ContextFromPreviousTurns(e,r){letn=r.getDisplayMessages(),o=n.findIndex(l=>l.id===e);if(o===-1||o===0)return{l2Context:"",l2Paths:newSet};leti=n.slice(0,o).filter(l=>l.sender==="user"),a=[],s=newSet,u=-1;for(letl=i.length-1;l>=0;l--)if(i[l].contextEnvelope?.layers?.find(p=>p.id==="L3_TURN")?.segments?.some(p=>p.metadata?.wasCompacted)){u=l;break}for(letl=0;l<i.length;l++){letd=i[l].c
`))}for(let f of d.segments||[]){if(f.metadata?.notePath&&s.add(f.metadata.notePath),f.metadata?.compactedPaths)for(let p of f.metadata.compactedPaths)s.add(p);if(f.metadata?.notePaths)for(let p of f.metadata.notePaths)s.add(p)}}}return{l2Context:a.join(`
`),l2Paths:s}}buildPromptContextEnvelope(e){let r=e.message.id;if(!r)return;let n={};if(e.systemPrompt&&(n.L1_SYSTEM=[{id:"system",content:e.systemPrompt,stable:!0,metadata:{source:"system_prompt"}}]),e.l2PreviousContext){let i=this.parseContextIntoSegments(e.l2PreviousContext,!0);i.length>0&&(n.L2_PREVIOUS=i)}let o=[];if(e.noteContextAddition){let i=this.parseContextIntoSegments(e.noteContextAddition,!1);o.push(...i)}return this.appendTurnContextSegment(o,"tags",e.tagContextAddition,{source:"tags",notePaths:e.tagNotePaths}),this.appendTurnContextSegment(o,"folders",e.folderContextAddition,{source:"folders",notePaths:e.folderNotePaths}),this.appendTurnContextSegment(o,"urls",e.urlContext,{source:"urls"}),this.appendTurnContextSegment(o,"selected_text",e.selectedText,{source:"selected_text"}),this.appendTurnContextSegment(o,"web_tabs",e.webTabContext,{source:"web_tabs"}),o.length>0&&(n.L3_TURN=o),n.L5_USER=[{id:`${r}-user`,content:e.processedUserMessage,stable:!1,metadata:{source:"user_input"}}],this.promptContextEngine.buildEnvelope({conversationId:null,messageId:r,layerSegments:n,metadata:{debugLabel:`message:${r}`,chainType:e.chainType}})}buildCompactedEnvelope(e){let r=e.message.id;if(!r)return;let n={};return e.systemPrompt&&(n.L1_SYSTEM=[{id:"system",content:e.systemPrompt,stable:!0,metadata:{source:"system_prompt"}}]),e.compactedContext.trim()&&(n.L3_TURN=[{id:"compacted_context",content:e.compactedContext,stable:!1,metadata:{source:"compacted",wasCompacted:!0,compactedPaths:e.compactedPaths}}]),n.L5_USER=[{id:`${r}-user`,content:e.processedUserMessage,stable:!1,metadata:{source:"user_input"}}],this.promptContextEngine.buildEnvelope({conversationId:null,messageId:r,layerSegments:n,metadata:{debugLabel:`message:${r}:compacted`,chainType:e.chainType}})}parseContextIntoSegments(e,r){if(!e.trim())return[];let n=[],o=/<(?:note_context|active_note)>[\s\S]*?<\/(?:note_context|active_note)>/g,i;for(;(i=o.exec(e))!==null;){let a=i[0],s=/<path>([^<]+)<\/path>/.exec(a);if(!s)continue;let u=s[1];n.push({id:u,content:a,stable:r,metadata:{source:r?"previous_turns":"current_turn",notePath:u}})}return n}appendTurnContextSegment(e,r,n,o){let i=(n||"").trim();i&&e.push({id:`${r}`,content:i,stable:!1,metadata:o})}createMessageContext(e,r,n=bL()){return{notes:e,urls:r,selectedTextContexts:n}}async extractContextNotes(e,r,n=[]){return[...await mL(e,r),...n].filter((s,u,l)=>l.findIndex(c=>c.path===s.path)===u)}needsContextReprocessing(e){return e.needsContextReprocessing===!0}getSelectedTextContexts(){return bL()}};Zt();_t();var sY=class{constructor(){this.messages=[]}generateId(){return`msg-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}addMessage(e,r,n,o,i){if(typeof e=="object"){let c=e,d=c.id||this.generateId(),f=c.timestamp||eg(new Date),p={id:d,displayText:c.message,processedText:c.originalMessage||c.message,sender:c.sender,timestamp:f,context:c.context,contextEnvelope:c.contextEnvelope,isVisible:c.isVisible!==!1,isErrorMessage:c.isErrorMessage,sources:c.sources,content:c.content,responseMetadata:c.responseMetadata};return this.messages.push(p),B(`[MessageRepository]AddedmessagewithID:${d}`),d}if(r===void 0||n===void 0)throw new Error("processedText and sender are required when using string-based addMessage");let a=e,s=this.generateId(),u=eg(new Date),l={id:s,displayText:a,processedText:r,sender:n,timestamp:u,context:o,contextEnvelope:void 0,isVisible:!0,isErrorMessage:!1,content:i};return this.messages.push(l),B(`[MessageRepository]AddedmessagewithID:${s}`),s}editMessage(e,r){let n=this.messages.find(o=>o.id===e);return n?n.displayText===r?(B(`[MessageRepository]Nochangesneededformessage:${e}`),!0):(n.displayText=r,n.sender==="user"||n.sender==="USER"?B(`[MessageRepository]Editedusermessage${e},needscontextreprocessing`):(n.processedText=r,B(`[MessageRepository]EditedAImessage${e}`)),!0):(B(`[MessageRepository]Messagenotfoundforedit:${e}`),!1)}updateProcessedText(e,r,n){let o=this.messages.find(i=>i.id===e);return o?(o.processedText=r,o.contextEnvelope=n,B(`[MessageRepository]Updatedp
${e}`}generateTopicAsyncIfNeeded(e,r,n){!ae().generateAIChatTitleOnSave||!r||n||(async()=>{try{let i=await this.generateAITopic(e);if(!i)return;await this.applyTopicToFrontmatter(r,i)}catch(i){ne("[ChatPersistenceManager] Error during async topic generation:",i)}})()}async applyTopicToFrontmatter(e,r){try{if(!this.app.fileManager?.processFrontMatter)return;let n=r.trim();await this.app.fileManager.processFrontMatter(e,o=>{o.topic!==n&&(o.topic=n)}),B(`[ChatPersistenceManager]AppliedAItopictochatfile:${e.path}`)}catch(n){ne("[ChatPersistenceManager] Error applying AI topic to file:",n)}}isNameTooLongError(e){if(!e)return!1;let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("enametoolong")||n.includes("name too long")}isFileAlreadyExistsError(e){return e?(e instanceof Error?e.message:String(e)).toLowerCase().includes("already exists"):!1}};Or();SJ();CX();var eke=class{constructor(e,r,n,o){this.messageRepo=e;this.chainManager=r;this.fileParserManager=n;this.plugin=o;this.projectMessageRepos=new Map;this.defaultProjectKey="defaultProjectKey";this.lastKnownProjectId=null;this.contextManager=QFe.getInstance(),this.projectMessageRepos.set(this.defaultProjectKey,e),this.persistenceManager=new lfe(o.app,e,r)}getCurrentMessageRepo(){let e=this.plugin.projectManager.getCurrentProjectId(),r=e??this.defaultProjectKey;if(this.lastKnownProjectId!==e&&(B(`[ChatManager]Projectchangedfrom${this.lastKnownProjectId}to${e}`),this.lastKnownProjectId=e),!this.projectMessageRepos.has(r)){B(`[ChatManager]Creatingnewmessagerepositoryforproject:${r}`);let o=new sY;this.projectMessageRepos.set(r,o)}let n=this.projectMessageRepos.get(r);return this.persistenceManager=new lfe(this.plugin.app,n,this.chainManager),n}setOnMessageCreatedCallback(e){this.onMessageCreatedCallback=e}async processSystemPromptTemplates(e,r,n){if(!e.includes("{")||!e.includes("}"))return{processedPrompt:e,includedFiles:[]};if(!ae().enableCustomPromptTemplating)return{processedPrompt:e,includedFiles:[]};try{let i=await gce(e,"",r,n,!0);return{processedPrompt:i.processedPrompt.trimEnd(),includedFiles:i.includedFiles}}catch(i){return Be("[ChatManager] Error processing system prompt templates:",i),{processedPrompt:e,includedFiles:[]}}}injectProcessedUserCustomPromptIntoSystemPrompt(e){let{systemPromptWithoutMemory:r,userCustomPrompt:n,processedUserCustomPrompt:o}=e,i=/<user_custom_instructions>\n[\s\S]*?\n<\/user_custom_instructions>/;return i.test(r)?r.replace(i,()=>`<user_custom_instructions>
${o}
</user_custom_instructions>`):r===n?o:(B("[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}`:(B("[ChatManager] basePromptWithMemory does not end with systemPromptWithoutMemory; returning original base prompt."),r)}async getSystemPromptForMessage(e,r,n){let o=z1e(),i=[],a=await MD(this.chainManager.userMemoryManager),s=PD(),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=Uu();if(l){let c=await Nm.instance.getProjectContext(l.id),d=await this.processSystemPromptTemplates(l.systemPrompt,r,n);i.push(...d.includedFiles);let f=`${u}
with CORS Error: `+Sn(l);throw new Error(c)}}let a=await i.json();return{success:!0,models:Bvt(t,a)}}catch(e){return ne(`Error fetching models for ${t}:`,e),{success:!1,models:[],error:Sn(e)}}}async function qnn(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:ab(t.provider),s={name:t.name,provider:t.provider,apiKey:a,enabled:!0},u=!1,l;if(!n)try{await Nm.instance.getCurrentChainManager().chatModelManager.ping(s)}catch(c){u=!0,l=Sn(c),ne("Modelverificationfailed:",c)}return{success:!0,alreadyExists:i,verificationFailed:u,verificationError:l}}function Unn(t){return{name:t.name,provider:t.provider,enabled:!0}}Zt();Jr();var M$=require("obsidian"),Fu=L(X());function Pke({provider:t,isReady:e,expanded:r=!1,skipVerification:n=!1,credentialVersion:o}){let i=zr(),[a,s]=(0,Fu.useState)(null),[u,l]=(0,Fu.useState)(!1),[c,d]=(0,Fu.useState)(null),[f,p]=(0,Fu.useState)(null),[m,h]=(0,Fu.useState)(!1),y=(0,Fu.useRef)(!1),g=(0,Fu.useCallback)(async()=>{if(!(y.current||!e)){y.current=!0,l(!0),d(null);try{let w=await knn(t);w.success?s(w.models):(d(w.error||"Failedtoloadmodels"),new M$.Notice(`Failed to load models for ${tg(t)}: ${w.error}`,5e3))}catch(w){let O=Sn(w);d(O),new M$.Notice(`Failed to load models for ${tg(t)}: ${O}`,5e3)}finally{l(!1),y.current=!1}}},[t,e]);(0,Fu.useEffect)(()=>{s(null),p(null),d(null)},[t,o]),(0,Fu.useEffect)(()=>{r&&e&&a===null&&!u&&!c&&g()},[r,e,a,u,c,g]);let b=async()=>{if(!f){new M$.Notice("Pleaseselectamodelfirst");return}h(!0);try{let w=await qnn({id:f.id,name:f.name,provider:t},i.activeModels,{skipVerification:n});if(w.alreadyExists)w.verificationFailed?new M$.Notice(`Model ${f.name} already exists (verification failed: ${w.verificationError})`,1e4):new M$.Notice(`Model ${f.name} verified successfully! It already exists in your models list.`);else{let O=Unn({id:f.id,name:f.name,provider:t}),T=[...i.activeModels,O];Ue("activeModels",T),w.verificationFailed?new M$.Notice(`Model ${f.name} added (verification failed: ${w.verificationError})`,1e4):new M$.Notice(`Model ${f.name} verified and added to your models list!`)}}catch(w){ne("Erroraddingmodel:",w),new M$.Notice(`Failed to add model: ${Sn(w)}`)}finally{h(!1)}},_=a?.filter((w,O,T)=>T.findIndex(P=>P.id===w.id)===O).sort((w,O)=>w.name.localeCompare(O.name));return Fu.default.createElement(qo,{label:"Model",description:"Addtheselectedmodeltoyourmodelslist.Afteradding,checktheModelTab."},Fu.default.createElement("div",null,Fu.default.createElement("div",{className:"tw-flextw-items-centertw-gap-2"},Fu.default.createElement("div",{className:"tw-flex-1"},Fu.default.createElement(wA,{options:_?.map(w=>({label:w.name,value:w.id}))||[],onChange:w=>{let O=w.target.value,T=a?.find(P=>P.id===O);T&&p(T)},onClick:()=>{a===null&&!u&&g()},value:f?.id||"",placeholder:"SelectModel",disabled:!e||u})),Fu.default.createElement("div",{className:"tw-w-[72px]"},Fu.default.createElement(ge,{onClick:b,disabled:!f||m,variant:"secondary",size:"sm",className:"tw-w-fulltw-whitespace-nowrap"},m?Fu.default.createElement(du,{className:"tw-mr-2tw-size-4tw-animate-spin"}):"Add"))),Fu.default.createElement("div",{className:"tw-mt-1tw-text-xs"},u&&Fu.default.createElement("div",{className:"tw-p-1tw-text-muted"},"Loadingmodels..."),c&&Fu.default.createElement("div",{className:"tw-p-1tw-text-error"},"Failedtoloadmodels.",c),a&&a.length===0&&Fu.default.createElement("div",{className:"tw-p-1tw-text-muted"},"Nomodelsavailable."),a===null&&!u&&!c&&Fu.default.createElement("div",{className:"tw-p-1tw-text-muted"},"Clicktoloadavailablemodels."))))}Jr();var I$=require("obsidian"),Ar=L(X());function Bnn(){let t=zr(),[e]=(0,Ar.useState)(()=>Fq.getInstance()),[r,n]=(0,Ar.useState)("idle"),[o,i]=(0,Ar.useState)(null),[a,s]=(0,Ar.useState)(null),[u,l]=(0,Ar.useState)(!1),c=(0,Ar.useRef)(0),d=(0,Ar.useRef)(!0);(0,Ar.useEffect)(()=>(d.current=!0,()=>{d.current=!1,c.current+=1,e.abortPolling()}),[e]),(0,Ar.useEffect)(()=>{e.getAuthState().status==="authenticated"&&n("done")},[e
`)}async function ibi(t,e){let r=[],n=t.provider?.trim()??"",o=Rke(n),i=t.baseUrl?.trim()??"",a=EB(i||o||"https://api.example.com/v1"),s=rbi(a),u=t.name?.trim()||"<MODEL_NAME>";t.name?.trim()||r.push("Model name is empty; using placeholder.");let l=await wY(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:Ike}}}:{ok:!0,warnings:r,spec:{method:"POST",url:`${s}/chat/completions`,headers:c,body:{model:u,messages:[{role:"user",content:vY}],stream:!1,max_tokens:Xnn}}}}function abi(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=tbi(a);if(s){let u=EB(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 sbi(t,e){let r=[],n=await wY(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=abi(t,o,e?"embeddings":"chat/completions",i);r.push(...s.warnings);let u=e?{input:Ike}:{messages:[{role:"user",content:vY}],stream:!1,max_tokens:Xnn};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 ubi(t){let e=[],r=t.baseUrl?.trim()??"",n=Rke("anthropic"),o=EB(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 wY(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":Gyi},body:{model:u,max_tokens:Zyi,messages:[{role:"user",content:vY}]}}}}async function lbi(t,e){let r=[],n=t.baseUrl?.trim()??"",o=Rke("google"),a=nbi(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 wY(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:Ike}]}}}}:{ok:!0,warnings:r,spec:{method:"POST",url:`${a}/${u}:generateContent`,headers:c,body:{contents:[{role:"user",parts:[{text:vY}]}],generationConfig:{maxOutputTokens:Qyi}}}}}function cbi(t){return/(^|\.)anthropic\./.test(t)}async function dbi(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=`${EB(o||`https://bedrock-runtime.${n}.amazonaws.com`)}/model/${encodeURIComponent(r)}/invoke`,s={messages:[{role:"user",content:[{type:"text",text:vY}]}],max_tokens:Yyi};cbi(r)?s.anthropic_version=Xyi:e.push("Model ID does not look like Anthropic; request body may need adjust
`),warnings:e}}async function fbi(t,e){let r=[],n=t.baseUrl?.trim()??"",o=Rke("ollama"),i=obi(EB(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 wY(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:Ike,truncate:!0}}}:{ok:!0,warnings:r,spec:{method:"POST",url:`${i}/api/chat`,headers:s,body:{model:a,messages:[{role:"user",content:vY}],stream:!1}}}}async function Znn(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 sbi(t,n);return o.ok?{ok:!0,command:k3(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 ubi(t);return o.ok?{ok:!0,command:k3(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 dbi(t);if(r==="google"||r==="google"){let o=await lbi(t,n);return o.ok?{ok:!0,command:k3(o.spec),warnings:o.warnings}:o}if(r==="ollama"||r==="ollama"){let o=await fbi(t,n);return o.ok?{ok:!0,command:k3(o.spec),warnings:o.warnings}:o}if(ebi.has(r)){let o=await ibi(t,n);return o.ok?{ok:!0,command:k3(o.spec),warnings:o.warnings}:o}return{ok:!1,error:`Provider"${r}"isnotsupportedforcurlgeneration.`,warnings:e}}Jr();pL();var PB=require("obsidian"),Xe=L(X()),zvt=({open:t,onOpenChange:e,onAdd:r,ping:n,isEmbeddingModel:o=!1})=>{let{modalContainer:i}=SB(),a=ae(),s=o?"openai":"openrouterai",u=$=>$==="azure openai",[l,c]=(0,Xe.useState)(null),[d,f]=(0,Xe.useState)(u(s)),[p,m]=(0,Xe.useState)(!1),[h,y]=(0,Xe.useState)("idle"),[g,b]=(0,Xe.useState)({name:!1,instanceName:!1,deploymentName:!1,embeddingDeploymentName:!1,apiVersion:!1,displayName:!1,bedrockRegion:!1}),_=($,H)=>{b(re=>({...re,[$]:H}))},w=()=>{b({name:!1,instanceName:!1,deploymentName:!1,embeddingDeploymentName:!1,apiVersion:!1,displayName:!1,bedrockRegion:!1})},O=()=>{let $=!0,H={...g};return H.name=!P.name,P.name||($=!1),P.provider==="azure openai"&&(H.instanceName=!P.azureOpenAIApiInstanceName,H.apiVersion=!P.azureOpenAIApiVersion,o?(H.embeddingDeploymentName=!P.azureOpenAIApiEmbeddingDeploymentName,P.azureOpenAIApiEmbeddingDeploymentName||($=!1)):(H.deploymentName=!P.azureOpenAIApiDeploymentName,P.azureOpenAIApiDeploymentName||($=!1)),(!P.azureOpenAIApiInstanceName||!P.azureOpenAIApiVersion)&&($=!1)),P.provider,"amazon-bedrock",H.bedrockRegion=!1,b(H),$},T=($=s)=>{let H={name:"",provider:$,enabled:!0,isBuiltIn:!1,baseUrl:"",apiKey:ab($),isEmbeddingModel:o,capabilities:[]};if(!o){let re={...H,stream:!0};return $==="amazon-bedrock"?{...re,bedrockRegion:a.amazonBedrockRegion}:re}return H},[P,M]=(0,Xe.useState)(T()),I=$=>{M(H=>({...H,...$})),y("idle")},j=$=>({...$,name:$.name?.trim(),baseUrl:$.baseUrl?.trim(),apiKey:$.apiKey?.trim(),openAIOrgId:$.openAIOrgId?.trim(),azureOpenAIApiInstanceName:$.azureOpenAIApiInstanceName?.trim(),azureOpenAIApiDeploymentName:$.azureOpenAIApiDeploymentName?.trim(),azureOpenAIApiEmbeddingDeploymentName:$.azureOpenAIApiEmbeddingDeploymentName?.trim(),azureOpenAIApiVersion:$.azureOpenAIApiVersion?.trim(),bedrockRegion:$.bedrockRegion?.trim()}),[A,k]=(0,Xe.useState)(dN(s)),V=()=>!!(P.name&&P.provider),q=()=>p||!V(),J=()=>{if(!O()){new PB.Notice("Please fill in all required fields");return}let $=j(P);r($),e(!1),M(T()),w(),y("idle"),f(!1)},K=$=>{k(dN($)),y("idle"),M({...P,provider:$,apiKey:ab($),...$==="openai"?{openAIOrgId:a.openAIOrgId}:{},...$==="azure openai"?{azureOpenAIApiInstanceName:a.azureOpenAIApiInstanceName,azureOpenAIApiDeploymentName:a.azureOpenAIApiDeploymentName,azureOpenAIApiVersion:a.azureOpenAIApiVersion,azureOpenAIApiEmbeddingDeploymentName:a.azureOpenAIApiEmbeddingDeploymentName
Use 'Refresh Vault Index' or 'Force Reindex Vault' commands to build the index after enabling. Pick your embedding model below.`:`Disabling semantic search will fall back to index-free lexical search (less resource-intensive, could be less accurate).
Your existing index will be preserved but not used.`,i=n?"Enable Semantic Search":"Disable Semantic Search",a=n?"Enable":"Disable";super(e,r,o,i,a,"Cancel")}};to();Or();ot();varion=require("obsidian"),tn=L(X()),aon=()=>{lett=zr(),e=asyncr=>{if(r!==t.embeddingModelKey){if(t.enableSemanticSearchV3){newFke(app,async()=>{Ue("embeddingModelKey",r),await(awaitPromise.resolve().then(()=>(Am(),xg))).default.getInstance().indexVaultToVectorStore(!1)}).open();return}Ue("embeddingModelKey",r),newion.Notice("Embedding model saved. Enable Semantic Search to build the index.")}};returntn.default.createElement("div",{className:"tw-space-y-4"},tn.default.createElement("section",null,tn.default.createElement("div",{className:"tw-space-y-4"},tn.default.createElement(on,{type:"switch",title:"Enable Semantic Search",description:"Enable semantic search for meaning-based document retrieval. When disabled, uses fast lexical search only. Use 'Refresh Vault Index' or 'Force Reindex Vault' to build the embedding index.",checked:t.enableSemanticSearchV3,onCheckedChange:r=>{newkke(app,async()=>{Ue("enableSemanticSearchV3",r),r&&await(awaitPromise.resolve().then(()=>(Am(),xg))).default.getInstance().indexVaultToVectorStore(!1)},r).open()}}),tn.default.createElement(on,{type:"switch",title:"Enable Inline Citations (experimental)",description:"When enabled, AI responses will include footnote-style citations within the text and numbered sources at the end. This is an experimental feature and may not work as expected for all models.",checked:t.enableInlineCitations,onCheckedChange:r=>Ue("enableInlineCitations",r)}),tn.default.createElement(on,{type:"select",title:"Embedding Model",description:tn.default.createElement("div",{className:"tw-space-y-2"},tn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},tn.default.createElement("span",{className:"tw-font-medium tw-leading-none tw-text-accent"},"Powers Semantic Vault Search and Relevant Notes. Enable Semantic Search to use it."),tn.default.createElement(xi,{content:tn.default.createElement("div",{className:"tw-flex tw-max-w-96 tw-flex-col tw-gap-2"},tn.default.createElement("div",{className:"tw-pt-2 tw-text-sm tw-text-muted"},"This model converts text into vector representations, essential for semantic search and Question Answering (QA) functionality. Changing the embedding model will:"),tn.default.createElement("ul",{className:"tw-pl-4 tw-text-sm tw-text-muted"},tn.default.createElement("li",null,"Require rebuilding your vault's vector index"),tn.default.createElement("li",null,"Affect semantic search quality"),tn.default.createElement("li",null,"Impact Question Answering feature performance")))}))),value:t.embeddingModelKey,onChange:e,options:t.activeEmbeddingModels.map(r=>({label:cX(r),value:oo(r)})),placeholder:"Model"}),tn.default.createElement(on,{type:"select",title:"Auto-Index Strategy",description:tn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},tn.default.createElement("span",{className:"tw-leading-none"},"Decide when you want the vault to be indexed."),tn.default.createElement(xi,{content:tn.default.createElement("div",{className:"tw-space-y-2 tw-py-2"},tn.default.createElement("div",{className:"tw-space-y-1"},tn.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Choose when to index your vault:"),tn.default.createElement("ul",{className:"tw-list-disc tw-space-y-1 tw-pl-2 tw-text-sm"},tn.default.createElement("li",null,tn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},tn.default.createElement("strong",{className:"tw-inline-block tw-whitespace-nowrap"},"NEVER:"),tn.default.createElement("span",null,"Manual indexing via command or refresh only"))),tn.default.createElement("li",null,tn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},tn.default.createElement("strong",{className:"tw-inline-block tw-whitespace-nowrap"},"ON STARTUP:"),tn.default.createElement("span",null,"Index updates when plugin loads or reloads"))),tn.default.createElement("li",null,tn.default.c
* 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/square-pen.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/tag.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/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
* derived from CryptoJS.mode.CTR
* Jan Hruby jhruby.web@gmail.com
*)
@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