Files
Obsidian/.obsidian/plugins/copilot/main.js

3492 lines
5.1 MiB
JavaScript
Raw Normal View History

2026-02-04 17:04:00 +08:00
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
// Polyfill for import.meta in CommonJS context
if (typeof import_meta === 'undefined') {
var import_meta = {
url: typeof __filename !== 'undefined' ? 'file://' + __filename : 'file:///obsidian-plugin'
};
}
var Usn=Object.create;var MY=Object.defineProperty;var Bsn=Object.getOwnPropertyDescriptor;var zsn=Object.getOwnPropertyNames;var Vsn=Object.getPrototypeOf,Hsn=Object.prototype.hasOwnProperty;var Iwt=t=>{throw TypeError(t)};var Jsn=(t,e,r)=>e in t?MY(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var v=(t,e)=>()=>(t&&(e=t(t=0)),e);var S=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Rn=(t,e)=>{for(var r in e)MY(t,r,{get:e[r],enumerable:!0})},Rwt=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of zsn(e))!Hsn.call(t,o)&&o!==r&&MY(t,o,{get:()=>e[o],enumerable:!(n=Bsn(e,o))||n.enumerable});return t};var L=(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);var x=(t,e,r)=>Jsn(t,typeof e!="symbol"?e+"":e,r),Wsn=(t,e,r)=>e.has(t)||Iwt("Cannot "+r);var aqe=(t,e,r)=>e.has(t)?Iwt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r);var Awt=(t,e,r)=>(Wsn(t,e,"access private method"),r);function sqe(){if(!Vfe&&(Vfe=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Vfe))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Vfe(Ksn)}var Vfe,Ksn,Nwt=v(()=>{Ksn=new Uint8Array(16)});function jwt(t,e=0){return Wh[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]]}var Wh,Dwt=v(()=>{Wh=[];for(let t=0;t<256;++t)Wh.push((t+256).toString(16).slice(1))});var Gsn,uqe,$wt=v(()=>{Gsn=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),uqe={randomUUID:Gsn}});function Xsn(t,e,r){if(uqe.randomUUID&&!e&&!t)return uqe.randomUUID();t=t||{};let n=t.random||(t.rng||sqe)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){r=r||0;for(let o=0;o<16;++o)e[r+o]=n[o];return e}return jwt(n)}var Zm,Lwt=v(()=>{$wt();Nwt();Dwt();Zm=Xsn});var D$=v(()=>{Lwt()});var Zsn,Rt,Bo=v(()=>{Zsn=Object.defineProperty,Rt=(t,e)=>{for(var r in e)Zsn(t,r,{get:e[r],enumerable:!0})}});function IY(t,e=AB){t=t.trim();let r=t.indexOf("```");if(r===-1)return e(t);let n=t.substring(r+3);n.startsWith(`json
`)?n=n.substring(5):n.startsWith("json")?n=n.substring(4):n.startsWith(`
`)&&(n=n.substring(1));let o=n.indexOf("```"),i=n;return o!==-1&&(i=n.substring(0,o)),e(i.trim())}function Ysn(t){try{return JSON.parse(t)}catch{}let e=t.trim();if(e.length===0)throw new Error("Unexpected end of JSON input");let r=0;function n(){for(;r<e.length&&/\s/.test(e[r]);)r+=1}function o(){if(e[r]!=='"')throw new Error(`Expected '"' at position ${r}, got '${e[r]}'`);r+=1;let c="",d=!1;for(;r<e.length;){let f=e[r];if(d){if(f==="n")c+=`
`;else if(f==="t")c+=" ";else if(f==="r")c+="\r";else if(f==="\\")c+="\\";else if(f==='"')c+='"';else if(f==="b")c+="\b";else if(f==="f")c+="\f";else if(f==="/")c+="/";else if(f==="u"){let p=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;else throw new Error(`Invalid unicode escape sequence '\\u${p}' at position ${r}`)}else throw new Error(`Invalid escape sequence '\\${f}' at position ${r}`);d=!1}else if(f==="\\")d=!0;else{if(f==='"')return r+=1,c;c+=f}r+=1}return d&&(c+="\\"),c}function i(){let c=r,d="";if(e[r]==="-"&&(d+="-",r+=1),r<e.length&&e[r]==="0"&&(d+="0",r+=1,e[r]>="0"&&e[r]<="9"))throw new Error(`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;let f=Number.parseFloat(d);if(Number.isNaN(f))throw r=c,new Error(`Invalid number '${d}' at position ${c}`);return f}function a(){if(n(),r>=e.length)throw new Error(`Unexpected end of input at position ${r}`);let c=e[r];if(c==="{")return u();if(c==="[")return s();if(c==='"')return o();if("null".startsWith(e.substring(r,r+4)))return r+=Math.min(4,e.length-r),null;if("true".startsWith(e.substring(r,r+4)))return r+=Math.min(4,e.length-r),!0;if("false".startsWith(e.substring(r,r+5)))return r+=Math.min(5,e.length-r),!1;if(c==="-"||c>="0"&&c<="9")return i();throw new Error(`Unexpected character '${c}' at position ${r}`)}function s(){if(e[r]!=="[")throw new Error(`Expected '[' at position ${r}, got '${e[r]}'`);let c=[];if(r+=1,n(),r>=e.length)return c;if(e[r]==="]")return r+=1,c;for(;r<e.length;){if(n(),r>=e.length||(c.push(a()),n(),r>=e.length))return c;if(e[r]==="]")return r+=1,c;if(e[r]===","){r+=1;continue}throw new Error(`Expected ',' or ']' at position ${r}, got '${e[r]}'`)}return c}function u(){if(e[r]!=="{")throw new Error(`Expected '{' at position ${r}, got '${e[r]}'`);let c={};if(r+=1,n(),r>=e.length)return c;if(e[r]==="}")return r+=1,c;for(;r<e.length;){if(n(),r>=e.length)return c;let d=o();if(n(),r>=e.length)return c;if(e[r]!==":")throw new Error(`Expected ':' at position ${r}, got '${e[r]}'`);if(r+=1,n(),r>=e.length||(c[d]=a(),n(),r>=e.length))return c;if(e[r]==="}")return r+=1,c;if(e[r]===","){r+=1;continue}throw new Error(`Expected ',' or '}' at position ${r}, got '${e[r]}'`)}return c}let l=a();if(n(),r<e.length)throw new Error(`Unexpected character '${e[r]}' at position ${r}`);return l}function AB(t){try{return typeof t>"u"?null:Ysn(t)}catch{return null}}var RY=v(()=>{});function $$(t,e){return t.lc_error_code=e,t.message=`${t.message}
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
`,t}var AY=v(()=>{});var kwt=S((qbi,Fwt)=>{"use strict";Fwt.exports=function(t,e){if(typeof t!="string")throw new TypeError("Expected a string");return e=typeof e>"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()}});var Jwt=S((Ubi,lqe)=>{"use strict";var Qsn=/[\p{Lu}]/u,eun=/[\p{Ll}]/u,qwt=/^[\p{Lu}](?![\p{Lu}])/gu,zwt=/([\p{Alpha}\p{N}_]|$)/u,Vwt=/[_.\- ]+/,tun=new RegExp("^"+Vwt.source),Uwt=new RegExp(Vwt.source+zwt.source,"gu"),Bwt=new RegExp("\\d+"+zwt.source,"gu"),run=(t,e,r)=>{let n=!1,o=!1,i=!1;for(let a=0;a<t.length;a++){let s=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)}return t},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(!(typeof t=="string"||Array.isArray(t)))throw new TypeError("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"";let r=e.locale===!1?i=>i.toLowerCase():i=>i.toLocaleLowerCase(e.locale),n=e.locale===!1?i=>i.toUpperCase():i=>i.toLocaleUpperCase(e.locale);return t.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});function Kwt(t,e){return e?.[t]||(0,Wwt.default)(t)}function Gwt(t,e,r){let n={};for(let o in t)Object.hasOwn(t,o)&&(n[e(o,r)]=t[o]);return n}var Wwt,iun,Xwt=v(()=>{Wwt=L(kwt(),1),iun=L(Jwt(),1)});function aun(t){return"lc"in t||Object.keys(t).length===1&&Zwt in t}function sun(t){return{[Zwt]:t}}function uun(t){return t!==null&&typeof t=="object"&&"lc_serializable"in t&&typeof t.toJSON=="function"}function lun(t){let e;return t!==null&&typeof t=="object"?"lc_id"in t&&Array.isArray(t.lc_id)?e=t.lc_id:e=[t.constructor?.name??"Object"]:e=[typeof t],{lc:1,type:"not_implemented",id:e}}function Hfe(t,e=new WeakSet){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){if(e.has(t))return lun(t);if(uun(t))return t;e.add(t);let r=t;if(aun(r))return e.delete(t),sun(r);let n={};for(let[o,i]of Object.entries(r))n[o]=Hfe(i,e);return e.delete(t),n}return Array.isArray(t)?t.map(r=>Hfe(r,e)):t}var Zwt,Ywt=v(()=>{Zwt="__lc_escaped__"});function Qwt(t){return Array.isArray(t)?[...t]:{...t}}function dun(t,e){let r=Qwt(t);for(let[n,o]of Object.entries(e)){let[i,...a]=n.split(".").reverse(),s=r;for(let u of a.reverse()){if(s[u]===void 0)break;s[u]=Qwt(s[u]),s=s[u]}s[i]!==void 0&&(s[i]={lc:1,type:"secret",id:[o]})}return r}function Jfe(t){let e=Object.getPrototypeOf(t);return typeof t.lc_name=="function"&&(typeof e.lc_name!="function"||t.lc_name()!==e.lc_name())?t.lc_name():t.name}var cun,Kh,L$=v(()=>{Bo();Xwt();Ywt();cun={};Rt(cun,{Serializable:()=>Kh,get_lc_unique_name:()=>Jfe});Kh=class eSt{constructor(e,...r){x(this,"lc_serializable",!1);x(this,"lc_kwargs");this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([n])=>this.lc_serializable_keys?.includes(n))):this.lc_kwargs=e??{}}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Jfe(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof eSt||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let e={},r={},n=Object.keys(this.lc_kwargs).reduce((u,l)=>(u[l]=l in this?this[l]:this.lc_kwargs[l],u),{});for(let u=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=>{let l=this,c=n,[d,...f]
`)}var hSt=v(()=>{});function Hg(t,e){return typeof t=="string"?t===""?e:typeof e=="string"?t+e:Array.isArray(e)&&e.length===0?t:Array.isArray(e)&&e.some(r=>Ym(r))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e]:Array.isArray(e)?NB(t,e)??[...t,...e]:e===""?t:Array.isArray(t)&&t.some(r=>Ym(r))?[...t,{type:"file",source_type:"text",text:e}]:[...t,{type:"text",text:e}]}function Qfe(t,e){return t==="error"||e==="error"?"error":"success"}function vun(t,e){function r(n,o){if(typeof n!="object"||n===null||n===void 0)return n;if(o>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(a=>r(a,o+1));let i={};for(let a of Object.keys(n))i[a]=r(n[a],o+1);return i}return JSON.stringify(r(t,0),null,2)}function ySt(t){return Array.isArray(t)&&t.every(e=>typeof e.index=="number")}function El(t,e){if(t===void 0&&e===void 0)return;if(t===void 0||e===void 0)return t??e;let r={...t};for(let[n,o]of Object.entries(e))if(r[n]==null)r[n]=o;else{if(o==null)continue;if(typeof r[n]!=typeof o||Array.isArray(r[n])!==Array.isArray(o))throw new Error(`field[${n}] already exists in the message chunk, but with a different type.`);if(typeof r[n]=="string"){if(n==="type")continue;["id","name","output_version","model_provider"].includes(n)?o&&(r[n]=o):r[n]+=o}else if(typeof r[n]=="number")r[n]=r[n]+o;else if(typeof r[n]=="object"&&!Array.isArray(r[n]))r[n]=El(r[n],o);else if(Array.isArray(r[n]))r[n]=NB(r[n],o);else{if(r[n]===o)continue;console.warn(`field[${n}] already exists in this message chunk and value has unsupported type.`)}}return r}function NB(t,e){if(!(t===void 0&&e===void 0)){if(t===void 0||e===void 0)return t||e;{let r=[...t];for(let n of e)if(typeof n=="object"&&n!==null&&"index"in n&&typeof n.index=="number"){let o=r.findIndex(i=>{let a=typeof i=="object",s="index"in i&&i.index===n.index,u="id"in i&&"id"in n&&i?.id===n?.id,l=!("id"in i)||!i?.id||!("id"in n)||!n?.id;return a&&s&&(u||l)});o!==-1&&typeof r[o]=="object"&&r[o]!==null?r[o]=El(r[o],n):r.push(n)}else{if(typeof n=="object"&&n!==null&&"text"in n&&n.text==="")continue;r.push(n)}return r}}}function epe(t,e){if(!(t===void 0&&e===void 0)){if(t===void 0||e===void 0)return t??e;if(typeof t!=typeof e)throw new Error(`Cannot merge objects of different types.
Left ${typeof t}
Right ${typeof e}`);if(typeof t=="string"&&typeof e=="string")return t+e;if(Array.isArray(t)&&Array.isArray(e))return NB(t,e);if(typeof t=="object"&&typeof e=="object")return El(t,e);if(t===e)return t;throw new Error(`Can not merge objects of different types.
Left ${t}
Right ${e}`)}}function tpe(t){return typeof t.role=="string"}function Gh(t){return typeof t?._getType=="function"}function K3(t){return Jy.isInstance(t)}var hqe,gSt,Uc,Jy,Jg=v(()=>{L$();DY();dqe();fqe();pqe();mqe();hSt();hqe=Symbol.for("langchain.message");Uc=class extends Kh{constructor(e){let r=typeof e=="string"||Array.isArray(e)?{content:e}:e;r.additional_kwargs||(r.additional_kwargs={}),r.response_metadata||(r.response_metadata={});super(r);x(this,"lc_namespace",["langchain_core","messages"]);x(this,"lc_serializable",!0);x(this,gSt,!0);x(this,"id");x(this,"name");x(this,"content");x(this,"additional_kwargs");x(this,"response_metadata");this.name=r.name,r.content===void 0&&r.contentBlocks!==void 0?(this.content=r.contentBlocks,this.response_metadata={output_version:"v1",...r.response_metadata}):r.content!==void 0?(this.content=r.content??[],this.response_metadata=r.response_metadata):(this.content=[],this.response_metadata=r.response_metadata),this.additional_kwargs=r.additional_kwargs,this.id=r.id}get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}_getType(){return this.type}getType(){return this._getType()}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e=="string"?e:e.type==="text"?e.text:"").join(""):""}get contentBlocks(){let e=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[lSt,Zfe,sSt].reduce((o,i)=>i(o),e)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(e){return typeof e=="object"&&e!==null&&hqe in e&&e[hqe]===!0&&Yfe(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[(gSt=hqe,Symbol.toStringTag)](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;let r=vun(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${r}`}toFormattedString(e="pretty"){return mSt(this,e)}};Jy=class bSt extends Uc{static isInstance(e){if(!super.isInstance(e))return!1;let r=Object.getPrototypeOf(e);for(;r!==null;){if(r===bSt.prototype)return!0;r=Object.getPrototypeOf(r)}return!1}}});function $Y(t){return t!=null&&typeof t=="object"&&"lc_direct_tool_output"in t&&t.lc_direct_tool_output===!0}function LY(t){let e=[],r=[];for(let n of t)if(n.function){let o=n.function.name;try{let i=JSON.parse(n.function.arguments);e.push({name:o||"",args:i||{},id:n.id})}catch{r.push({name:o,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[e,r]}function FY(t){return typeof t=="object"&&t!==null&&"getType"in t&&typeof t.getType=="function"&&t.getType()==="tool"}function gqe(t){return t._getType()==="tool"}var wun,Wg,Iw,G3=v(()=>{Bo();Jg();wun={};Rt(wun,{ToolMessage:()=>Wg,ToolMessageChunk:()=>Iw,defaultToolCallParser:()=>LY,isDirectToolOutput:()=>$Y,isToolMessage:()=>FY,isToolMessageChunk:()=>gqe});Wg=class extends Uc{constructor(e,r,n){let o=typeof e=="string"||Array.isArray(e)?{content:e,name:n,tool_call_id:r}:e;super(o);x(this,"lc_direct_tool_output",!0);x(this,"type","tool");x(this,"status");x(this,"tool_call_id");x(this,"metadata");x(this,"artifact");this.tool_call_id=o.tool_call_id,this.artifact=o.artifact,this.status=o.status,this.metadata=o.metadata}static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}static isInstance(e){return super.isInstance(e)&&e.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},Iw=class extends Jy{constructor(e){super(e);x(this,"type","tool");x(this,"tool_call_id");x(this,"status");x(this,"artifact");this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}concat(e){let r=this.constructor;return new r({content:Hg(this.content,e.content),additional_kwargs:El(this.addit
Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(n!=null&&o===void 0){let[i,a]=LY(n);r.tool_calls=i??[],r.invalid_tool_calls=a??[]}else r.tool_calls=r.tool_calls??[],r.invalid_tool_calls=r.invalid_tool_calls??[]}catch{r.tool_calls=[],r.invalid_tool_calls=[]}if(r.response_metadata!==void 0&&"output_version"in r.response_metadata&&r.response_metadata.output_version==="v1"&&(r.contentBlocks=r.content,r.content=void 0),r.contentBlocks!==void 0){r.tool_calls&&r.contentBlocks.push(...r.tool_calls.map(a=>({type:"tool_call",id:a.id,name:a.name,args:a.args})));let i=r.contentBlocks.filter(a=>a.type==="tool_call").filter(a=>!r.tool_calls?.some(s=>s.id===a.id&&s.name===a.name));i.length>0&&(r.tool_calls=i.map(a=>({type:"tool_call",id:a.id,name:a.name,args:a.args})))}}super(r);x(this,"type","ai");x(this,"tool_calls",[]);x(this,"invalid_tool_calls",[]);x(this,"usage_metadata");typeof r!="string"&&(this.tool_calls=r.tool_calls??this.tool_calls,this.invalid_tool_calls=r.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=r.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let r=bqe(this.response_metadata.model_provider);if(r)return r.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls){let r=this.tool_calls.filter(n=>!e.some(o=>o.id===n.id&&o.name===n.name));e.push(...r.map(n=>({type:"tool_call",id:n.id,name:n.name,args:n.args})))}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}};Ir=class extends Jy{constructor(e){let r;if(typeof e=="string"||Array.isArray(e))r={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0||e.tool_call_chunks.length===0)r={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0};else{let n=spe(e.tool_call_chunks??[]);r={...e,tool_call_chunks:n.tool_call_chunks,tool_calls:n.tool_calls,invalid_tool_calls:n.invalid_tool_calls,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(r);x(this,"type","ai");x(this,"tool_calls",[]);x(this,"invalid_tool_calls",[]);x(this,"tool_call_chunks",[]);x(this,"usage_metadata");this.tool_call_chunks=r.tool_call_chunks??this.tool_call_chunks,this.tool_calls=r.tool_calls??this.tool_calls,this.invalid_tool_calls=r.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=r.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let r=bqe(this.response_metadata.model_provider);if(r)return r.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls&&typeof this.content!="string"){let r=this.content.filter(n=>n.type==="tool_call").map(n=>n.id);for(let n of this.tool_calls)n.id&&!r.includes(n.id)&&e.push({...n,type:"tool_call",id:n.id,name:n.name,args:n.args})}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){let r={conten
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(`Got unsupported message type: ${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(`Got unexpected type: ${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]
Context: ${e}`:""}`),Jpe("[Unserializable]");od("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
Context: ${e}`:""}`),typeof o>"u"&&(o=Tfn()),$Ue(t,"",0,[],void 0,0,o);let a;try{eW.length===0?a=JSON.stringify(t,r,n):a=JSON.stringify(t,Pfn(r),n)}catch{return Jpe("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Wpe.length!==0;){let s=Wpe.pop();s.length===4?Object.defineProperty(s[0],s[1],s[3]):s[0][s[1]]=s[2]}}return Jpe(a)}}function DUe(t,e,r,n){var o=Object.getOwnPropertyDescriptor(n,r);o.get!==void 0?o.configurable?(Object.defineProperty(n,r,{value:t}),Wpe.push([n,r,e,o])):eW.push([e,r,t]):(n[r]=t,Wpe.push([n,r,e]))}function $Ue(t,e,r,n,o,i,a){i+=1;var s;if(typeof t=="object"&&t!==null){for(s=0;s<n.length;s++)if(n[s]===t){DUe(xfn,t,e,o);return}if(typeof a.depthLimit<"u"&&i>a.depthLimit){DUe(_Ot,t,e,o);return}if(typeof a.edgesLimit<"u"&&r+1>a.edgesLimit){DUe(_Ot,t,e,o);return}if(n.push(t),Array.isArray(t))for(s=0;s<t.length;s++)$Ue(t[s],s,s,n,t,i,a);else{t=vOt(t);var u=Object.keys(t);for(s=0;s<u.length;s++){var l=u[s];$Ue(t[l],l,s,n,t,i,a)}}n.pop()}}function Pfn(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(eW.length>0)for(var n=0;n<eW.length;n++){var o=eW[n];if(o[1]===e&&o[0]===r){r=o[2],eW.splice(n,1);break}}return t.call(this,e,r)}}var _Ot,xfn,Wpe,eW,Ofn,wOt=v(()=>{VA();_Ot="[...]",xfn={result:"[Circular]"},Wpe=[],eW=[],Ofn=new TextEncoder});function SOt(t,e,r){if(r)return t;let n=Cpe(),o=e??Vqe(),i=t.extra??{},a=i.metadata;return t.extra={...i,runtime:{...n,...i?.runtime},metadata:{...o,...o.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??o.revision_id}:{},...a}},t}async function Rfn(t){let e=[];for await(let r of t)e.push(r);return e}function Kpe(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}function COt(t){return typeof t=="number"?Number(t.toFixed(4)):t}function OOt(t){return"dataset_id"in t||"dataset_name"in t}var Mfn,Ifn,Afn,Nfn,TOt,jfn,Dfn,xOt,LUe,qB,kqe=v(()=>{ype();pCt();Yqe();OCt();TCt();VA();Spe();vpe();bpe();gOt();jUe();Fqe();$qe();wOt();Mfn=t=>{let e=t?.toString()??od("TRACING_SAMPLING_RATE");if(e===void 0)return;let r=parseFloat(e);if(r<0||r>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r},Ifn=t=>{let r=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"};Afn=async t=>{if(t?.status===429){let e=parseInt(t.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(r=>setTimeout(r,e)),!0}return!1};Nfn=24*1024*1024,TOt=1024*1024*1024,jfn=1e4,Dfn=100,xOt="https://api.smith.langchain.com",LUe=class{constructor(e){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=e??TOt}peek(){return this.items[0]}push(e){let r,n=new Promise(i=>{r=i}),o=Hb(e.item,`Serializing run with id: ${e.item.id}`).length;return this.sizeBytes+o>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${o} bytes.`),r(),n):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:r,itemPromise:n,size:o}),this.sizeBytes+=o,n)}pop({upToSizeBytes:e,upToSize:r}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");let n=[],o=0;for(;o+(this.peek()?.size??0)<e&&this.items.length>0&&n.length<r;){let i=this.items.shift();i&&(n.push(i),o+=i.size,this.sizeBytes-=i.size)}if(n.length===0&&this.items.length>0){let i=this.items.shift();n.push(i),o+=i.size,this.sizeBytes-=i.size}return[n.map(i=>({action:i.action,item:i.payload,otelContext:i.otelContext,apiKey:i.apiKey,apiUrl:i.apiUrl,size:i.size})),()=>n.forEach(i=>i.itemPromiseResolve())]}},qB=class t{get _fetch(){ret
=== LangSmith Server Configuration ===
`+JSON.stringify(r,null,2)+`
`),r}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let e=await this._getBatchSizeLimitBytes(),r=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r})}_cloneCurrentOTELContext(){let e=Ope(),r=dCt();if(this.langSmithToOTELTranslator!==void 0){let n=e.getActiveSpan();if(n)return e.setSpan(r.active(),n)}}async createRun(e,r){if(!this._filterForSampling([e]).length)return;let n={...this.headers,"Content-Type":"application/json"},o=e.project_name;delete e.project_name;let i=await this.prepareRunCreateOrUpdateInputs({session_name:o,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){let u=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:i,otelContext:u,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}let a=SOt(i,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(n["x-tenant-id"]=r.workspaceId);let s=Hb(a,`Creating run with id: ${a.id}`);await this.caller.call(async()=>{let u=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await Lr(u,"create run",!0),u})}async batchIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let o=await Promise.all(e?.map(u=>this.prepareRunCreateOrUpdateInputs(u))??[]),i=await Promise.all(r?.map(u=>this.prepareRunCreateOrUpdateInputs(u))??[]);if(o.length>0&&i.length>0){let u=o.reduce((c,d)=>(d.id&&(c[d.id]=d),c),{}),l=[];for(let c of i)c.id!==void 0&&u[c.id]?u[c.id]={...u[c.id],...c}:l.push(c);o=Object.values(u),i=l}let a={post:o,patch:i};if(!a.post.length&&!a.patch.length)return;let s={post:[],patch:[]};for(let u of["post","patch"]){let l=u,c=a[l].reverse(),d=c.pop();for(;d!==void 0;)s[l].push(d),d=c.pop()}if(s.post.length>0||s.patch.length>0){let u=s.post.map(l=>l.id).concat(s.patch.map(l=>l.id)).join(",");await this._postBatchIngestRuns(Hb(s,`Ingesting runs with ids: ${u}`),n)}}async _postBatchIngestRuns(e,r){let n={...this.headers,"Content-Type":"application/json",Accept:"application/json"};r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{let o=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await Lr(o,"batch create run",!0),o})}async multipartIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let o={},i=[];for(let d of e??[]){let f=await this.prepareRunCreateOrUpdateInputs(d);f.id!==void 0&&f.attachments!==void 0&&(o[f.id]=f.attachments),delete f.attachments,i.push(f)}let a=[];for(let d of r??[])a.push(await this.prepareRunCreateOrUpdateInputs(d));if(i.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(a.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(i.length>0&&a.length>0){let d=i.reduce((p,m)=>(m.id&&(p[m.id]=m),p),{}),f=[];for(let p of a)p.id!==void 0&&d[p.id]?d[p.id]={...d[p.id],...p}:f.push(p);i=Object.values(d),a=f}if(i.length===0&&a.length===0)return;let l=[],c=[];for(let[d,f]of[["post",i],["patch",
`])),n.push(new Blob([`Content-Disposition: form-data; name="${a.name}"\r
`,`Content-Type: ${a.payload.type}\r
\r
`])),n.push(a.payload),n.push(new Blob([`\r
`]));return n.push(new Blob([`--${r}--\r
`])),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
`),await a(`Content-Disposition: form-data; name="${s.name}"\r
`),await a(`Content-Type: ${s.payload.type}\r
\r
`);let l=s.payload.stream().getReader();try{let c;for(;!(c=await l.read()).done;)i.enqueue(c.value)}finally{l.releaseLock()}await a(`\r
`)}await a(`--${r}--\r
`),i.close()}})}async _sendMultipartRequest(e,r,n){let o="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),i=rCt(),a=()=>this._createNodeFetchBody(e,o),s=()=>this._createMultipartStream(e,o),u=async l=>this.batchIngestCaller.callWithOptions({sizeBytes:n?.sizeBytes},async()=>{let c=await l(),d={...this.headers,"Content-Type":`multipart/form-data; boundary=${o}`};n?.apiKey!==void 0&&(d["x-api-key"]=n.apiKey);let f=c;n?.useGzip&&typeof c=="object"&&"pipeThrough"in c&&(f=c.pipeThrough(new CompressionStream("gzip")),d["Content-Encoding"]="gzip");let p=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:d,body:f,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Lr(p,"Failed to send multipart request",!0),p});try{let l,c=!1;!i&&!this.multipartStreamingDisabled&&zqe()!=="bun"?(c=!0,l=await u(s)):l=await u(a),(!this.multipartStreamingDisabled||c)&&l.status===422&&(n?.apiUrl??this.apiUrl)!==xOt&&(console.warn(`Streaming multipart upload to ${n?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${r}".`),this.multipartStreamingDisabled=!0,l=await u(a))}catch(l){if(NUe(l))throw l;console.warn(`${l.message.trim()}
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,`Serializing payload to update run with id: ${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} has no app_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(`Child run ${i.id} has no parent`);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
Status: ${i.status}
Message: ${Array.isArray(a.detail)?a.detail.join(`
`):"Unspecified error"}`):new Error(`Failed to list shared examples: ${i.status} ${i.statusText}`);return a.map(s=>({...s,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:r=null,metadata:n=null,upsert:o=!1,projectExtra:i=null,referenceDatasetId:a=null}){let s=o?"?upsert=true":"",u=`${this.apiUrl}/sessions${s}`,l=i||{};n&&(l.metadata=n);let c={name:e,extra:l,description:r};a!==null&&(c.reference_dataset_id=a);let d=JSON.stringify(c);return await(await this.caller.call(async()=>{let m=await this._fetch(u,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:d});return await Lr(m,"create project"),m})).json()}async updateProject(e,{name:r=null,description:n=null,metadata:o=null,projectExtra:i=null,endTime:a=null}){let s=`${this.apiUrl}/sessions/${e}`,u=i;o&&(u={...u||{},metadata:o});let l=JSON.stringify({name:r,extra:u,description:n,end_time:a?new Date(a).toISOString():null});return await(await this.caller.call(async()=>{let f=await this._fetch(s,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await Lr(f,"update project"),f})).json()}async hasProject({projectId:e,projectName:r}){let n="/sessions",o=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)Po(e),n+=`/${e}`;else if(r!==void 0)o.append("name",r);else throw new Error("Must provide projectName or projectId");let i=await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${n}?${o}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Lr(a,"has project"),a});try{let a=await i.json();return i.ok?Array.isArray(a)?a.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:r,includeStats:n}){let o="/sessions",i=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)Po(e),o+=`/${e}`;else if(r!==void 0)i.append("name",r);else throw new Error("Must provide projectName or projectId");n!==void 0&&i.append("include_stats",n.toString());let a=await this._get(o,i),s;if(Array.isArray(a)){if(a.length===0)throw new Error(`Project[id=${e}, name=${r}] not found`);s=a[0]}else s=a;return s}async getProjectUrl({projectId:e,projectName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either projectName or projectId");let n=await this.readProject({projectId:e,projectName:r}),o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");let n=await this.readDataset({datasetId:e,datasetName:r}),o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let e=new URLSearchParams({limit:"1"});for await(let r of this._getPaginated("/sessions",e))return this._tenantId=r[0].tenant_id,r[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:r,nameContains:n,referenceDatasetId:o,referenceDatasetName:i,includeStats:a,datasetVersion:s,referenceFree:u,metadata:l}={}){let c=new URLSearchParams;if(e!==void 0)for(let d of e)c.append("id",d);if(r!==void 0&&c.append("name",r),n!==void 0&&c.append("name_contains",n),o!==void 0)c.append("reference_dataset",o);else if(i!==void 0){let d=await this.readDataset({datasetName:i});c.append("reference_dataset",d.id)}a!==void 0&&c.append("include_stats",a.toString()),s!==void 0&&c.append("dataset_version",s),u!==void 0&&c.append("reference_free",u.toString()),l!==void 0&&c.append("metadata",JSON.stringify(l));for await(let d of this._getPaginated("/sessions",c))yield*d}async deleteProject({projectId:e,projectName:r}){let n;if(e===void 0&&r===void 0)throw new Error("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("Must provide either datasetName or datasetId");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,"update dataset"),u})).json()}async updateDatasetTag(e){let{datasetId:r,datasetName:n,asOf:o,tag:i}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let a=r??(await this.readDataset({datasetName:n})).id;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,"update dataset tags",!0),u})}async deleteDataset({datasetId:e,datasetName:r}){let n="/datasets",o=e;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(o=(await this.readDataset({datasetName:r})).id),o!==void 0)Po(o),n+=`/${o}`;else throw new Error("Must provide datasetName or datasetId");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("Must provide either datasetName or datasetId");if(o&&r)throw new Error("Must provide either datasetName or datasetId, not both");o||(o=(await this.readDataset({datasetName:r})).id),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,"index dataset"),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,"fetch similar examples"),l})).json()).examples}async createExample(e,r,n){if(OOt(e)&&(r!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let o=r?n?.datasetId:e.dataset_id,i=r?n?.datasetName:e.dataset_name;if(o===void 0&&i===void 0)throw new Error("Must provide either datasetName or datasetId");if(o!==void 0&&i!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");o===void 0&&(o=(await this.readDataset({datasetName:i})).id);let a=(r?n?.createdAt:e.created_at)||new Date,s;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
Current tenant: ${n.tenant_handle}
Requested tenant: ${r}`)}async _getLatestCommitHash(e){let n=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await Lr(o,"get latest commit hash"),o})).json();if(n.commits.length!==0)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(e,r){let[n,o,i]=HA(e),a=JSON.stringify({like:r});return(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/likes/${n}/${o}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await Lr(u,`${r?"like":"unlike"} prompt`),u})).json()}async _getPromptUrl(e){let[r,n,o]=HA(e);if(await this._currentTenantIsOwner(r)){let i=await this._getSettings();return o!=="latest"?`${this.getHostUrl()}/prompts/${n}/${o.substring(0,8)}?organizationId=${i.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${i.id}`}else return o!=="latest"?`${this.getHostUrl()}/hub/${r}/${n}/${o.substring(0,8)}`:`${this.getHostUrl()}/hub/${r}/${n}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){for await(let r of this._getPaginated(`/commits/${e}/`,new URLSearchParams,n=>n.commits))yield*r}async*listPrompts(e){let r=new URLSearchParams;r.append("sort_field",e?.sortField??"updated_at"),r.append("sort_direction","desc"),r.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&r.append("is_public",e.isPublic.toString()),e?.query&&r.append("query",e.query);for await(let n of this._getPaginated("/repos",r,o=>o.repos))yield*n}async getPrompt(e){let[r,n,o]=HA(e),a=await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return s?.status===404?null:(await Lr(s,"get prompt"),s)}))?.json();return a?.repo?a.repo:null}async createPrompt(e,r){let n=await this._getSettings();if(r?.isPublic&&!n.tenant_handle)throw new Error(`Cannot create a public prompt without first
creating a LangChain Hub handle.
You can add a handle by creating a public prompt at:
https://smith.langchain.com/prompts`);let[o,i,a]=HA(e);if(!await this._currentTenantIsOwner(o))throw await this._ownerConflictError("create a prompt",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,"create prompt"),d}),{repo:c}=await l.json();return c}async createCommit(e,r,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");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,"create commit"),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("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");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,"update examples"),a})).json()}async uploadExamplesMultipart(e,r=[]){return this._uploadExamplesMultipart(e,r)}async _uploadExamplesMultipart(e,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");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
${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,r){e.child_runs.push(r)}_addRunToRunMap(e){let{dottedOrder:r,microsecondPrecisionDatestring:n}=qUe(new Date(e.start_time).getTime(),e.id,e.execution_order),o={...e},i=this.getRunById(o.parent_run_id);if(o.parent_run_id!==void 0?i?(this._addChildRun(i,o),i.child_execution_order=Math.max(i.child_execution_order,o.child_execution_order),o.trace_id=i.trace_id,i.dotted_order!==void 0&&(o.dotted_order=[i.dotted_order,r].join("."),o._serialized_start_time=n)):o.parent_run_id=void 0:(o.trace_id=o.id,o.dotted_order=r,o._serialized_start_time=n),this.usesRunTreeMap){let a=BUe(o,i);a!==void 0&&this.runTreeMap.set(o.id,a)}else this.runMap.set(o.id,o);return o}async _endTrace(e){let r=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);r?r.child_execution_order=Math.max(r.child_execution_order,e.child_execution_order):await this.persistRun(e),await this.onRunUpdate?.(e),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){let r=e!==void 0&&this.getRunById(e);return r?r.child_execution_order+1:1}_createRunForLLMStart(e,r,n,o,i,a,s,u){let l=this._getExecutionOrder(o),c=Date.now(),d=s?{...i,metadata:s}:i,f={id:n,name:u??e.id[e.id.length-1],parent_run_id:o,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{prompts:r},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:a||[]};return this._addRunToRunMap(f)}async handleLLMStart(e,r,n,o,i,a,s,u){let l=this.getRunById(n)??this._createRunForLLMStart(e,r,n,o,i,a,s,u);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}_createRunForChatModelStart(e,r,n,o,i,a,s,u){let l=this._getExecutionOrder(o),c=Date.now(),d=s?{...i,metadata:s}:i,f={id:n,name:u??e.id[e.id.length-1],parent_run_id:o,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{messages:r},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:a||[]};return this._addRunToRunMap(f)}async handleChatModelStart(e,r,n,o,i,a,s,u){let l=this.getRunById(n)??this._createRunForChatModelStart(e,r,n,o,i,a,s,u);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}async handleLLMEnd(e,r,n,o,i){let a=this.getRunById(r);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.outputs=e,a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...i},await this.onLLMEnd?.(a),await this._endTrace(a),a}async handleLLMError(e,r,n,o,i){let a=this.getRunById(r);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...i},await this.onLLMError?.(a),await this._endTrace(a),a}_createRunForChainStart(e,r,n,o,i,a,s,u,l){let c=this._getExecutionOrder(o),d=Date.now(),f={id:n,name:u??e.id[e.id.length-1],parent_run_id:o,start_time:d,serialized:e,events:[{name:"start",time:new Date(d).toISOString()}],inputs:r,execution_order:c,child_execution_order:c,run_type:s??"chain",child_runs:[],extra:a?{...l,metadata:a}:{...l},tags:i||[]};return this._addRunToRunMap(f)}async handleChainStart(e,r,n,o,i,a,s,u){let l=this.getRunById(n)??this._createRunForChainStart(e,r,n,o,i,a,s,u);return await this.onRunCreate?.(l),await this.onChainStart?.(l),l}async handleChainEnd(e,r,n,o,i){let a=this.getRunById(r);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.outputs=UUe(e,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=UUe(i.inputs,"input")),await this.onChainEnd?.(a),await this._endTrace(a),a}async handleChainError(e,r,n,o,i){let a=this.getRunById(r);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=UUe(i.inputs,"input")),await this.onChainError?.(a),await
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)=>{"use strict";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` to be a positive number");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=>{"use strict";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=>{"use strict";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=>{"use strict";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("Test operation failed","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` property is not one of operations defined in RFC-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` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&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("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,t);dme(f)&&(f=~~f)}if(l>=c){if(r&&e.op==="add"&&f>u.length)throw new Sc("The specified index MUST NOT be greater than the number of elements in the array","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("Test operation failed","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("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return m}if(u=u[f],r&&l<c&&(!u||typeof u!="object"))throw new Sc("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function J$(t,e,r,n=!0,o=!0){if(r&&!Array.isArray(e))throw new Sc("Patch sequence must be an array","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("Test operation failed","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("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(nW[t.op]){if(typeof t.path!="string")throw new Sc("Operation `path` property is not a string","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` property is not present (applicable in `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` property is not present (applicable in `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` property is not present (applicable in `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(`
`))}}});var Eze,Pze=v(()=>{Eze={major:4,minor:0,patch:0}});function Gze(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function VTt(t){if(!Mme.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Gze(r)}function HTt(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function NTt(t,e,r){t.issues.length&&e.issues.push(...Wb(r,t.issues)),e.value[r]=t.value}function jme(t,e,r){t.issues.length&&e.issues.push(...Wb(r,t.issues)),e.value[r]=t.value}function jTt(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...Wb(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function DTt(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(i=>gv(i,n,ad())))}),e}function Mze(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(sW(t)&&sW(e)){let r=Object.keys(e),n=Object.keys(t).filter(i=>r.indexOf(i)!==-1),o={...t,...e};for(let i of n){let a=Mze(t[i],e[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};o[i]=a.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],i=e[n],a=Mze(o,i);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function $Tt(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),ZB(t))return t;let n=Mze(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function Dme(t,e,r){t.issues.length&&e.issues.push(...Wb(r,t.issues)),e.value[r]=t.value}function LTt(t,e,r,n,o,i,a){t.issues.length&&(SQ.has(typeof n)?r.issues.push(...Wb(n,t.issues)):r.issues.push({origin:"map",code:"invalid_key",input:o,inst:i,issues:t.issues.map(s=>gv(s,a,ad()))})),e.issues.length&&(SQ.has(typeof n)?r.issues.push(...Wb(n,e.issues)):r.issues.push({origin:"map",code:"invalid_element",input:o,inst:i,key:n,issues:e.issues.map(s=>gv(s,a,ad()))})),r.value.set(t.value,e.value)}function FTt(t,e){t.issues.length&&e.issues.push(...t.issues),e.value.add(t.value)}function kTt(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function qTt(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function UTt(t,e,r){return ZB(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function BTt(t){return t.value=Object.freeze(t.value),t}function zTt(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(EBe(o))}}var no,tz,Ou,Ize,Rze,Aze,Nze,jze,Dze,$ze,Lze,Fze,kze,qze,Uze,Bze,zze,Vze,Hze,Jze,Wze,Kze,Xze,Zze,Yze,Qze,e4e,$me,t4e,MQ,Lme,r4e,n4e,o4e,i4e,a4e,K$,IQ,s4e,u4e,RQ,l4e,Fme,c4e,d4e,rz,f4e,p4e,m4e,h4e,g4e,y4e,AQ,cW,b4e,_4e,v4e,w4e,S4e,C4e,x4e,NQ,O4e,T4e,E4e,P4e,M4e,jQ=v(()=>{Nme();iW();Tze();Pme();Ime();Ln();Pze();Ln();no=Se("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Eze;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let i of o._zod.onattach)i(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(i,a,s)=>{let u=ZB(i),l;for(let c of a){if(c._zod.def.when){if(!c._zod.def.when(i))continue}else if(u)continue;let d=i.issues.length,f=c._zod.check(i);if(f instanceof Promise&&s?.async===!1)throw new iO;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,i.is
if (${_}.issues.length) {
if (input[${w}] === undefined) {
if (${w} in input) {
newResult[${w}] = undefined;
}
} else {
payload.issues = payload.issues.concat(
${_}.issues.map((iss) => ({
...iss,
path: iss.path ? [${w}, ...iss.path] : [${w}],
}))
);
}
} else if (${_}.value === undefined) {
if (${w} in input) newResult[${w}] = undefined;
} else {
newResult[${w}] = ${_}.value;
}
`)}else{let _=h[b];f.write(`const ${_} = ${m(b)};`),f.write(`
if (${_}.issues.length) payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
...iss,
path: iss.path ? [${XB(b)}, ...iss.path] : [${XB(b)}]
})));`),f.write(`newResult[${XB(b)}] = ${_}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");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:"No matching discriminator",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
`;return e}function RPt(t,e,r){let{firstNode:n,lastNode:o,nodeColors:i,withStyles:a=!0,curveStyle:s="linear",wrapLabelNWords:u=9}=r??{},l=a?`%%{init: {'flowchart': {'curve': '${s}'}}}%%
graph TD;
`:`graph TD;
`;if(a){let m="default",h={[m]:"{0}({1})"};n!==void 0&&(h[n]="{0}([{1}]):::first"),o!==void 0&&(h[o]="{0}([{1}]):::last");for(let[y,g]of Object.entries(t)){let b=g.name.split(":").pop()??"",w=ghn.some(T=>b.startsWith(T)&&b.endsWith(T))?`<p>${b}</p>`:b;Object.keys(g.metadata??{}).length&&(w+=`<hr/><small><em>${Object.entries(g.metadata??{}).map(([T,P])=>`${T} = ${P}`).join(`
`)}</em></small>`);let O=(h[y]??h[m]).replace("{0}",T2e(y)).replace("{1}",w);l+=` ${O}
`}}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(`Found duplicate subgraph '${b}' at '${h} -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(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("&nbsp;<br>&nbsp;")),P=T?` -. &nbsp;${M}&nbsp; .-> `:` -- &nbsp;${M}&nbsp; --> `}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("Let zodToJsonSchema decide on which parser to use"),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}else if(n[u]==="$"){o+=`($|(?=[\r
]))`;continue}}if(r.s&&n[u]==="."){o+=a?`${n[u]}\r
`:`[${n[u]}\r
]`;continue}o+=n[u],n[u]==="\\"?i=!0:a&&n[u]==="]"?a=!1:!a&&n[u]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var 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":
Known schemas:
- ${Object.keys(n).join(`
- `)}`,new Error(We)}let rt=`${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)){let st=m.length,Le=!1;for(let rt=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('", "')}".`})}else m==="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!==void 0&&c!==m&&Ne.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m}".`});if(h!==void 0&&(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!==void 0&&(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!==void 0){let st=`${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.'})}let Tr=[];if(_!==void 0){let st=`${s}/anyOf`,Le=Ne.length,rt=!1;for(let Fe=0;Fe<_.length;Fe++){let We=_[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!==void 0){let st=`${s}/allOf`,Le=Ne.length,rt=!0;for(let Fe=0;Fe<w.length;Fe++){let We=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!==void 0){let st=`${s}/oneOf`,Le=Ne.length,rt=O.filter((Fe,We)=>{let ke=Object.create(u),Lt=qu(t,Fe,r,n,o,p===!0?i:null,a,`${st}/${We}`,ke);return Ne.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!==void 0){let st=`${s}/if`;if(qu(t,T,r,n,o,i,a,st,u).valid){if(P!==void 0){let rt=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)}}else if(M!==void 0){let rt=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!==void 0)for(let Fe of g)Fe in t||Ne.push({instanceLocation:a,keyword:"required",keywordLocation:`${s}/required`,error:`Instance does not have required property "${Fe}".`});let st=Object.keys(t);if(q!==void 0&&st.length<q&&Ne.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${q} properties.`}),J!==void 0&&st.length>J&&Ne.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${J} properties.`}),K!==void 0){let Fe=`${s}/propertyNames`;for(let We in t){let ke=`${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
data: ${JSON.stringify(o)}
`));n.enqueue(e.encode(`event: end
`)),n.close()}});return Qy.fromReadableStream(r)}var kMt=v(()=>{nO()});function hVe(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}function $he(t){return typeof t=="object"&&t!==null&&typeof t[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;yield r}}async function*Lhe(t,e){let r=e[Symbol.asyncIterator]();for(;;){let{value:n,done:o}=await eh.runWithConfig(Yy(t),r.next.bind(e),!0);if(o)break;yield n}}var qMt,UMt=v(()=>{HB();JB();rO();qMt=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function"});function ud(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function vyn(t){if(tme(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}function bv(t){if(typeof t=="function")return new Yb({func:t});if(Vo.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){let e={};for(let[r,n]of Object.entries(t))e[r]=bv(n);return new aL({steps:e})}else throw new Error(`Expected a Runnable, function or object.
Instead got an unsupported type.`)}function wyn(t,e){let r=e.name??t.getName(),n=e.description??eL(e.schema);return gW(e.schema)?new Fhe({name:r,description:n,schema:Ct.object({input:Ct.string()}).transform(o=>o.input),bound:t}):new Fhe({name:r,description:n,schema:e.schema,bound:t})}var Vo,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=class extends Kh{constructor(){super(...arguments);x(this,"lc_runnable",!0);x(this,"name")}getName(e){let r=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${r}${e}`:r}withRetry(e){return new khe({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new Hw({bound:this,config:e,kwargs:{}})}withFallbacks(e){let r=Array.isArray(e)?e:e.fallbacks;return new yVe({runnable:this,fallbacks:r})}_getOptionsList(e,r=0){if(Array.isArray(e)&&e.length!==r)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${r} inputs`);if(Array.isArray(e))return e.map(Qo);if(r>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");let n=Object.fromEntries(Object.entries(e).filter(([o])=>o!=="runId"));return Array.from({length:r},(o,i)=>Qo(i===0?e:n))}return Array.from({length:r},()=>Qo(e))}async batch(e,r,n){let o=this._getOptionsList(r??{},e.length),i=o[0]?.maxConcurrency??n?.maxConcurrency,a=new Fw({maxConcurrency:i,onFailedAttempt:u=>{throw u}}),s=e.map((u,l)=>a.call(async()=>{try{return await this.invoke(u,o[l])}catch(c){if(n?.returnExceptions)return c;throw c}}));return Promise.all(s)}async*_streamIterator(e,r){yield this.invoke(e,r)}async stream(e,r){let n=Qo(r),o=new H$({generator:this._streamIterator(e,n),config:n});return await o.setup,Qy.fromAsyncGenerator(o)}_separateRunnableConfigFromCallOptions(e){let r;e===void 0?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});let n={...e};return delete n.callbacks,delete n.tags,delete n.metadata,delete n.runName,delete n.configurable,delete n.recursionLimit,delete n.maxConcurrency,delete n.runId,delete n.timeout,delete n.signal,[r,n]}async _callWithConfig(e,r,n){let o=Qo(n),a=await(await Zg(o))?.handleChainStart(this.toJSON(),ud(r,"input"),o.runId,o?.runType,void 0,void 0,o?.runName??this.getName());delete o.runId;let s;try{let u=e.call(this,r,o,a);s=await $w(u,n?.signal)}catch(u){throw await a?.handleChainError(u),u}return await a?.handleChainEnd(ud(s,"output")),s}async _batchWithConfig(e,r,n,o){let i=this._getOptionsList(n??{},r.length),a=await Promise.all(i.map(Zg)),s=await Promise.all(a.map(async(l,c)=>{let d=await l?.handleChainStart(this.toJSON(),ud(r[c],"input"),i[c].runId,i[c].runType,void 0,void 0,i[c].runName??this.getName());return delete i[c].runId,d})),u;try{let l=e.call(this,r,i,s,o);u=await $w(l,i?.[0]?.signal)}catch(l){throw await Promise.all(s.map(c=>c?.handleChainError(l))),l}return await Promise.all(s.map(l=>l?.handleChainEnd(ud(u,"output")))),u}_concatOutputChunks(e,r){return eb(e,r)}async*_transformStreamWithConfig(e,r,n){let o,i=!0,a,s=!0,u=Qo(n),l=await Zg(u),c=this;async function*d(){for await(let p of e){if(i)if(o===void 0)o=p;else try{o=c._concatOutputChunks(o,p)}catch{o=void 0,i=!1}yield p}}let f;try{let p=await sBe(r.bind(this),d(),async()=>l?.handleChainStart(this.toJSON(),{input:""},u.runId,u.runType,void 0,void 0,u.runName??this.getName(),void 0,{lc_defers_inputs:!0}),n?.signal,u);delete u.runId,f=p.setup;let m=f?.handlers.find(gTt),h=p.output;m!==void 0&&f!==void 0&&(h=m.tapOutputIterable(f.runId,h));let y=f?.handlers.find(fBe);y!==void 0&&f!==void 0&&(h=y.tapOutputIterable(f.runId,h));for await(let g of h)if(yield g,s)if(a===void 0)a=g;else try{a=this._concatOutputChunks(a,g)}catch{a=void 0,s=!1}}catch(p){throw await f?.handleChainError(p,void 0,void 0,
${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(`Unrecognized strategy: '${o}'. Must be one of '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(`Unrecognized message type ${t}`)}if(r&&n)return n;if(o)return o;throw new Error(`Unrecognized message type ${t}`)}function Cyn(t){let e=t.getType(),r,n=Object.fromEntries(Object.entries(t
`);return Promise.resolve([...e.slice(0,-1).map(r=>`${r}
`),e[e.length-1]])}var Uhe,rIt,sIt=v(()=>{Jg();G3();kY();rpe();U$();npe();qY();H0();Rw();Qh();Uhe=(t,e)=>{let r=[...new Set(e?.map(o=>{if(typeof o=="string")return o;let i=new o({});if(!("getType"in i)||typeof i.getType!="function")throw new Error("Invalid type provided.");return i.getType()}))],n=t.getType();return r.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}}});var uIt,lIt=v(()=>{uIt=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"]});var cIt,dIt=v(()=>{cIt=["image","video","audio","text-plain","file"]});var fIt,pIt=v(()=>{lIt();dIt();fIt=["text","reasoning",...uIt,...cIt]});var xyn,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})});var mIt,hIt=v(()=>{Jg();U$();Rw();Qh();Qa();qhe();mIt=class extends Hw{constructor(e){let r=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"}));let o=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){let r;if(typeof e=="object"&&!Array.isArray(e)&&!Gh(e)){let n;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]}else r=e;if(typeof r=="string")return[new Hs(r)];if(Array.isArray(r))return r;if(Gh(r))return[r];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.
Got ${JSON.stringify(r,null,2)}`)}_getOutputMessages(e){let r;if(!Array.isArray(e)&&!Gh(e)&&typeof e!="string"){let n;this.outputMessagesKey!==void 0?n=this.outputMessagesKey:Object.keys(e).length===1?n=Object.keys(e)[0]:n="output",e.generations!==void 0?r=e.generations[0][0].message:r=e[n]}else r=e;if(typeof r=="string")return[new eo(r)];if(Array.isArray(r))return r;if(Gh(r))return[r];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(r,null,2)}`)}async _enterHistory(e,r){let o=await(r?.configurable?.messageHistory).getMessages();return this.historyMessagesKey===void 0?o.concat(this._getInputMessages(e)):o}async _exitHistory(e,r){let n=r.configurable?.messageHistory,o;Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?o=e.inputs[0]:o=e.inputs;let i=this._getInputMessages(o);if(this.historyMessagesKey===void 0){let u=await n.getMessages();i=i.slice(u.length)}let a=e.outputs;if(!a)throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);let s=this._getOutputMessages(a);await n.addMessages([...i,...s])}async _mergeConfig(...e){let r=await super._mergeConfig(...e);if(!r.configurable||!r.configurable.sessionId){let o={[this.inputMessagesKey??"input"]:"foo"},i={configurable:{sessionId:"123"}};throw new Error(`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;return r.configurable.messageHistory=await this.getMessageHistory(n),r}}});var Oyn,_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})});var Sz,iN,th,TW=v(()=>{AY();Qh();_v();Sz=class extends Vo{parseResultWithPrompt(t,e,r){return this.parseResult(t,r)}_baseMessageToString(t){return typeof t.content=="string"?t.content:this._baseMessageContentToString(t.content)}_baseMessageContentToString(t){return JSON.stringify(t)}async invoke(t,e){return typeof t=="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=class extends Sz{parseResult(t,e){return this.parse(t[0].text,e)}async parseWithPrompt(t,e,r){return this.parse(t,r)}_type(){throw new Error("_type not implemented")}},th=class extends Error{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===void 0||r===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");$$(this,"OUTPUT_PARSING_FAILURE")}}});var aN,sL,uL=v(()=>{Jg();H0();id();TW();jhe();aN=class extends iN{async*_transform(t){for await(let e of t)typeof e=="string"?yield this.parseResult([{text:e}]):yield this.parseResult([{message:e,text:this._baseMessageToString(e)}])}async*transform(t,e){yield*this._transformStreamWithConfig(t,this._transform.bind(this),{...e,runType:"parser"})}},sL=class extends aN{constructor(e){super(e);x(this,"diff",!1);this.diff=e?.diff??this.diff}async*_transform(e){let r,n;for await(let o of e){if(typeof o!="string"&&typeof o.content!="string")throw new Error("Cannot handle non-string output.");let i;if(K3(o)){if(typeof o.content!="string")throw new Error("Cannot handle non-string message output.");i=new yi({message:o,text:o.content})}else if(Gh(o)){if(typeof o.content!="string")throw new Error("Cannot handle non-string message output.");i=new yi({message:$B(o),text:o.content})}else i=new Lw({text:o});n===void 0?n=i:n=n.concat(i);let a=await this.parsePartialResult([n]);a!=null&&!dO(a,r)&&(this.diff?yield this._diff(r,a):yield a,r=a)}}getFormatInstructions(){return""}}});var gIt,yIt=v(()=>{uL();gIt=class extends aN{constructor(){super(...arguments);x(this,"lc_namespace",["langchain_core","output_parsers","bytes"]);x(this,"lc_serializable",!0);x(this,"textEncoder",new TextEncoder)}static lc_name(){return"BytesOutputParser"}parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return""}}});var EW,bIt,_It,vIt,wIt,SIt=v(()=>{TW();uL();EW=class extends aN{constructor(){super(...arguments);x(this,"re")}async*_transform(e){let r="";for await(let n of e)if(typeof n=="string"?r+=n:r+=n.content,this.re){let o=[...r.matchAll(this.re)];if(o.length>1){let i=0;for(let a of o.slice(0,-1))yield[a[1]],i+=(a.index??0)+a[0].length;r=r.slice(i)}}else{let o=await this.parse(r);if(o.length>1){for(let i of o.slice(0,-1))yield[i];r=o[o.length-1]}}for(let n of await this.parse(r))yield[n]}},bIt=class extends EW{constructor(){super(...arguments);x(this,"lc_namespace",["langchain_core","output_parsers","list"]);x(this,"lc_serializable",!0)}static lc_name(){return"CommaSeparatedListOutputParser"}async parse(e){try{return e.trim().split(",").map(r=>r.trim())}catch{throw new th(`Could not pa
1. foo
2. bar
3. baz`}async parse(e){return[...e.matchAll(this.re)??[]].map(r=>r[1])}},wIt=class extends EW{constructor(){super(...arguments);x(this,"lc_namespace",["langchain_core","output_parsers","list"]);x(this,"lc_serializable",!0);x(this,"re",/^\s*[-*]\s([^\n]+)$/gm)}static lc_name(){return"NumberedListOutputParser"}getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
1. foo
2. bar
3. baz`}async parse(e){return[...e.matchAll(this.re)??[]].map(r=>r[1])}}});var Bhe,CIt=v(()=>{uL();Bhe=class extends aN{constructor(){super(...arguments);x(this,"lc_namespace",["langchain_core","output_parsers","string"]);x(this,"lc_serializable",!0)}static lc_name(){return"StrOutputParser"}parse(e){return Promise.resolve(e)}getFormatInstructions(){return""}_textContentToString(e){return e.text}_imageUrlContentToString(e){throw new Error('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentToString(e){switch(e.type){case"text":case"text_delta":if("text"in e)return this._textContentToString(e);break;case"image_url":if("image_url"in e)return this._imageUrlContentToString(e);break;default:throw new Error(`Cannot coerce "${e.type}" message part into a string.`)}throw new Error(`Invalid content type: ${e.type}`)}_baseMessageContentToString(e){return e.reduce((r,n)=>r+this._messageContentToString(n),"")}}});var Jw,wVe,xIt,OIt=v(()=>{eN();nb();TW();cO();Jw=class extends iN{constructor(e){super(e);x(this,"lc_namespace",["langchain","output_parsers","structured"]);this.schema=e}static lc_name(){return"StructuredOutputParser"}toJSON(){return this.toJSONNotImplemented()}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){let r=Ct.object(Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Ct.string().describe(o)])));return new this(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:
\`\`\`json
${JSON.stringify(Ni(this.schema))}
\`\`\`
`}async parse(e){try{let r=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,"");return await Q$(this.schema,JSON.parse(o))}catch(r){throw new th(`Failed to parse. Text: "${e}". Error: ${r}`,e)}}},wVe=class extends Jw{static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(t){let e=t?.interpolationDepth??1;if(e<1)throw new Error("f string interpolation depth must be at least 1");return`Return a markdown code snippet with a JSON object formatted to look like:
\`\`\`json
${this._schemaToInstruction(Ni(this.schema)).replaceAll("{","{".repeat(e)).replaceAll("}","}".repeat(e))}
\`\`\``}_schemaToInstruction(t,e=2){let r=t;if("type"in r){let n=!1,o;if(Array.isArray(r.type)){let s=r.type.findIndex(u=>u==="null");s!==-1&&(n=!0,r.type.splice(s,1)),o=r.type.join(" | ")}else o=r.type;if(r.type==="object"&&r.properties){let s=r.description?` // ${r.description}`:"";return`{
${Object.entries(r.properties).map(([l,c])=>{let d=r.required?.includes(l)?"":" (optional)";return`${" ".repeat(e)}"${l}": ${this._schemaToInstruction(c,e+2)}${d}`}).join(`
`)}
${" ".repeat(e-2)}}${s}`}if(r.type==="array"&&r.items){let s=r.description?` // ${r.description}`:"";return`array[
${" ".repeat(e)}${this._schemaToInstruction(r.items,e+2)}
${" ".repeat(e-2)}] ${s}`}let i=n?" (nullable)":"",a=r.description?` // ${r.description}`:"";return`${o}${a}${i}`}if("anyOf"in r)return r.anyOf.map(n=>this._schemaToInstruction(n,e)).join(`
${" ".repeat(e-2)}`);throw new Error("unsupported schema type")}static fromZodSchema(t){return new this(t)}static fromNamesAndDescriptions(t){let e=Ct.object(Object.fromEntries(Object.entries(t).map(([r,n])=>[r,Ct.string().describe(n)])));return new this(e)}},xIt=class extends iN{constructor({inputSchema:e}){super(...arguments);x(this,"structuredInputParser");this.structuredInputParser=new wVe(e)}async parse(e){let r;try{r=await this.structuredInputParser.parse(e)}catch(n){throw new th(`Failed to parse. Text: "${e}". Error: ${n}`,e)}return this.outputProcessor(r)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}}});var Tyn,SVe=v(()=>{Bo();pQ();mQ();cBe();Tyn={};Rt(Tyn,{applyPatch:()=>J$,compare:()=>oW})});var vv,CVe=v(()=>{RY();mQ();uL();SVe();vv=class extends sL{constructor(){super(...arguments);x(this,"lc_namespace",["langchain_core","output_parsers"]);x(this,"lc_serializable",!0)}static lc_name(){return"JsonOutputParser"}_concatOutputChunks(e,r){return this.diff?super._concatOutputChunks(e,r):r}_diff(e,r){if(r)return e?oW(e,r):[{op:"replace",path:"",value:r}]}async parsePartialResult(e){return IY(e[0].text)}async parse(e){return IY(e,JSON.parse)}getFormatInstructions(){return""}_baseMessageToString(e){return e.text}}});var Eyn,TIt,EIt=v(()=>{Eyn=function(){let t={};t.parser=function(D,R){return new r(D,R)},t.SAXParser=r,t.SAXStream=l,t.createStream=u,t.MAX_BUFFER_LENGTH=65536;let e=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];t.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function r(D,R){if(!(this instanceof r))return new r(D,R);var z=this;o(z),z.q=z.c="",z.bufferCheckPosition=t.MAX_BUFFER_LENGTH,z.opt=R||{},z.opt.lowercase=z.opt.lowercase||z.opt.lowercasetags,z.looseCase=z.opt.lowercase?"toLowerCase":"toUpperCase",z.tags=[],z.closed=z.closedRoot=z.sawRoot=!1,z.tag=z.error=null,z.strict=!!D,z.noscript=!!(D||z.opt.noscript),z.state=M.BEGIN,z.strictEntities=z.opt.strictEntities,z.ENTITIES=z.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),z.attribList=[],z.opt.xmlns&&(z.ns=Object.create(m)),z.trackPosition=z.opt.position!==!1,z.trackPosition&&(z.position=z.line=z.column=0),j(z,"onready")}Object.create||(Object.create=function(D){function R(){}R.prototype=D;var z=new R;return z}),Object.keys||(Object.keys=function(D){var R=[];for(var z in D)D.hasOwnProperty(z)&&R.push(z);return R});function n(D){for(var R=Math.max(t.MAX_BUFFER_LENGTH,10),z=0,U=0,ee=e.length;U<ee;U++){var ce=D[e[U]].length;if(ce>R)switch(e[U]){case"textNode":k(D);break;case"cdata":A(D,"oncdata",D.cdata),D.cdata="";break;case"script":A(D,"onscript",D.script),D.script="";break;default:q(D,"Max buffer length exceeded: "+e[U])}z=Math.max(z,ce)}var ve=t.MAX_BUFFER_LENGTH-z;D.bufferCheckPosition=ve+D.position}function o(D){for(var R=0,z=e.length;R<z;R++)D[e[R]]=""}function i(D){k(D),D.cdata!==""&&(A(D,"oncdata",D.cdata),D.cdata=""),D.script!==""&&(A(D,"onscript",D.script),D.script="")}r.prototype={end:function(){J(this)},write:re,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){i(this)}};var a=ReadableStream;a||(a=function(){});var s=t.EVENTS.filter(function(D){return D!=="error"&&D!=="end"});function u(D,R){return new l(D,R)}function l(D,R){if(!(this instanceof l))return new l(D,R);a.apply(this),this._parser=new r(D,R),this.writable=!0,this.readable=!0;var z=this;this._parser.onend=function(){z.emit("end")},this._parser.onerror=function(U){z.emit("error",U),z._parser.error=null},this._decoder=null,s.forEach(function(U){Object.defineProperty(z,"on"+U,{get:function(){return z._parser["on"+U]},set:function(ee){if(!ee)return z.removeAllListeners(U),z._parser["on"+U]=ee,ee;z.on(U,ee)},enumerable:!0,configurable:!1})})}l.prototype=Object.create(a.prototype,{constructor:{value:l}}),l.prototy
`||D==="\r"||D===" "}function w(D){return D==='"'||D==="'"}function O(D){return D===">"||_(D)}function T(D,R){return D.test(R)}function P(D,R){return!T(D,R)}var M=0;t.STATE={BEGIN:M++,BEGIN_WHITESPACE:M++,TEXT:M++,TEXT_ENTITY:M++,OPEN_WAKA:M++,SGML_DECL:M++,SGML_DECL_QUOTED:M++,DOCTYPE:M++,DOCTYPE_QUOTED:M++,DOCTYPE_DTD:M++,DOCTYPE_DTD_QUOTED:M++,COMMENT_STARTING:M++,COMMENT:M++,COMMENT_ENDING:M++,COMMENT_ENDED:M++,CDATA:M++,CDATA_ENDING:M++,CDATA_ENDING_2:M++,PROC_INST:M++,PROC_INST_BODY:M++,PROC_INST_ENDING:M++,OPEN_TAG:M++,OPEN_TAG_SLASH:M++,ATTRIB:M++,ATTRIB_NAME:M++,ATTRIB_NAME_SAW_WHITE:M++,ATTRIB_VALUE:M++,ATTRIB_VALUE_QUOTED:M++,ATTRIB_VALUE_CLOSED:M++,ATTRIB_VALUE_UNQUOTED:M++,ATTRIB_VALUE_ENTITY_Q:M++,ATTRIB_VALUE_ENTITY_U:M++,CLOSE_TAG:M++,CLOSE_TAG_SAW_WHITE:M++,SCRIPT:M++,SCRIPT_ENDING:M++},t.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},t.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(t.ENTITIES).forEach(function(D){var R=t.ENTITIES[D],z=typeof R=="number"?String.fromCharCode(R):R;t.ENTITIES[D]=z});for(var I in t.STATE)t.STATE[t.STATE[I]]=I;M=t.STATE;function j(D,R,z){D[R]&&D[R](z)}function A(D,R,z){D.textNode&&k(D),j(D,R,z)}function k(D){D.textNode=V(D.opt,D.textNode),D.textNode&&j(D,"ontext",D.textNode),D.textNode=""}function V(D,R){return D.trim&&(R=R.trim()),D.normalize&&(R=R.replace(/\s+/g," ")),R}function q(D,R){return k(D),D.trackPosition&&(R+=`
Line: `+D.line+`
Column: `+D.column+`
Char: `+D.c),R=new Error(R),D.error=R,j(D,"onerror",R),D}function J(D){return D.sawRoot&&!D.closedRoot&&K(D,"Unclosed root tag"),D.state!==M.BEGIN&&D.state!==M.BEGIN_WHITESPACE&&D.state!==M.TEXT&&q(D,"Unexpected end"),k(D),D.c="",D.closed=!0,j(D,"onend"),r.call(D,D.strict,D.opt),D}function K(D,R){if(typeof D!="object"||!(D instanceof r))throw new Error("bad call to strictFail");D.strict&&q(D,R)}function ue(D){D.strict||(D.tagName=D.tagName[D.looseCase]());var R=D.tags[D.tags.length-1]||D,z=D.tag={name:D.tagName,attributes:{}};D.opt.xmlns&&(z.ns=R.ns),D.attribList.length=0,A(D,"onopentagstart",z)}function oe(D,R){var z=D.indexOf(":"),U=z<0?["",D]:D.split(":"),ee=U[0],ce=U[1];return R&&D==="xmlns"&&(ee="xmlns",ce=""),{prefix:ee,local:ce}}function G(D){if(D.strict||(D.attribName=D.attribName[D.looseCase]()),D.attribList.indexOf(D.attribName)!==-1||D.tag.attributes.hasOwnProperty(D.attribName)){D.attribName=D.attribValue="";return}if(D.opt.xmlns){var R=oe(D.attribName,!0),z=R.prefix,U=R.local;if(z==="xmlns")if(U==="xml"&&D.attribValue!==f)K(D,"xml: prefix must be bound to "+f+`
Actual: `+D.attribValue);else if(U==="xmlns"&&D.attribValue!==p)K(D,"xmlns: prefix must be bound to "+p+`
Actual: `+D.attribValue);else{var ee=D.tag,ce=D.tags[D.tags.length-1]||D;ee.ns===ce.ns&&(ee.ns=Object.create(ce.ns)),ee.ns[U]=D.attribValue}D.attribList.push([D.attribName,D.attribValue])}else D.tag.attributes[D.attribName]=D.attribValue,A(D,"onattribute",{name:D.attribName,value:D.attribValue});D.attribName=D.attribValue=""}function Y(D,R){if(D.opt.xmlns){var z=D.tag,U=oe(D.tagName);z.prefix=U.prefix,z.local=U.local,z.uri=z.ns[U.prefix]||"",z.prefix&&!z.uri&&(K(D,"Unbound namespace prefix: "+JSON.stringify(D.tagName)),z.uri=U.prefix);var ee=D.tags[D.tags.length-1]||D;z.ns&&ee.ns!==z.ns&&Object.keys(z.ns).forEach(function(Tr){A(D,"onopennamespace",{prefix:Tr,uri:z.ns[Tr]})});for(var ce=0,ve=D.attribList.length;ce<ve;ce++){var Oe=D.attribList[ce],Je=Oe[0],tt=Oe[1],Ke=oe(Je,!0),dt=Ke.prefix,Pt=Ke.local,Nt=dt===""?"":z.ns[dt]||"",Ne={name:Je,value:tt,prefix:dt,local:Pt,uri:Nt};dt&&dt!=="xmlns"&&!Nt&&(K(D,"Unbound namespace prefix: "+JSON.stringify(dt)),Ne.uri=dt),D.tag.attributes[Je]=Ne,A(D,"onattribute",Ne)}D.attribList.length=0}D.tag.isSelfClosing=!!R,D.sawRoot=!0,D.tags.push(D.tag),A(D,"onopentag",D.tag),R||(!D.noscript&&D.tagName.toLowerCase()==="script"?D.state=M.SCRIPT:D.state=M.TEXT,D.tag=null,D.tagName=""),D.attribName=D.attribValue="",D.attribList.length=0}function se(D){if(!D.tagName){K(D,"Weird empty close tag."),D.textNode+="</>",D.state=M.TEXT;return}if(D.script){if(D.tagName!=="script"){D.script+="</"+D.tagName+">",D.tagName="",D.state=M.SCRIPT;return}A(D,"onscript",D.script),D.script=""}var R=D.tags.length,z=D.tagName;D.strict||(z=z[D.looseCase]());for(var U=z;R--;){var ee=D.tags[R];if(ee.name!==U)K(D,"Unexpected close tag");else break}if(R<0){K(D,"Unmatched closing tag: "+D.tagName),D.textNode+="</"+D.tagName+">",D.state=M.TEXT;return}D.tagName=z;for(var ce=D.tags.length;ce-- >R;){var ve=D.tag=D.tags.pop();D.tagName=D.tag.name,A(D,"onclosetag",D.tagName);var Oe={};for(var Je in ve.ns)Oe[Je]=ve.ns[Je];var tt=D.tags[D.tags.length-1]||D;D.opt.xmlns&&ve.ns!==tt.ns&&Object.keys(ve.ns).forEach(function(Ke){var dt=ve.ns[Ke];A(D,"onclosenamespace",{prefix:Ke,uri:dt})})}R===0&&(D.closedRoot=!0),D.tagName=D.attribValue=D.attribName="",D.attribList.length=0,D.state=M.TEXT}function ie(D){var R=D.entity,z=R.toLowerCase(),U,ee="";return D.ENTITIES[R]?D.ENTITIES[R]:D.ENTITIES[z]?D.ENTITIES[z]:(R=z,R.charAt(0)==="#"&&(R.charAt(1)==="x"?(R=R.slice(2),U=parseInt(R,16),ee=U.toString(16)):(R=R.slice(1),U=parseInt(R,10),ee=U.toString(10))),R=R.replace(/^0+/,""),isNaN(U)||ee.toLowerCase()!==R?(K(D,"Invalid character entity"),"&"+D.entity+";"):String.fromCodePoint(U))}function $(D,R){R==="<"?(D.state=M.OPEN_WAKA,D.startTagPosition=D.position):_(R)||(K(D,"Non-whitespace before first tag."),D.textNode=R,D.state=M.TEXT)}function H(D,R){var z="";return R<D.length&&(z=D.charAt(R)),z}function re(D){var R=this;if(this.error)throw this.error;if(R.closed)return q(R,"Cannot write after close. Assign an onready handler.");if(D===null)return J(R);typeof D=="object"&&(D=D.toString());for(var z=0,U="";U=H(D,z++),R.c=U,!!U;)switch(R.trackPosition&&(R.position++,U===`
`?(R.line++,R.column=0):R.column++),R.state){case M.BEGIN:if(R.state=M.BEGIN_WHITESPACE,U==="\uFEFF")continue;$(R,U);continue;case M.BEGIN_WHITESPACE:$(R,U);continue;case M.TEXT:if(R.sawRoot&&!R.closedRoot){for(var ee=z-1;U&&U!=="<"&&U!=="&";)U=H(D,z++),U&&R.trackPosition&&(R.position++,U===`
`?(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
1. Output should conform to the tags below.
2. If tags are not given, make them on your own.
3. Remember to always open and close all the tags.
As an example, for the tags ["foo", "bar", "baz"]:
1. String "<foo>
<bar>
<baz></baz>
</bar>
</foo>" is a well-formatted instance of the schema.
2. String "<foo>
<bar>
</foo>" is a badly-formatted instance.
3. String "<foo>
<tag>
</tag>
</foo>" is a badly-formatted instance.
Here are the output tags:
\`\`\`
{tags}
\`\`\``,PIt=class extends sL{constructor(e){super(e);x(this,"tags");x(this,"lc_namespace",["langchain_core","output_parsers"]);x(this,"lc_serializable",!0);this.tags=e?.tags}static lc_name(){return"XMLOutputParser"}_diff(e,r){if(r)return e?oW(e,r):[{op:"replace",path:"",value:r}]}async parsePartialResult(e){return Vhe(e[0].text)}async parse(e){return Vhe(e)}getFormatInstructions(){return!!(this.tags&&this.tags.length>0)?zhe.replace("{tags}",this.tags?.join(", ")??""):zhe}},Pyn=t=>t.split(`
`).map(e=>e.replace(/^\s+/,"")).join(`
`).trim(),MIt=t=>{if(Object.keys(t).length===0)return{};let e={};return t.children.length>0?(e[t.name]=t.children.map(MIt),e):(e[t.name]=t.text??void 0,e)}});var Myn,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})});var Ww,PW=v(()=>{Qh();Ww=class extends Vo{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"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,e)}get lc_attributes(){return{partialVariables:void 0}}async mergePartialAndUserVariables(e){let r=this.partialVariables??{},n={};for(let[i,a]of Object.entries(r))typeof a=="string"?n[i]=a:n[i]=await a();return{...n,...e}}async invoke(e,r){let n={...this.metadata,...r?.metadata},o=[...this.tags??[],...r?.tags??[]];return this._callWithConfig(i=>this.formatPromptValue(i),e,{...r,tags:o,metadata:n,runType:"prompt"})}}});var Iyn,Hhe,see,uee,xVe,lee=v(()=>{Bo();L$();U$();H0();Iyn={};Rt(Iyn,{BasePromptValue:()=>Hhe,ChatPromptValue:()=>uee,ImagePromptValue:()=>xVe,StringPromptValue:()=>see});Hhe=class extends Kh{},see=class extends Hhe{constructor(e){super({value:e});x(this,"lc_namespace",["langchain_core","prompt_values"]);x(this,"lc_serializable",!0);x(this,"value");this.value=e}static lc_name(){return"StringPromptValue"}toString(){return this.value}toChatMessages(){return[new Hs(this.value)]}},uee=class extends Hhe{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}static lc_name(){return"ChatPromptValue"}toString(){return ol(this.messages)}toChatMessages(){return this.messages}},xVe=class extends Hhe{constructor(e){"imageUrl"in e||(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}static lc_name(){return"ImagePromptValue"}toString(){return this.imageUrl.url}toChatMessages(){return[new Hs({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}}});var sN,cee=v(()=>{lee();PW();sN=class extends Ww{async formatPromptValue(t){let e=await this.format(t);return new see(e)}}});function TVe(t){return typeof t=="function"}function Ayn(t){return IW(t)?"array":typeof t}function OVe(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function RIt(t,e){return t!=null&&typeof t=="object"&&e in t}function Nyn(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}function Dyn(t,e){return jyn.call(t,e)}function Lyn(t){return!Dyn($yn,t)}function kyn(t){return String(t).replace(/[&<>"'`=\/]/g,function(r){return Fyn[r]})}function Vyn(t,e){if(!t)return[];var r=!1,n=[],o=[],i=[],a=!1,s=!1,u="",l=0;function c(){if(a&&!s)for(;i.length;)delete o[i.pop()];else i=[];a=!1,s=!1}var d,f,p;function m(M){if(typeof M=="string"&&(M=M.split(Uyn,2)),!IW(M)||M.length!==2)throw new Error("Invalid tags: "+M);d=new RegExp(OVe(M[0])+"\\s*"),f=new RegExp("\\s*"+OVe(M[1])),p=new RegExp("\\s*"+OVe("}"+M[1]))}m(e||Kw.tags);for(var h=new fee(t),y,g,b,_,w,O;!h.eos();){if(y=h.pos,b=h.scanUntil(d),b)for(var T=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={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};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("Cannot use higher-order sections without the original template");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(`
`),a=0;a<i.length;a++)i[a].length&&(a>0||!n)&&(i[a]=o+i[a]);return i.join(`
`)};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 '{' in template.");r.push({type:"variable",name:e.slice(o+1,i).join("")}),o=i+1}else{if(e[o]==="}")throw new Error("Single '}' in template.");{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("Mustache templates cannot be validated.");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=`
`,a=""){let s=[a,...r,n].join(i);return new mee({inputVariables:o,template:s})}static fromTemplate(r,n){let{templateFormat:o="f-string",...i}=n??{},a=new Set;return xz(r,o).forEach(s=>{s.type==="variable"&&a.add(s.name)}),new mee({inputVariables:[...a],templateFormat:o,template:r,...i})}async partial(r){let n=this.inputVariables.filter(a=>!(a in r)),o={...this.partialVariables??{},...r},i={...this,inputVariables:n,partialVariables:o};return new mee(i)}serialize(){if(this.outputParser!==void 0)throw new Error("Cannot serialize a prompt template with an output parser");return{_type:this._getPromptType(),input_variables:this.inputVariables,template:this.template,template_format:this.templateFormat}}static async deserialize(r){if(!r.template)throw new Error("Prompt template must have a template");return new mee({inputVariables:r.input_variables,template:r.template,templateFormat:r.template_format})}}});var AW,IVe=v(()=>{lee();PW();Oz();AW=class $It extends Ww{constructor(r){super(r);x(this,"lc_namespace",["langchain_core","prompts","image"]);x(this,"template");x(this,"templateFormat","f-string");x(this,"validateTemplate",!0);x(this,"additionalContentFields");if(this.template=r.template,this.templateFormat=r.templateFormat??this.templateFormat,this.validateTemplate=r.validateTemplate??this.validateTemplate,this.additionalContentFields=r.additionalContentFields,this.validateTemplate){let n=this.inputVariables;this.partialVariables&&(n=n.concat(Object.keys(this.partialVariables))),uN([{type:"image_url",image_url:this.template}],this.templateFormat,n)}}static lc_name(){return"ImagePromptTemplate"}_getPromptType(){return"prompt"}async partial(r){let n=this.inputVariables.filter(a=>!(a in r)),o={...this.partialVariables??{},...r},i={...this,inputVariables:n,partialVariables:o};return new $It(i)}async format(r){let n={};for(let[s,u]of Object.entries(this.template))typeof u=="string"?n[s]=ey(u,this.templateFormat,r):n[s]=u;let o=r.url||n.url,i=r.detail||n.detail;if(!o)throw new Error("Must provide either an image URL.");if(typeof o!="string")throw new Error("url must be a string.");let a={url:o};return i&&(a.detail=i),a}async formatPromptValue(r){let n=await this.format(r);return new xVe(n)}}});function RVe(t,e){let r=[];for(let n of Object.values(t))if(typeof n=="string")xz(n,e).forEach(o=>{o.type==="variable"&&r.push(o.name)});else if(Array.isArray(n))for(let o of n)typeof o=="string"?xz(o,e).forEach(i=>{i.type==="variable"&&r.push(i.name)}):typeof o=="object"&&r.push(...RVe(o,e));else typeof n=="object"&&n!==null&&r.push(...RVe(n,e));return Array.from(new Set(r))}function AVe(t,e,r){let n={};for(let[o,i]of Object.entries(t))if(typeof i=="string")n[o]=ey(i,r,e);else if(Array.isArray(i)){let a=[];for(let s of i)typeof s=="string"?a.push(ey(s,r,e)):typeof s=="object"&&a.push(AVe(s,e,r));n[o]=a}else typeof i=="object"&&i!==null?n[o]=AVe(i,e,r):n[o]=i;return n}var hee,NVe=v(()=>{Qh();Oz();hee=class extends Vo{constructor(e){let r=e.templateFormat??"f-string",n=RVe(e.template,r);super({inputVariables:n,...e});x(this,"lc_namespace",["langchain_core","prompts","dict"]);x(this,"lc_serializable",!0);x(this,"template");x(this,"templateFormat");x(this,"inputVariables");this.template=e.template,this.templateFormat=r,this.inputVariables=n}static lc_name(){return"DictPromptTemplate"}async format(e){return AVe(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:"prompt"})}}});function Wyn(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function Kyn(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:"image_url"in t&&(typeof t.image_url=="string"||typeof t.image_url=="object"&&t.image_url!==null&&"url"in t.image_url&&typeof t.image_url.url=="string")}function Gyn(t){return typeof t.formatMessages=="function"}function Xyn(t,e){if(Gyn(t)||Gh(t))return t;if(Array.isArray(t)&&t[0]==="placeholder"){let o=t[1];if(e?.templateFormat==="mustache"&&typeof o=="string"&&o.slice(0,2)==="{{"&&o.slice(-2)==="}}
`));throw a.name="InputFormatError",a.lc_error_code=o.lc_error_code,a}return n}},jVe=class extends gee{constructor(e){"prompt"in e||(e={prompt:e});super(e);x(this,"prompt");this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}},yee=class extends Ww{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){let e=await this.formatMessages(t);return new uee(e)}},DVe=class extends jVe{constructor(e,r){"prompt"in e||(e={prompt:e,role:r});super(e);x(this,"role");this.role=e.role}static lc_name(){return"ChatMessagePromptTemplate"}async format(e){return new nd(await this.prompt.format(e),this.role)}static fromTemplate(e,r,n){return new this(lu.fromTemplate(e,{templateFormat:n?.templateFormat}),r)}};$Ve=class extends gee{constructor(e,r){"prompt"in e||(e={prompt:e});super(e);x(this,"lc_namespace",["langchain_core","prompts","chat"]);x(this,"lc_serializable",!0);x(this,"inputVariables",[]);x(this,"additionalOptions",{});x(this,"prompt");x(this,"messageClass");x(this,"chatMessageClass");if(this.prompt=e.prompt,Array.isArray(this.prompt)){let n=[];this.prompt.forEach(o=>{"inputVariables"in o&&(n=n.concat(o.inputVariables))}),this.inputVariables=n}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=r??this.additionalOptions}static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}createMessage(e){let r=this.constructor;if(r._messageClass()){let n=r._messageClass();return new n({content:e})}else if(r.chatMessageClass){let n=r.chatMessageClass();return new n({content:e,role:this.getRoleFromMessageClass(n.lc_name())})}else throw new Error("No message class defined")}getRoleFromMessageClass(e){switch(e){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw new Error("Invalid message class name")}}static fromTemplate(e,r){if(typeof e=="string")return new this(lu.fromTemplate(e,r));let n=[];for(let o of e)if(typeof o=="string")n.push(lu.fromTemplate(o,r));else if(o!==null)if(Wyn(o)){let i="";typeof o.text=="string"&&(i=o.text??"");let a={...r,additionalContentFields:o};n.push(lu.fromTemplate(i,a))}else if(Kyn(o)){let i=o.image_url??"",a,s=[];if(typeof i=="string"){let u;r?.templateFormat==="mustache"?u=RW(i):u=Cz(i);let l=u.flatMap(c=>c.type==="variable"?[c.name]:[]);if((l?.length??0)>0){if(l.length>1)throw new Error(`Only one format variable allowed per image template.
Got: ${l}
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} does not have inputVariables defined.`);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(`Input variables \`${[...a]}\` are not used in any of the prompt messages.`);let s=new Set([...n].filter(u=>!i.has(u)));if(s.size>0)throw new Error(`Input variables \`${[...s]}\` are used in prompt messages but not in the prompt template.`)}}static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}_getPromptType(){return"chat"}async _parseImagePrompts(r,n){if(typeof r.content=="string")return r;let o=await Promise.all(r.content.map(async i=>{if(i.type!=="image_url")return i;let a="";typeof i.image_url=="string"?a=i.image_url:typeof i.image_url=="object"&&i.image_url!==null&&"url"in i.image_url&&typeof i.image_url.url=="string"&&(a=i.image_url.url);let u=await lu.fromTemplate(a,{templateFormat:this.templateFormat}).format(n);return typeof i.image_url=="object"&&i.image_url!==null&&"url"in i.image_url?i.image_url.url=u:i.image_url=u,i}));return r.content=o,r}async formatMessages(r){let n=await this.mergePartialAndUserVariables(r),o=[];for(let i of this.promptMessages)if(i instanceof Uc)o.push(await this._parseImagePrompts(i,n));else{let a;this.templateFormat==="mustache"?a={...n}:a=i.inputVariables.reduce((u,l)=>{if(!(l in n)&&!(Zyn(i)&&i.optional))throw $$(new Error(`Missing value for input variable \`${l.toString()}\``),"INVALID_PROMPT_INPUT");return u[l]=n[l],u},{});let s=await i.formatMessages(a);o=o.concat(s)}return o}async partial(r){let n=this.inputVariables.filter(a=>!(a in r)),o={...this.partialVariables??{},...r},i={...this,inputVariables:n,partialVariables:o};return new Khe(i)}static fromTemplate(r,n){let o=lu.fromTemplate(r,n),i=new Qb({prompt:o});return this.fromMessages([i])}static fromMessages(r,n){let o=r.reduce((s,u)=>s.concat(u instanceof Khe?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",`
`);x(this,"prefix","");x(this,"templateFormat","f-string");x(this,"validateTemplate",!0);if(this.examples=r.examples,this.examplePrompt=r.examplePrompt,this.exampleSeparator=r.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
`)});function Cc(t,e){let r=`atom${++rbn}`,n={toString(){return(Al.env?Al.env.MODE:void 0)!=="production"&&this.debugLabel?r+":"+this.debugLabel:r}};return typeof t=="function"?n.read=t:(n.init=t,n.read=nbn,n.write=obn),e&&(n.write=e),n}function nbn(t){return t(this)}function obn(t,e,r){return e(this,typeof r=="function"?r(t(this)):r)}var Al,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"in t,qVe=t=>!!t.write,Qhe=new WeakMap,BVe=t=>{var e;return zVe(t)&&!((e=Qhe.get(t))!=null&&e[1])},ibn=(t,e)=>{let r=Qhe.get(t);if(r)r[1]=!0,r[0].forEach(n=>n(e));else if((Al.env?Al.env.MODE:void 0)!=="production")throw new Error("[Bug] cancelable promise not found")},abn=t=>{if(Qhe.has(t))return;let e=[new Set,!1];Qhe.set(t,e);let r=()=>{e[1]=!0};t.then(r,r),t.onCancel=n=>{e[0].add(n)}},zVe=t=>typeof t?.then=="function",KIt=t=>"v"in t||"e"in t,Yhe=t=>{if("e"in t)throw t.e;if((Al.env?Al.env.MODE:void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.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)=>{var i;if((Al.env?Al.env.MODE:void 0)!=="production"&&n===e)throw new Error("[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=()=>[new Map,new Map,new Set],UVe=(t,e,r)=>{t[0].has(e)||t[0].set(e,new Set),t[1].set(e,r)},sbn=(t,e,r)=>{let n=t[0].get(e);n&&n.add(r)},ubn=(t,e)=>t[0].get(e),XIt=(t,e)=>{t[2].add(e)},lL=t=>{let e,r=!1,n=o=>{try{o()}catch(i){r||(e=i,r=!0)}};for(;t[1].size||t[2].size;){t[0].clear();let o=new Set(t[1].values());t[1].clear();let i=new Set(t[2]);t[2].clear(),o.forEach(a=>{var s;return(s=a.m)==null?void 0:s.l.forEach(n)}),i.forEach(n)}if(r)throw e},YIt=(...[t,e,r,n])=>{let o;(Al.env?Al.env.MODE:void 0)!=="production"&&(o=new Set);let i=(_,w,O)=>{let T="v"in w,P=w.v,M=BVe(w.v)?w.v:null;if(zVe(O)){abn(O);for(let I of w.d.keys())ZIt(_,O,t(I));w.v=O,delete w.e}else w.v=O,delete w.e;(!T||!Object.is(P,w.v))&&(++w.n,M&&ibn(M,O))},a=(_,w,O)=>{var T;let P=t(w);if(KIt(P)&&(P.m&&!O?.has(w)||Array.from(P.d).every(([V,q])=>a(_,V,O).n===q)))return P;P.d.clear();let M=!0,I=V=>{if(WIt(w,V)){let J=t(V);if(!KIt(J))if(kVe(V))i(V,J,V.init);else throw new Error("no atom init");return Yhe(J)}let q=a(_,V,O);try{return Yhe(q)}finally{if(M)GIt(_,w,P,V,q);else{let J=jW();GIt(J,w,P,V,q),p(J,w,P),lL(J)}}},j,A,k={get signal(){return j||(j=new AbortController),j.signal},get setSelf(){return(Al.env?Al.env.MODE:void 0)!=="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:void 0)!=="production"&&M&&console.warn("setSelf function cannot be called in sync"),!M)return f(w,...V)}),A}};try{let V=e(w,I,k);if(i(w,P,V),zVe(V)){(T=V.onCancel)==null||T.call(V,()=>j?.abort());let q=()=>{if(P.m){let J=jW();p(J,w,P),lL(J)}};V.then(q,q)}return P}catch(V){return delete P.v,P.e=V,++P.n,P}finally{M=!1}},s=_=>Yhe(a(void 0,_)),u=(_,w,O)=>{var T,P;let M=new Map;for(let I of((T=O.m)==null?void 0:T.t)||[])M.set(I,t(I));for(let I of O.p)M.set(I,t(I));return(P=ubn(_,w))==null||P.forEach(I=>{M.set(I,t(I))}),M};function l(_,w,O){let T=[],P=new Set,M=new Set,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]of u(_,j,A))j!==k&&!P.has(k)&&I.push([k,V])}return[T,M]}let c=(_,w,O)=>{let[T,P]=l(_,w,O),M=new Set([w]);for(let I=T.length-1;I>=0;--I){let[j,A,k]=T[I],V=!1;for(let q of A.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)=>{let T=!0,P=I=>Yhe(a(_,I)),M=(I,...j)=>{let A=t(I);try{if(WIt(w,I)){if(!kVe(I))throw new Error("atom not writable");let k=A.n,V=j[0];i(I,A,V),p(_,I,A),k!==A.n&&(UVe(_,I,A),c(_,I,A));return}else return d(_,I,...j)}finally{T||lL(_)}};try{return r(w,P,M,...O)}finally{T=!1}},f=(_,...w)=>{let O=jW();try{return d
`)}return JSON.stringify(t)??String(t)}catch{return String(t)}}var tHe=v(()=>{});var rHe,pm,Ez=v(()=>{tHe();Zt();ot();rHe=class t{constructor(){this.maxLines=500;this.maxLineChars=8e3;this.buffer=[];this.initialized=!1;this.flushing=!1}static getInstance(){return t.instance||(t.instance=new t),t.instance}getLogPath(){return"copilot/copilot-log.md"}async ensureInitialized(){this.initialized||(this.initialized=!0)}hasVault(){try{return typeof app<"u"&&!!app.vault?.adapter}catch{return!1}}sanitizeForSingleLine(e){if(e instanceof Error){let r=Sn(e,!0);return this.escapeAngleBrackets(this.collapseToSingleLine(r))}if(typeof e=="string")return this.escapeAngleBrackets(this.collapseToSingleLine(e));try{let r=JSON.stringify(e);return this.escapeAngleBrackets(this.collapseToSingleLine(r??String(e)))}catch{return this.escapeAngleBrackets(this.collapseToSingleLine(String(e)))}}collapseToSingleLine(e){let r=e.replace(/[\r\n]+/g,"\\n").replace(/\t/g," ");return r.length<=this.maxLineChars?r:r.slice(0,this.maxLineChars)+` \u2026 [truncated ${r.length-this.maxLineChars} chars]`}async append(e,...r){await this.ensureInitialized();let n=new Date().toISOString(),o=r.map(a=>this.sanitizeForSingleLine(a)),i=`${n} ${e} ${o.join(" ")}`.trim();this.buffer.push(i),this.buffer.length>this.maxLines&&this.buffer.splice(0,this.buffer.length-this.maxLines)}escapeAngleBrackets(e){return e.replace(/</g,"&lt;").replace(/>/g,"&gt;")}async appendMarkdownBlock(e){if(await this.ensureInitialized(),!(!Array.isArray(e)||e.length===0))for(let r of e){let n=typeof r=="string"?r:String(r??"");this.buffer.push(n),this.buffer.length>this.maxLines&&this.buffer.splice(0,this.buffer.length-this.maxLines)}}async flush(){if(this.hasVault()&&!this.flushing){this.flushing=!0;try{let e=this.getLogPath();if(await app.vault.adapter.exists(e)){let r=this.buffer.join(`
`)+(this.buffer.length?`
`:"");await app.vault.adapter.write(e,r)}}catch{}finally{this.flushing=!1}}}async clear(){if(this.buffer=[],!!this.hasVault())try{let e=this.getLogPath();await app.vault.adapter.exists(e)&&await app.vault.adapter.remove(e)}catch{}}sanitizeSettingsForLog(){let e=ae();return this.removeKeysRecursive(e)}removeKeysRecursive(e){if(e==null)return e;if(Array.isArray(e))return e.map(r=>this.removeKeysRecursive(r));if(typeof e=="object"&&e.constructor===Object){let r={},n=e;for(let[o,i]of Object.entries(n))/apiKey$/i.test(o)||/licenseKey$/i.test(o)||/_api_key$/i.test(o)||/_license_key$/i.test(o)||/orgId$/i.test(o)||/instanceName$/i.test(o)||/deploymentName$/i.test(o)||/apiVersion$/i.test(o)||(r[o]=this.removeKeysRecursive(i));return r}return e}async openLogFile(){if(!this.hasVault())return;let e=this.getLogPath(),r=[...this.buffer];try{let o=this.sanitizeSettingsForLog(),a=["","## Settings","```json",...JSON.stringify(o,null,2).split(`
`),"```"];r.push(...a)}catch{}try{let o=r.join(`
`)+(r.length?`
`:""),i=e.includes("/")?e.split("/").slice(0,-1).join("/"):"";i&&await xc(i),await app.vault.adapter.exists(e)?await app.vault.adapter.write(e,o):await app.vault.create(e,o)}catch{}let n=app.vault.getAbstractFileByPath(e);try{n&&await app.workspace.getLeaf(!0).openFile(n)}catch{}}},pm=rHe.getInstance()});function B(...t){ae().debug&&console.log(...t),pm.append("INFO",...t)}function ne(...t){ae().debug&&console.error(...t),pm.append("ERROR",...t)}function Be(...t){ae().debug&&console.warn(...t),pm.append("WARN",...t)}function ige(t){pm.appendMarkdownBlock(t)}function _Rt(t,e){if(ae().debug)try{if(typeof console.table=="function"){Array.isArray(e)&&e.length>0?console.table(t,e):console.table(t);return}}catch{}B("Table:",JSON.stringify(t))}var _t=v(()=>{ot();Ez()});var vRt=S((nHe,FW)=>{(function(t,e){typeof nHe=="object"&&typeof FW<"u"?FW.exports=e():typeof define=="function"&&define.amd?define(e):t.moment=e()})(nHe,function(){"use strict";var t;function e(){return t.apply(null,arguments)}function r(C){t=C}function n(C){return C instanceof Array||Object.prototype.toString.call(C)==="[object Array]"}function o(C){return C!=null&&Object.prototype.toString.call(C)==="[object Object]"}function i(C,E){return Object.prototype.hasOwnProperty.call(C,E)}function a(C){if(Object.getOwnPropertyNames)return Object.getOwnPropertyNames(C).length===0;var E;for(E in C)if(i(C,E))return!1;return!0}function s(C){return C===void 0}function u(C){return typeof C=="number"||Object.prototype.toString.call(C)==="[object Number]"}function l(C){return C instanceof Date||Object.prototype.toString.call(C)==="[object Date]"}function c(C,E){var N=[],F,W=C.length;for(F=0;F<W;++F)N.push(E(C[F],F));return N}function d(C,E){for(var N in E)i(E,N)&&(C[N]=E[N]);return i(E,"toString")&&(C.toString=E.toString),i(E,"valueOf")&&(C.valueOf=E.valueOf),C}function f(C,E,N,F){return uwt(C,E,N,F,!0).utc()}function p(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidEra:null,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],era:null,meridiem:null,rfc2822:!1,weekdayMismatch:!1}}function m(C){return C._pf==null&&(C._pf=p()),C._pf}var h;Array.prototype.some?h=Array.prototype.some:h=function(C){var E=Object(this),N=E.length>>>0,F;for(F=0;F<N;F++)if(F in E&&C.call(this,E[F],F,E))return!0;return!1};function y(C){if(C._isValid==null){var E=m(C),N=h.call(E.parsedDateParts,function(W){return W!=null}),F=!isNaN(C._d.getTime())&&E.overflow<0&&!E.empty&&!E.invalidEra&&!E.invalidMonth&&!E.invalidWeekday&&!E.weekdayMismatch&&!E.nullInput&&!E.invalidFormat&&!E.userInvalidated&&(!E.meridiem||E.meridiem&&N);if(C._strict&&(F=F&&E.charsLeftOver===0&&E.unusedTokens.length===0&&E.bigHour===void 0),Object.isFrozen==null||!Object.isFrozen(C))C._isValid=F;else return F}return C._isValid}function g(C){var E=f(NaN);return C!=null?d(m(E),C):m(E).userInvalidated=!0,E}var b=e.momentProperties=[],_=!1;function w(C,E){var N,F,W,de=b.length;if(s(E._isAMomentObject)||(C._isAMomentObject=E._isAMomentObject),s(E._i)||(C._i=E._i),s(E._f)||(C._f=E._f),s(E._l)||(C._l=E._l),s(E._strict)||(C._strict=E._strict),s(E._tzm)||(C._tzm=E._tzm),s(E._isUTC)||(C._isUTC=E._isUTC),s(E._offset)||(C._offset=E._offset),s(E._pf)||(C._pf=m(E)),s(E._locale)||(C._locale=E._locale),de>0)for(N=0;N<de;N++)F=b[N],W=E[F],s(W)||(C[F]=W);return C}function O(C){w(this,C),this._d=new Date(C._d!=null?C._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),_===!1&&(_=!0,e.updateOffset(this),_=!1)}function T(C){return C instanceof O||C!=null&&C._isAMomentObject!=null}function P(C){e.suppressDeprecationWarnings===!1&&typeof console<"u"&&console.warn&&console.warn("Deprecation warning: "+C)}function M(C,E){var N=!0;return d(function(){if(e.deprecationHandler!=null&&e.deprecationHandler(null,C),N){var F=[],W,de,Ae,rn=arguments.length;for(de=0;de<rn;de++){if(W="",typeof arguments[de]=="object"){W+=`
[`+de+"] ";for(Ae in arguments[0])i(arguments[0],Ae)&&(W+=Ae+": "+arguments[0][Ae]+", ");W=W.slice(0,-2)}else W=arguments[de];F.push(W)}P(C+`
Arguments: `+Array.prototype.slice.call(F).join("")+`
`+new Error().stack),N=!1}return E.apply(this,arguments)},E)}var I={};function j(C,E){e.deprecationHandler!=null&&e.deprecationHandler(C,E),I[C]||(P(E),I[C]=!0)}e.suppressDeprecationWarnings=!1,e.deprecationHandler=null;function A(C){return typeof Function<"u"&&C instanceof Function||Object.prototype.toString.call(C)==="[object Function]"}function k(C){var E,N;for(N in C)i(C,N)&&(E=C[N],A(E)?this[N]=E:this["_"+N]=E);this._config=C,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)}function V(C,E){var N=d({},C),F;for(F in E)i(E,F)&&(o(C[F])&&o(E[F])?(N[F]={},d(N[F],C[F]),d(N[F],E[F])):E[F]!=null?N[F]=E[F]:delete N[F]);for(F in C)i(C,F)&&!i(E,F)&&o(C[F])&&(N[F]=d({},N[F]));return N}function q(C){C!=null&&this.set(C)}var J;Object.keys?J=Object.keys:J=function(C){var E,N=[];for(E in C)i(C,E)&&N.push(E);return N};var K={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"};function ue(C,E,N){var F=this._calendar[C]||this._calendar.sameElse;return A(F)?F.call(E,N):F}function oe(C,E,N){var F=""+Math.abs(C),W=E-F.length,de=C>=0;return(de?N?"+":"":"-")+Math.pow(10,Math.max(0,W)).toString().substr(1)+F}var G=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,Y=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,se={},ie={};function $(C,E,N,F){var W=F;typeof F=="string"&&(W=function(){return this[F]()}),C&&(ie[C]=W),E&&(ie[E[0]]=function(){return oe(W.apply(this,arguments),E[1],E[2])}),N&&(ie[N]=function(){return this.localeData().ordinal(W.apply(this,arguments),C)})}function H(C){return C.match(/\[[\s\S]/)?C.replace(/^\[|\]$/g,""):C.replace(/\\/g,"")}function re(C){var E=C.match(G),N,F;for(N=0,F=E.length;N<F;N++)ie[E[N]]?E[N]=ie[E[N]]:E[N]=H(E[N]);return function(W){var de="",Ae;for(Ae=0;Ae<F;Ae++)de+=A(E[Ae])?E[Ae].call(W,C):E[Ae];return de}}function D(C,E){return C.isValid()?(E=R(E,C.localeData()),se[E]=se[E]||re(E),se[E](C)):C.localeData().invalidDate()}function R(C,E){var N=5;function F(W){return E.longDateFormat(W)||W}for(Y.lastIndex=0;N>=0&&Y.test(C);)C=C.replace(Y,F),Y.lastIndex=0,N-=1;return C}var z={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"};function U(C){var E=this._longDateFormat[C],N=this._longDateFormat[C.toUpperCase()];return E||!N?E:(this._longDateFormat[C]=N.match(G).map(function(F){return F==="MMMM"||F==="MM"||F==="DD"||F==="dddd"?F.slice(1):F}).join(""),this._longDateFormat[C])}var ee="Invalid date";function ce(){return this._invalidDate}var ve="%d",Oe=/\d{1,2}/;function Je(C){return this._ordinal.replace("%d",C)}var tt={future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",w:"a week",ww:"%d weeks",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function Ke(C,E,N,F){var W=this._relativeTime[N];return A(W)?W(C,E,N,F):W.replace(/%d/i,C)}function dt(C,E){var N=this._relativeTime[C>0?"future":"past"];return A(N)?N(E):N.replace(/%s/i,E)}var Pt={};function Nt(C,E){var N=C.toLowerCase();Pt[N]=Pt[N+"s"]=Pt[E]=C}function Ne(C){return typeof C=="string"?Pt[C]||Pt[C.toLowerCase()]:void 0}function Tr(C){var E={},N,F;for(F in C)i(C,F)&&(N=Ne(F),N&&(E[N]=C[F]));return E}var st={};function Le(C,E){st[C]=E}function rt(C){var E=[],N;for(N in C)i(C,N)&&E.push({unit:N,priority:st[N]});return E.sort(function(F,W){return F.priority-W.priority}),E}function Fe(C){return C%4===0&&C%100!==0||C%400===0}function We(C){return C<0?Math.ceil(C)||0:Math.floor(C)}function ke(C){var E=+C,N=0;return E!==0&&isFinite(E)&&(N=We(E)),N}function Lt(C,E){return function(N){return N!=null?(xl(this,C,N),e.updateOffset(this,E),this):Eo(this,C)}}function Eo(C,E){return C.isValid()?C._d["get"+(C._isUTC?"UTC":"")+E]():NaN}function xl(C,E,N){C.isValid()&&!isNaN(N)&&(E==="FullYea
`)?o.slice(2):o.startsWith(`
`)||o.startsWith("\r")?o.slice(1):o}}return t}function yO(t,e=!0){let r=app.metadataCache.getFileCache(t),n=r?.frontmatter?.tags,o=new Set;if(!e){let i=r?.tags?.map(a=>a.tag);i&&i.forEach(a=>o.add(qW(a)))}return n&&(Array.isArray(n)?n.forEach(i=>{typeof i=="string"&&o.add(qW(i))}):typeof n=="string"&&o.add(qW(n))),Array.from(o)}function sge(t,e,r){if(e.length===0)return[];e=e.map(i=>qW(i));let n=r&&r.length>0?r:Eee(t,"/"),o=[];for(let i of n){let a=yO(i);e.some(s=>a.includes(s))&&o.push(i)}return o}async function xc(t){let e=(0,ry.normalizePath)(t).replace(/^\/+/,"").replace(/\/+$/,"");if(!e)return;let r=e.split("/").filter(Boolean),n="";for(let o of r){n=n?`${n}/${o}`:o;let i=app.vault.getAbstractFileByPath(n);if(i){if(i instanceof ry.TFile)throw new Error(`Path conflict: "${n}" exists as a file, expected folder.`);continue}await app.vault.adapter.mkdir(n)}}async function BW(t,e){return t.extension!="md"&&t.extension!="canvas"?null:await e.cachedRead(t)}function uge(t){return t.basename}function bO(t){return t?Dbn.includes(t.extension):!1}function sb(t){return t==="copilot_plus"||t==="project"}function zW(t,e){return t?t.extension==="md"||t.extension==="canvas"?!0:sb(e):!1}function ERt(t,e){return!t||!e?!1:t.includes(iHe)&&e.includes(iHe)||t==="small"&&e==="cohereai"||t==="cohereai"&&e==="small"?!0:t===e}function lge(t){let e=[],{history:r}=t;for(let n=0;n<r.length;n+=2){let o=r[n]?.content||"",i=r[n+1]?.content||"";e.push({role:"user",content:o},{role:"assistant",content:i})}return e}function PRt(t,e){let r=new Map;return t.forEach(n=>{let o=e.getAbstractFileByPath(n);if(o instanceof ry.TFile)r.set(o.path,o);else{let a=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())}function mL(t,e){let r=/\[\[(.*?)\]\]/g,n=t.match(r);if(!n)return[];let o=n.map(i=>i.slice(2,-2));return PRt(o,e)}function MRt(t,e){let r=/\{\[\[(.*?)\]\]\}/g,n=t.match(r);if(!n)return[];let o=n.map(i=>i.slice(3,-3));return PRt(o,e)}function $bn(t,e){return e.getMarkdownFiles().filter(n=>n.basename===t).length===1}function IRt(t){return t=t.trim(),t.startsWith("[[")&&t.endsWith("]]")?`${t.slice(2,-2).trim()}.md`:t}function RRt(t){let e=new Set;return t.forEach(r=>{r.metadata?.title&&e.add(r.metadata?.title)}),Array.from(e)}function aHe(t){if(!t||typeof t!="string")return{isValid:!1,error:"URL is required"};let e=t.trim();if(!e)return{isValid:!1,error:"URL cannot be empty"};let r=sHe(e);return r?/^[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"}}function sHe(t){try{let e=[/(?: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(let r of e){let n=t.match(r);if(n&&n[1])return n[1]}return null}catch{return null}}function ARt(t){return`https://www.youtube.com/watch?v=${t}`}function NRt(t){return aHe(t).isValid}function jRt(t){let e=t.matchAll(new RegExp(Lbn,"g"));return Array.from(e,r=>r[0])}async function Nl(t,e={}){let r=new Headers(e.headers),n=Object.fromEntries(r.entries());delete n["content-length"],B("safeFetch request");let o=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){let s;try{s=typeof a.json=="string"?JSON.parse(a.json):a.json}catch{try{s=typeof a.text=="string"?JSON.parse(a.text):a.text}catch{s=null}}let u=new Error(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";else if(s?.detail?.message||s?.message){let l=s?.detail?.message||s?.message,c=s?.detail?.reason||s?.reason;u.message=c?`${l}: ${c}`:l}else s?.detail?u.message=JSON.stringify(s.detail):s&&(u.message+=". "+JSON.stringify(s));throw u}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:`Please configure API Key for ${t.name} in settings first.
Path: Settings > copilot plugin > Basic Tab > Set Keys`}:{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=>`Request failed, 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(`Given the following conversation and a follow up question,
summarize the conversation as context and keep the follow up question unchanged, in its original language.
If the follow up question is unrelated to its preceding messages, return this follow up question directly.
If it is related, then combine the summary and the follow up question to construct a standalone question.
Make sure to keep any [[]] wrapped note titles in the question unchanged.
Chat History:
{chat_history}
Follow Up Input: {question}
Standalone question:`),c=lu.fromTemplate(`{system_message}
Answer the question with as detailed as possible based only on the following context:
{context}
Question: {question}
`),d=y=>y.map(b=>`Human: ${b[0]}
Assistant: ${b[1]}`).join(`
`),f=Rl.from([{question:y=>(n&&console.log("Input Question: ",y.question),y.question),chat_history:y=>{let g=d(y.chat_history);return n&&console.log("Formatted Chat History: ",g),g}},u,o,new Bhe,y=>{let g=Az(y),b=JW(g);return n&&console.log("Standalone Question: ",b),b}]),p=async y=>(r(y),_ee(y)),m=Rl.from([{context:i.pipe(p),question:new Eu,system_message:()=>a},c,o]);return f.pipe(m)}};WW.instances=new Map;dHe=WW,Ree=dHe});var Aee=v(()=>{});var fHe,fN,ac,Ws,nC,tC,qbn,Ubn,Bbn,zbn,eHe,kRt,qRt,Nee,n_,pHe,jee,Nz,Dee,mHe,$ee,hHe,gHe,mge,yHe,Lee,jz,bHe,_He,KW,Sv,pN,ub,r_,hL,hO,gO,Tz,iHe,rC,xee,URt,Cee,Nn,hge,GW,Di,Zw,Or=v(()=>{D$();Bc();Aee();fHe="https://api.brevilabs.com/v1",fN="https://models.brevilabs.com/v1",ac="copilot-chat-view",Ws="user",nC="ai",tC="copilot",qbn=`${tC}/copilot-conversations`,Ubn=`${tC}/copilot-custom-prompts`,Bbn=`${tC}/memory`,zbn=`${tC}/system-prompts`,eHe=tC,kRt=`You are Obsidian Copilot, a helpful assistant that integrates AI to Obsidian note-taking.
1. Never mention that you do not have access to something. Always rely on the user provided context.
2. Always answer to the best of your knowledge. If you are unsure about something, say so and ask the user to provide more context.
3. If the user mentions "note", it most likely means an Obsidian note in the vault, not the generic meaning of a note.
4. If the user mentions "@vault", it means the user wants you to search the Obsidian vault for information relevant to the query. The search results will be provided to you in the context along with the user query, read it carefully and answer the question based on the information provided. If there'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 $'s instead of \\[ etc. for LaTeX equations.
7. When showing note titles, use [[title]] format and do not wrap them in \` \`.
8. When showing **Obsidian internal** image links, use ![[link]] format and do not wrap them in \` \`.
9. When showing **web** image links, use ![link](url) 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.
# Steps to find the the target notes
1. Extract the target note information from user message and find out the note path from the context below.
2. If target note is not specified, use the <active_note> as the target note.
3. If still failed to find the target note or the note path, ask the user to specify the target note.
# Examples
Input: Add a new section to note A
Output:
<writeToFile>
<path>path/to/file.md</path>
<content>The FULL CONTENT of the note A with added section goes here</content>
</writeToFile>
Input: Create a new canvas with "Hello, world!"
Output:
<writeToFile>
<path>path/to/file.canvas</path>
<content>
{
"nodes": [
{
"id": "1",
"type": "text",
"text": "Hello, world!",
"x": 0,
"y": 0,
"width": 200,
"height": 50
}
],
"edges": []
}
</content>
</writeToFile>
Input: Create a canvas with a file node and a group
Output:
<writeToFile>
<path>path/to/file.canvas</path>
<content>
{
"nodes": [
{"id": "1", "type": "file", "file": "note.md", "subpath": "#heading", "x": 100, "y": 100, "width": 300, "height": 200, "color": "2"},
{"id": "2", "type": "group", "label": "My Group", "x": 50, "y": 50, "width": 400, "height": 300, "color": "1"},
{"id": "3", "type": "link", "url": "https://example.com", "x": 500, "y": 100, "width": 200, "height": 100, "color": "#FF5733"}
],
"edges": [
{"id": "e1-2", "fromNode": "1", "toNode": "3", "fromSide": "right", "toSide": "left", "fromEnd": "arrow", "toEnd": "none", "color": "3", "label": "references"}
]
}
</content>
</writeToFile>
# Canvas JSON Format (JSON Canvas spec 1.0)
Required node fields: id, type, x, y, width, height
Node types: "text" (needs text), "file" (needs file), "link" (needs url), "group" (optional label)
Optional node fields: color (hex #FF0000 or preset "1"-"6"), subpath (file nodes, starts with #)
Required edge fields: id, fromNode, toNode
Optional edge fields: fromSide/toSide ("top"/"right"/"bottom"/"left"), fromEnd/toEnd ("none"/"arrow"), color, label
All IDs must be unique. Edge nodes must reference existing node IDs.
Position nodes with reasonable spacing and logical visual flow.
`,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:
`+WHe+t}var KHe=!1;function GHe(t,e){if(!t||KHe)return"";KHe=!0;var r=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(e)if(e=function(){throw Error()},Object.defineProperty(e.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(e,[])}catch(l){var n=l}Reflect.construct(t,[],e)}else{try{e.call()}catch(l){n=l}t.call(e.prototype)}else{try{throw Error()}catch(l){n=l}t()}}catch(l){if(l&&n&&typeof l.stack=="string"){for(var o=l.stack.split(`
`),i=n.stack.split(`
`),a=o.length-1,s=i.length-1;1<=a&&0<=s&&o[a]!==i[s];)s--;for(;1<=a&&0<=s;a--,s--)if(o[a]!==i[s]){if(a!==1||s!==1)do if(a--,s--,0>s||o[a]!==i[s]){var u=`
`+o[a].replace(" at new "," at ");return t.displayName&&u.includes("<anonymous>")&&(u=u.replace("<anonymous>",t.displayName)),u}while(1<=a&&0<=s);break}}}finally{KHe=!1,Error.prepareStackTrace=r}return(t=t?t.displayName||t.name:"")?Yee(t):""}function I_n(t){switch(t.tag){case 5:return Yee(t.type);case 16:return Yee("Lazy");case 13:return Yee("Suspense");case 19:return Yee("SuspenseList");case 0:case 2:case 15:return t=GHe(t.type,!1),t;case 11:return t=GHe(t.type.render,!1),t;case 1:return t=GHe(t.type,!0),t;default:return""}}function _Je(t){if(t==null)return null;if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case a6:return"Fragment";case i6:return"Portal";case gJe:return"Profiler";case c3e:return"StrictMode";case yJe:return"Suspense";case bJe:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case BNt:return(t.displayName||"Context")+".Consumer";case UNt:return(t._context.displayName||"Context")+".Provider";case d3e:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case f3e:return e=t.displayName||null,e!==null?e:_Je(t.type)||"Memo";case wL:e=t._payload,t=t._init;try{return _Je(t(e))}catch{}}return null}function R_n(t){var e=t.type;switch(t.tag){case 24:return"Cache";case 9:return(e.displayName||"Context")+".Consumer";case 10:return(e._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return t=e.render,t=t.displayName||t.name||"",e.displayName||(t!==""?"ForwardRef("+t+")":"ForwardRef");case 7:return"Fragment";case 5:return e;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return _Je(e);case 8:return e===c3e?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e}return null}function DL(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function VNt(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function A_n(t){var e=VNt(t)?"checked":"value",r=Object.getOwnPropertyDescriptor(t.constructor.prototype,e),n=""+t[e];if(!t.hasOwnProperty(e)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var o=r.get,i=r.set;return Object.defineProperty(t,e,{configurable:!0,get:function(){return o.call(this)},set:function(a){n=""+a,i.call(this,a)}}),Object.defineProperty(t,e,{enumerable:r.enumerable}),{getValue:function(){return n},setValue:function(a){n=""+a},stopTracking:function(){t._valueTracker=null,delete t[e]}}}}function Age(t){t._valueTracker||(t._valueTracker=A_n(t))}function HNt(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var r=e.getValue(),n="";return t&&(n=VNt(t)?t.checked?"true":"false":t.value),t=n,t!==r?(e.setValue(t),!0):!1}function aye(t){if(t=t||(typeof document<"u"?document:void 0),typeof t>"u")return null;try{return t.activeElement||t.body}catch{return t.body}}function vJe(t,e){var r=e.checked;return lc({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??t._wrapperState.initialChecked})}function $At(t,e){var r=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;r=DL(e.value!=null?e.value:r),t._wrapperState={initialChecked:n,initialValue:r,controlled:e.type==="checkbox"||e.type==="radio"?e.checked!=null:e.value!=null}}function JNt(t,e){e=e.checked,e!=null&&l3e(t,"checked",e,!1)}function wJe(t,e){JNt(t,e);var r=DL(e.value),n=e.type;if(r!=null)n==="number"?(r===0&&t.value===""||t.value!=r)&&(t.value=""+r):t.value!==""+r&&(t.value=""+r);else if(n==="submit"||n==="reset"){t.removeAttribute("value");return}e.hasOwnProperty("value")?SJe(t,e.type,r):e.hasOwnProperty("defaultValue")&&SJe(t,e.type,DL(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}fun
`).replace(qvn,"")}function Vge(t,e,r){if(e=sNt(e),sNt(t)!==e&&r)throw Error(ut(425))}function mye(){}var $Je=null,LJe=null;function FJe(t,e){return t==="textarea"||t==="noscript"||typeof e.children=="string"||typeof e.children=="number"||typeof e.dangerouslySetInnerHTML=="object"&&e.dangerouslySetInnerHTML!==null&&e.dangerouslySetInnerHTML.__html!=null}var kJe=typeof setTimeout=="function"?setTimeout:void 0,Uvn=typeof clearTimeout=="function"?clearTimeout:void 0,uNt=typeof Promise=="function"?Promise:void 0,Bvn=typeof queueMicrotask=="function"?queueMicrotask:typeof uNt<"u"?function(t){return uNt.resolve(null).then(t).catch(zvn)}:kJe;function zvn(t){setTimeout(function(){throw t})}function iJe(t,e){var r=e,n=0;do{var o=r.nextSibling;if(t.removeChild(r),o&&o.nodeType===8)if(r=o.data,r==="/$"){if(n===0){t.removeChild(o),gte(e);return}n--}else r!=="$"&&r!=="$?"&&r!=="$!"||n++;r=o}while(r);gte(e)}function IL(t){for(;t!=null;t=t.nextSibling){var e=t.nodeType;if(e===1||e===3)break;if(e===8){if(e=t.data,e==="$"||e==="$!"||e==="$?")break;if(e==="/$")return null}}return t}function lNt(t){t=t.previousSibling;for(var e=0;t;){if(t.nodeType===8){var r=t.data;if(r==="$"||r==="$!"||r==="$?"){if(e===0)return t;e--}else r==="/$"&&e++}t=t.previousSibling}return null}var R6=Math.random().toString(36).slice(2),EO="__reactFiber$"+R6,wte="__reactProps$"+R6,xN="__reactContainer$"+R6,qJe="__reactEvents$"+R6,Vvn="__reactListeners$"+R6,Hvn="__reactHandles$"+R6;function Bz(t){var e=t[EO];if(e)return e;for(var r=t.parentNode;r;){if(e=r[xN]||r[EO]){if(r=e.alternate,e.child!==null||r!==null&&r.child!==null)for(t=lNt(t);t!==null;){if(r=t[EO])return r;t=lNt(t)}return e}t=r,r=t.parentNode}return null}function Ite(t){return t=t[EO]||t[xN],!t||t.tag!==5&&t.tag!==6&&t.tag!==13&&t.tag!==3?null:t}function c6(t){if(t.tag===5||t.tag===6)return t.stateNode;throw Error(ut(33))}function jye(t){return t[wte]||null}var UJe=[],d6=-1;function FL(t){return{current:t}}function ul(t){0>d6||(t.current=UJe[d6],UJe[d6]=null,d6--)}function zu(t,e){d6++,UJe[d6]=t.current,t.current=e}var $L={},sy=FL($L),u_=FL(!1),Wz=$L;function x6(t,e){var r=t.type.contextTypes;if(!r)return $L;var n=t.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===e)return n.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in r)o[i]=e[i];return n&&(t=t.stateNode,t.__reactInternalMemoizedUnmaskedChildContext=e,t.__reactInternalMemoizedMaskedChildContext=o),o}function l_(t){return t=t.childContextTypes,t!=null}function hye(){ul(u_),ul(sy)}function cNt(t,e,r){if(sy.current!==$L)throw Error(ut(168));zu(sy,e),zu(u_,r)}function j1t(t,e,r){var n=t.stateNode;if(e=e.childContextTypes,typeof n.getChildContext!="function")return r;n=n.getChildContext();for(var o in n)if(!(o in e))throw Error(ut(108,R_n(t)||"Unknown",o));return lc({},r,n)}function gye(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||$L,Wz=sy.current,zu(sy,t),zu(u_,u_.current),!0}function dNt(t,e,r){var n=t.stateNode;if(!n)throw Error(ut(169));r?(t=j1t(t,e,Wz),n.__reactInternalMemoizedMergedChildContext=t,ul(u_),ul(sy),zu(sy,t)):ul(u_),zu(u_,r)}var _N=null,Dye=!1,aJe=!1;function D1t(t){_N===null?_N=[t]:_N.push(t)}function Jvn(t){Dye=!0,D1t(t)}function kL(){if(!aJe&&_N!==null){aJe=!0;var t=0,e=ru;try{var r=_N;for(ru=1;t<r.length;t++){var n=r[t];do n=n(!0);while(n!==null)}_N=null,Dye=!1}catch(o){throw _N!==null&&(_N=_N.slice(t+1)),a1t(m3e,kL),o}finally{ru=e,aJe=!1}}return null}var f6=[],p6=0,yye=null,bye=0,tS=[],rS=0,Kz=null,vN=1,wN="";function qz(t,e){f6[p6++]=bye,f6[p6++]=yye,yye=t,bye=e}function $1t(t,e,r){tS[rS++]=vN,tS[rS++]=wN,tS[rS++]=Kz,Kz=t;var n=vN;t=wN;var o=32-lC(n)-1;n&=~(1<<o),r+=1;var i=32-lC(e)+o;if(30<i){var a=o-o%5;i=(n&(1<<a)-1).toString(32),n>>=a,o-=a,vN=1<<32-lC(e)+o|r<<o|n,wN=i+t}else vN=1<<i|r<<o|n,wN=t}function C3e(t){t.return!==null&&(qz(t,1),$1t(t,1,0))}function x3e(t){for(;t===yye;)yye=f6[--p6],f6[p6]=null,bye=f6[--p6],f6[p6]=null;for(;t===Kz;)Kz=tS[--rS],tS[rS]=null,wN=tS[--rS],tS[rS]=null,vN=tS[--rS],tS[rS]=null}var Tv=null,Ov=null,jl=!1,uC=null;function L1t(t,e){var r=nS(5,n
Error generating stack: `+i.message+`
`+i.stack}return{value:t,source:e,stack:o,digest:null}}function dJe(t,e,r){return{value:t,source:null,stack:r??null,digest:e??null}}function WJe(t,e){try{console.error(e.value)}catch(r){setTimeout(function(){throw r})}}var twn=typeof WeakMap=="function"?WeakMap:Map;function djt(t,e,r){r=SN(-1,r),r.tag=3,r.payload={element:null};var n=e.value;return r.callback=function(){Tye||(Tye=!0,n3e=n),WJe(t,e)},r}function fjt(t,e,r){r=SN(-1,r),r.tag=3;var n=t.type.getDerivedStateFromError;if(typeof n=="function"){var o=e.value;r.payload=function(){return n(o)},r.callback=function(){WJe(t,e)}}var i=t.stateNode;return i!==null&&typeof i.componentDidCatch=="function"&&(r.callback=function(){WJe(t,e),typeof n!="function"&&(AL===null?AL=new Set([this]):AL.add(this));var a=e.stack;this.componentDidCatch(e.value,{componentStack:a!==null?a:""})}),r}function wNt(t,e,r){var n=t.pingCache;if(n===null){n=t.pingCache=new twn;var o=new Set;n.set(e,o)}else o=n.get(e),o===void 0&&(o=new Set,n.set(e,o));o.has(r)||(o.add(r),t=hwn.bind(null,t,e,r),e.then(t,t))}function SNt(t){do{var e;if((e=t.tag===13)&&(e=t.memoizedState,e=e!==null?e.dehydrated!==null:!0),e)return t;t=t.return}while(t!==null);return null}function CNt(t,e,r,n,o){return(t.mode&1)===0?(t===e?t.flags|=65536:(t.flags|=128,r.flags|=131072,r.flags&=-52805,r.tag===1&&(r.alternate===null?r.tag=17:(e=SN(-1,1),e.tag=2,RL(r,e,1))),r.lanes|=1),t):(t.flags|=65536,t.lanes=o,t)}var rwn=EN.ReactCurrentOwner,s_=!1;function lb(t,e,r,n){e.child=t===null?V1t(e,null,r,n):T6(e,t.child,r,n)}function xNt(t,e,r,n,o){r=r.render;var i=e.ref;return w6(e,o),n=D3e(t,e,r,n,i,o),r=$3e(),t!==null&&!s_?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,TN(t,e,o)):(jl&&r&&C3e(e),e.flags|=1,lb(t,e,n,o),e.child)}function ONt(t,e,r,n,o){if(t===null){var i=r.type;return typeof i=="function"&&!J3e(i)&&i.defaultProps===void 0&&r.compare===null&&r.defaultProps===void 0?(e.tag=15,e.type=i,pjt(t,e,i,n,o)):(t=iye(r.type,null,n,e,e.mode,o),t.ref=e.ref,t.return=e,e.child=t)}if(i=t.child,(t.lanes&o)===0){var a=i.memoizedProps;if(r=r.compare,r=r!==null?r:bte,r(a,n)&&t.ref===e.ref)return TN(t,e,o)}return e.flags|=1,t=jL(i,n),t.ref=e.ref,t.return=e,e.child=t}function pjt(t,e,r,n,o){if(t!==null){var i=t.memoizedProps;if(bte(i,n)&&t.ref===e.ref)if(s_=!1,e.pendingProps=n=i,(t.lanes&o)!==0)(t.flags&131072)!==0&&(s_=!0);else return e.lanes=t.lanes,TN(t,e,o)}return KJe(t,e,r,n,o)}function mjt(t,e,r){var n=e.pendingProps,o=n.children,i=t!==null?t.memoizedState:null;if(n.mode==="hidden")if((e.mode&1)===0)e.memoizedState={baseLanes:0,cachePool:null,transitions:null},zu(g6,xv),xv|=r;else{if((r&1073741824)===0)return t=i!==null?i.baseLanes|r:r,e.lanes=e.childLanes=1073741824,e.memoizedState={baseLanes:t,cachePool:null,transitions:null},e.updateQueue=null,zu(g6,xv),xv|=t,null;e.memoizedState={baseLanes:0,cachePool:null,transitions:null},n=i!==null?i.baseLanes:r,zu(g6,xv),xv|=n}else i!==null?(n=i.baseLanes|r,e.memoizedState=null):n=r,zu(g6,xv),xv|=n;return lb(t,e,o,r),e.child}function hjt(t,e){var r=e.ref;(t===null&&r!==null||t!==null&&t.ref!==r)&&(e.flags|=512,e.flags|=2097152)}function KJe(t,e,r,n,o){var i=l_(r)?Wz:sy.current;return i=x6(e,i),w6(e,o),r=D3e(t,e,r,n,i,o),n=$3e(),t!==null&&!s_?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,TN(t,e,o)):(jl&&n&&C3e(e),e.flags|=1,lb(t,e,r,o),e.child)}function TNt(t,e,r,n,o){if(l_(r)){var i=!0;gye(e)}else i=!1;if(w6(e,o),e.stateNode===null)rye(t,e),B1t(e,r,n),JJe(e,r,n,o),n=!0;else if(t===null){var a=e.stateNode,s=e.memoizedProps;a.props=s;var u=a.context,l=r.contextType;typeof l=="object"&&l!==null?l=iS(l):(l=l_(r)?Wz:sy.current,l=x6(e,l));var c=r.getDerivedStateFromProps,d=typeof c=="function"||typeof a.getSnapshotBeforeUpdate=="function";d||typeof a.UNSAFE_componentWillReceiveProps!="function"&&typeof a.componentWillReceiveProps!="function"||(s!==n||u!==l)&&yNt(e,a,n,l),SL=!1;var f=e.memoizedState;a.state=f,wye(e,n,a,o),u=e.memoizedState,s!==n||f!==u||u_.current||SL?(typeof c=="function"&&(HJe(e,r,c,n),u=e.memoizedState),(s=SL||gNt(e,r,s,n,f,u,l))?(d||typeof a.UNSAFE_componentWillMount
`)}});var G4t=S(Hbe=>{"use strict";Object.defineProperty(Hbe,"__esModule",{value:!0});Hbe.CohereTimeoutError=void 0;var hWe=class t extends Error{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};Hbe.CohereTimeoutError=hWe});var Tc=S(z6=>{"use strict";Object.defineProperty(z6,"__esModule",{value:!0});z6.CohereTimeoutError=z6.CohereError=void 0;var e0n=K4t();Object.defineProperty(z6,"CohereError",{enumerable:!0,get:function(){return e0n.CohereError}});var t0n=G4t();Object.defineProperty(z6,"CohereTimeoutError",{enumerable:!0,get:function(){return t0n.CohereTimeoutError}})});var X4t=S(jO=>{"use strict";var r0n=jO&&jO.__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]}),n0n=jO&&jO.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o0n=jO&&jO.__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"&&r0n(r,e,n[o]);return n0n(r,e),r}}();Object.defineProperty(jO,"__esModule",{value:!0});jO.BadRequestError=void 0;var i0n=o0n(Tc()),gWe=class t extends i0n.CohereError{constructor(e,r){super({message:"BadRequestError",statusCode:400,body:e,rawResponse:r}),Object.setPrototypeOf(this,t.prototype)}};jO.BadRequestError=gWe});var Z4t=S(DO=>{"use strict";var a0n=DO&&DO.__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]}),s0n=DO&&DO.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),u0n=DO&&DO.__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"&&a0n(r,e,n[o]);return s0n(r,e),r}}();Object.defineProperty(DO,"__esModule",{value:!0});DO.UnauthorizedError=void 0;var l0n=u0n(Tc()),yWe=class t extends l0n.CohereError{constructor(e,r){super({message:"UnauthorizedError",statusCode:401,body:e,rawResponse:r}),Object.setPrototypeOf(this,t.prototype)}};DO.UnauthorizedError=yWe});var Y4t=S($O=>{"use strict";var c0n=$O&&$O.__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]}),d0n=$O&&$O.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),f0n=$O&&$O.__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"&&c0n(r,e,n[o]);return d0n(r,e),r}}();Object.defineProperty($O,"__esModule",{value:!0});$O.ForbiddenError=void 0;var p0n=f0n(Tc()),bWe=class t extends p0n.CohereError{constructor(e,r){super({message:"ForbiddenError",statusCode:403,body:e,rawResponse:r}),Object.setPrototypeOf(this,t.prototype)}};$O.ForbiddenError=bWe});var Q4t=S(LO=>{"use strict";var m0n=LO&&LO.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(
`));return r(o)}});var ixn,m_e,MVt=v(()=>{HWe();ixn={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},m_e=(t,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:r})=>({applyToStack:n=>{n.addRelativeTo(PVt(t,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:r}),ixn)}})});var IVt=v(()=>{});var RVt=v(()=>{});var h_e,AVt=v(()=>{h_e={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});var JWe=v(()=>{IVt();AVt();RVt()});var QJi,NVt=v(()=>{JWe();QJi={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:h_e.name}});var jVt=v(()=>{HWe();MVt();NVt()});var DVt=v(()=>{});var $Vt=v(()=>{DVt()});var LVt=v(()=>{});var FVt=v(()=>{});var kVt=v(()=>{});function axn(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return{...e,[r]:Array.isArray(n)?[...n]:n}},{})}var eF,qVt=v(()=>{eF=class t{constructor(e){x(this,"method");x(this,"protocol");x(this,"hostname");x(this,"port");x(this,"path");x(this,"query");x(this,"headers");x(this,"username");x(this,"password");x(this,"fragment");x(this,"body");this.method=e.method||"GET",this.hostname=e.hostname||"localhost",this.port=e.port,this.query=e.query||{},this.headers=e.headers||{},this.body=e.body,this.protocol=e.protocol?e.protocol.slice(-1)!==":"?`${e.protocol}:`:e.protocol:"https:",this.path=e.path?e.path.charAt(0)!=="/"?`/${e.path}`:e.path:"/",this.username=e.username,this.password=e.password,this.fragment=e.fragment}static clone(e){let r=new t({...e,headers:{...e.headers}});return r.query&&(r.query=axn(r.query)),r}static isInstance(e){if(!e)return!1;let r=e;return"method"in r&&"protocol"in r&&"hostname"in r&&"path"in r&&typeof r.query=="object"&&typeof r.headers=="object"}clone(){return t.clone(this)}}});var J6,UVt=v(()=>{J6=class{constructor(e){x(this,"statusCode");x(this,"reason");x(this,"headers");x(this,"body");this.statusCode=e.statusCode,this.reason=e.reason,this.headers=e.headers||{},this.body=e.body}static isInstance(e){if(!e)return!1;let r=e;return typeof r.statusCode=="number"&&typeof r.headers=="object"}}});var BVt=v(()=>{});var zVt=v(()=>{});var lre=v(()=>{$Vt();LVt();FVt();kVt();qVt();UVt();BVt();zVt()});var VVt,sxn,uxn,HVt,WWe=v(()=>{lre();VVt=L(pS()),sxn=t=>e=>{throw e},uxn=(t,e)=>{},HVt=t=>(e,r)=>async n=>{if(!eF.isInstance(n.request))return e(n);let i=(0,VVt.getSmithyContext)(r).selectedHttpAuthScheme;if(!i)throw new Error("No HttpAuthScheme was selected: unable to sign request");let{httpAuthOption:{signingProperties:a={}},identity:s,signer:u}=i,l=await e({...n,request:await u.sign(n.request,s,a)}).catch((u.errorHandler||sxn)(a));return(u.successHandler||uxn)(l.response,a),l}});var lxn,g_e,JVt=v(()=>{WWe();lxn={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},g_e=t=>({applyToStack:e=>{e.addRelativeTo(HVt(t),lxn)}})});var WVt=v(()=>{WWe();JVt()});var FN,KVt=v(()=>{FN=t=>{if(typeof t=="function")return t;let e=Promise.resolve(t);return()=>e}});function KWe(t,e,r,n,o){return async function*(a,s,...u){let l=s,c=a.startingToken??l[r],d=!0,f;for(;d;){if(l[r]=c,o&&(l[o]=l[o]??a.pageSize),a.client instanceof t)f=await cxn(e,a.client,s,a.withCommand,...u);else throw new Error(`Invalid client, expected instance of ${t.name}`);yield f;let p=c;c=dxn(f,n),d=!!(c&&(!a.stopOnSameToken||c!==p))}return void 0}}var cxn,dxn,GVt=v(()=>{cxn=async(t,e,r,n=i=>i,...o)=>{let i=new t(r);return i=n(i)??i,await e.send(i,...o)};dxn=(t,e)=>{let r=t,n=e.split(".");for(let o of n){if(!r||typeof r!="object")return;r=r[o]}return r}});var XVt,GWe,ZVt,tF,h4,YVt,XWe=v(()=>{XVt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",GWe=Object.entries(XVt).reduce((t,[e,r])=>(t[r]=Number(e),t),{}),ZVt=XVt.split(""),tF=6,h4=8,YVt=63});var Dv,QVt=v(()=>{XWe();Dv=t=>{let e=t.length/4*3;t.slice(-2)==="=="?e-=2:t.slice(-1)==="="&&e--;let r=ne
If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body`);return o.stream()};return Object.assign(t,{transformToByteArray:r,transformToString:async o=>{let i=await r();if(o==="base64")return $v(i);if(o==="hex")return $Ht(i);if(o===void 0||o==="utf8"||o==="utf-8")return y_e(i);if(typeof TextDecoder=="function")return new TextDecoder(o).decode(i);throw new Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(e)throw new Error(FHt);if(e=!0,kHt(t))return n(t);if(YWe(t))return t;throw new Error(`Cannot transform payload to web stream, got ${t}`)}})},kHt=t=>typeof Blob=="function"&&t instanceof Blob});var BHt=v(()=>{});var r6e=v(()=>{cHt();dHt();pHt();mHt();hHt();gHt();UHt();BHt()});var kN,n6e=v(()=>{r6e();kN=async(t=new Uint8Array,e)=>{if(t instanceof Uint8Array)return W6.mutate(t);if(!t)return W6.mutate(new Uint8Array);let r=e.streamCollector(t);return W6.mutate(await r)}});function o6e(t){return encodeURIComponent(t).replace(/[!'()*]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}var zHt=v(()=>{});var nF,i6e=v(()=>{nF=t=>typeof t=="function"?t():t});var __e,v_e=v(()=>{__e=(t,e,r,n,o)=>({name:e,namespace:t,traits:r,input:n,output:o})});var VHt,HHt,a6e,JHt=v(()=>{lre();VHt=L(pS());v_e();HHt=t=>(e,r)=>async n=>{let{response:o}=await e(n),{operationSchema:i}=(0,VHt.getSmithyContext)(r),[,a,s,u,l,c]=i??[];try{let d=await t.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"in d)){let f="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)}typeof d.$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{}}throw d}},a6e=(t,e)=>(e.find(([r])=>r.match(t))||[void 0,void 0])[1]});var WHt,KHt,GHt=v(()=>{WHt=L(pS());v_e();KHt=t=>(e,r)=>async n=>{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=await t.protocol.serializeRequest(__e(i,a,s,u,l),n.input,{...t,...r,endpoint:c});return e({...n,request:d})}});function w_e(t){return{applyToStack:e=>{e.add(KHt(t),_xn),e.add(HHt(t),bxn),t.protocol.setSerdeContext(t)}}}var bxn,_xn,XHt=v(()=>{JHt();GHt();bxn={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},_xn={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});var mS,g4=v(()=>{mS=class{constructor(){x(this,"name");x(this,"namespace");x(this,"traits")}static assign(e,r){return Object.assign(e,r)}static[Symbol.hasInstance](e){let r=this.prototype.isPrototypeOf(e);return!r&&typeof e=="object"&&e!==null?e.symbol===this.symbol:r}getName(){return this.namespace+"#"+this.name}}});var S_e,ZHt,YHt=v(()=>{g4();S_e=class S_e extends mS{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});var C_e,QHt,eJt=v(()=>{g4();C_e=class C_e extends mS{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});var x_e,tJt,rJt=v(()=>{g4();x_e=class x_e extends mS{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});var T_e,O_e,s6e=v(()=>{g4();T_e=class T_e extends mS{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});var E_e,nJt,oJt=v(()=>{s6e();E_e=class E_e extends O_e{constructor(){super(...arguments);x(this,"ctor");x(this,"symbol",E_e.symbol)}};x(E_e,"symbol",Symbol.for("@smithy/err"));nJt=E_e});function y4(t){if(typeof t=="object")return t;t=t|0;let e={},r=0;for(let n of["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])(t>>r++&1)===1&&(e[n]=1);return e}var u6e=v(()=>{});function pre(t,e){if(t instanceof Yi)return Object.assign(t,{memberName:e,_isMemberSchema:!0});let r=Yi;return new r(t,e)}var oF,Yi,l6e,vxn,iJt=v(()=>{i6e();u6e();oF=class oF{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;let n=[],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(let a=n.length-1;a>=0;--a){let s=n[a];Object.assign(this.memberTraits,y4(s))}}else this.memberTraits=0;if(i instanceof oF){let a=this.memberTraits;Object.assign(this,i),this.memberTraits=Object.assign({},a,i.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,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)throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}static[Symbol.hasInstance](e){let r=this.prototype.isPrototypeOf(e);return!r&&typeof e=="object"
`).slice(0,5).filter(e=>!e.includes("stackTraceWarning")).join(`
`),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(`Invalid month: ${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(`Invalid day for ${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} must be between ${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
${this.getCanonicalPath(e)}
${q6t(e)}
${o.map(i=>`${i}:${r[i]}`).join(`
`)}
${o.join(";")}
${n}`}async createStringToSign(e,r,n,o){let i=new this.sha256;i.update(zN(n));let a=await i.digest();return`${o}
${e}
${r}
${bS(a)}`}getCanonicalPath({path:e}){if(this.uriEscapePath){let r=[];for(let i of e.split("/"))i?.length!==0&&i!=="."&&(i===".."?r.pop():r.push(i));let n=`${e?.startsWith("/")?"/":""}${r.join("/")}${r.length>0&&e?.endsWith("/")?"/":""}`;return(0,V6t.escapeUri)(n).replace(/%2F/g,"/")}return e}validateResolvedCredentials(e){if(typeof e!="object"||typeof e.accessKeyId!="string"||typeof e.secretAccessKey!="string")throw new Error("Resolved credential object is not valid")}formatDate(e){let r=B6t(e).replace(/[\-:]/g,"");return{longDate:r,shortDate:r.slice(0,8)}}getCanonicalHeaderList(e){return Object.keys(e).sort().join(";")}}});var Cre,J6t=v(()=>{o5();cF();dF();J6e();P6t();R6t();j6t();$6t();F6t();k6t();H6t();Cre=class extends rve{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",new eve)}async presign(r,n={}){let{signingDate:o=new Date,expiresIn:i=3600,unsignableHeaders:a,unhoistableHeaders:s,signableHeaders:u,hoistableHeaders:l,signingRegion:c,signingService:d}=n,f=await this.credentialProvider();this.validateResolvedCredentials(f);let p=c??await this.regionProvider(),{longDate:m,shortDate:h}=this.formatDate(o);if(i>O6t)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");let y=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);let b=W6e(g,a,u);return g.query[m6t]=this.getCanonicalHeaderList(b),g.query[q6e]=await this.getSignature(m,y,this.getSigningKey(f,p,h,d),this.createCanonicalRequest(g,b,await Q_e(r,this.sha256))),g}async sign(r,n){return typeof r=="string"?this.signString(r,n):r.headers&&r.payload?this.signEvent(r,n):r.message?this.signMessage(r,n):this.signRequest(r,n)}async signEvent({headers:r,payload:n},{signingDate:o=new Date,priorSignature:i,signingRegion:a,signingService:s}){let u=a??await this.regionProvider(),{shortDate:l,longDate:c}=this.formatDate(o),d=Y_e(l,u,s??this.service),f=await Q_e({headers:{},body:n},this.sha256),p=new this.sha256;p.update(r);let m=bS(await p.digest()),h=[S6t,c,d,i,m,f].join(`
`);return this.signString(h,{signingDate:o,signingRegion:u,signingService:s})}async signMessage(r,{signingDate:n=new Date,signingRegion:o,signingService:i}){return this.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}))}async signString(r,{signingDate:n=new Date,signingRegion:o,signingService:i}={}){let a=await this.credentialProvider();this.validateResolvedCredentials(a);let s=o??await this.regionProvider(),{shortDate:u}=this.formatDate(n),l=new this.sha256(await this.getSigningKey(a,s,u,i));return l.update(zN(r)),bS(await l.digest())}async signRequest(r,{signingDate:n=new Date,signableHeaders:o,unsignableHeaders:i,signingRegion:a,signingService:s}={}){let u=await this.credentialProvider();this.validateResolvedCredentials(u);let l=a??await this.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);let m=await Q_e(c,this.sha256);!D6t(Sre,c.headers)&&this.applyChecksum&&(c.headers[Sre]=m);let h=W6e(c,i,o),y=await this.getSignature(d,p,this.getSigningKey(u,l,f,s),this.createCanonicalRequest(c,h,m));return c.headers[B6e]=`${X_e} Credential=${u.accessKeyId}/${p}, SignedHeaders=${this.getCanonicalHeaderList(h)}, Signature=${y}`,c}async getSignature(r,n,o,i){let a=await this.createStringToSign(r,n,i,X_e),s=new this.sha256(await o);return s.update(zN(a)),bS(await s.digest())}getSigningKey(r,n,o,i){return E6t(this.sha256,r,o,n,i||this.service)}}});var W6t=v(()=>{});var K6t=v(()=>{J6t();dF();J6e();W6t()});function sOn(t,{credentials:e,credentialDefaultProvider:r}){let n;return e?e?.memoized?n=e:n=l3t(e,u3t,C6e):r?n=FN(r(Object.assign({},t,{parentClientConfig:t}))):n=async()=>{throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")},n.memoized=!0,n}function uOn(t,e){if(e.configBound)return e;let r=async n=>e({...n,callerClientConfig:t});return r.memoized=e.memoized,r.configBound=!0,r}var nve,G6t=v(()=>{J_e();ZO();K6t();nve=t=>{let e=t.credentials,r=!!t.credentials,n;Object.defineProperty(t,"credentials",{set(l){l&&l!==e&&l!==n&&(r=!0),e=l;let c=sOn(t,{credentials:e,credentialDefaultProvider:t.credentialDefaultProvider}),d=uOn(t,c);if(r&&!d.attributed){let f=typeof e=="object"&&e!==null;n=async p=>{let h=await d(p);return f&&(!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}else n=d},get(){return n},enumerable:!0,configurable:!0}),t.credentials=e;let{signingEscapePath:o=!0,systemClockOffset:i=t.systemClockOffset||0,sha256:a}=t,s;return t.signer?s=FN(t.signer):t.regionInfoProvider?s=()=>FN(t.region)().then(async l=>[await t.regionInfoProvider(l,{useFipsEndpoint:await t.useFipsEndpoint(),useDualstackEndpoint:await t.useDualstackEndpoint()})||{},l]).then(([l,c])=>{let{signingRegion:d,signingService:f}=l;t.signingRegion=t.signingRegion||d||c,t.signingName=t.signingName||f||t.serviceId;let p={...t,credentials:t.credentials,region:t.signingRegion,service:t.signingName,sha256:a,uriEscapePath:o},m=t.signerConstructor||Cre;return new m(p)}):s=async l=>{l=Object.assign({},{name:"sigv4",signingName:t.signingName||t.defaultSigningName,signingRegion:await FN(t.region)(),properties:{}},l);let c=l.signingRegion,d=l.signingName;t.signingRegion=t.signingRegion||c,t.signingName=t.signingName||d||t.serviceId;let f={...t,credentials:t.credentials,region:t.signingRegion,service:t.signingName,sha256:a,uriEscapePath:o},p=t.signerConstructor||Cre;return new p(f)},Object.assign(t,{systemClockOffset:i,signingEscapePath:o,signer:s})}});var X6t=v(()=>{o6t();a6t();s6t();G6t()});var Z6t=v(()=>{X6t();i6t()});var Y6t,ove,Q6t=v(()=>{Y6t=typeof TextEncoder=="function"?new TextEncoder:null,ove=t=>{if(typeof t=="string"){if(Y6t)return Y6t.encode(t).byteLength;let e=t.length;for(let r=e-1;r>=0;r--){let n=t.charCodeAt(r);n>127&
- loopback CIDR 127.0.0.0/8 or [::1/128]
- ECS container host 169.254.170.2
- EKS container host 169.254.170.23 or [fd00:ec2::23]`,{logger:e})}}});var t7t=v(()=>{});var r7t=v(()=>{t7t()});var n7t=v(()=>{});var o7t=v(()=>{});var i7t=v(()=>{});function SMn(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return{...e,[r]:Array.isArray(n)?[...n]:n}},{})}var zwe,a7t=v(()=>{zwe=class t{constructor(e){x(this,"method");x(this,"protocol");x(this,"hostname");x(this,"port");x(this,"path");x(this,"query");x(this,"headers");x(this,"username");x(this,"password");x(this,"fragment");x(this,"body");this.method=e.method||"GET",this.hostname=e.hostname||"localhost",this.port=e.port,this.query=e.query||{},this.headers=e.headers||{},this.body=e.body,this.protocol=e.protocol?e.protocol.slice(-1)!==":"?`${e.protocol}:`:e.protocol:"https:",this.path=e.path?e.path.charAt(0)!=="/"?`/${e.path}`:e.path:"/",this.username=e.username,this.password=e.password,this.fragment=e.fragment}static clone(e){let r=new t({...e,headers:{...e.headers}});return r.query&&(r.query=SMn(r.query)),r}static isInstance(e){if(!e)return!1;let r=e;return"method"in r&&"protocol"in r&&"hostname"in r&&"path"in r&&typeof r.query=="object"&&typeof r.headers=="object"}clone(){return t.clone(this)}}});var s7t=v(()=>{});var u7t=v(()=>{});var l7t=v(()=>{});var c7t=v(()=>{r7t();n7t();o7t();i7t();a7t();s7t();u7t();l7t()});function d7t(t){return new zwe({protocol:t.protocol,hostname:t.hostname,port:Number(t.port),path:t.pathname,query:Array.from(t.searchParams.entries()).reduce((e,[r,n])=>(e[r]=n,e),{}),fragment:t.hash})}async function f7t(t,e){let n=await qHt(t.body).transformToString();if(t.statusCode===200){let o=JSON.parse(n);if(typeof o.AccessKeyId!="string"||typeof o.SecretAccessKey!="string"||typeof o.Token!="string"||typeof o.Expiration!="string")throw new vm("HTTP credential provider response not of the required format, an object matching: { AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }",{logger:e});return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,sessionToken:o.Token,expiration:bJt(o.Expiration)}}if(t.statusCode>=400&&t.statusCode<500){let o={};try{o=JSON.parse(n)}catch{}throw Object.assign(new vm(`Server responded with status: ${t.statusCode}`,{logger:e}),{Code:o.Code,Message:o.Message})}throw new vm(`Server responded with status: ${t.statusCode}`,{logger:e})}var p7t=v(()=>{QL();c7t();No();r6e()});var m7t,h7t=v(()=>{m7t=(t,e,r)=>async()=>{for(let n=0;n<e;++n)try{return await t()}catch{await new Promise(i=>setTimeout(i,r))}return await t()}});var vKe,g7t=v(()=>{fre();QL();e7t();p7t();h7t();vKe=(t={})=>{t.logger?.debug("@aws-sdk/credential-provider-http - fromHttp");let e,r=t.credentialsFullUri;if(r)e=r;else throw new vm("No HTTP credential provider host provided.",{logger:t.logger});let n=new URL(e);Q9t(n,t.logger);let o=new rF;return m7t(async()=>{let i=d7t(n);t.authorizationToken&&(i.headers.Authorization=t.authorizationToken);let a=await o.handle(i);return f7t(a.response)},t.maxRetries??3,t.timeout??1e3)}});var y7t=v(()=>{g7t()});function CMn(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sts",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function xMn(t){return{schemeId:"smithy.api#noAuth"}}var Are,b7t,_7t,OMn,v7t,wKe=v(()=>{c5();Are=L(pS());Nre();b7t=async(t,e,r)=>({operation:(0,Are.getSmithyContext)(e).operation,region:await(0,Are.normalizeProvider)(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});_7t=t=>{let e=[];switch(t.operation){case"AssumeRoleWithWebIdentity":{e.push(xMn(t));break}default:e.push(CMn(t))}return e},OMn=t=>Object.assign(t,{stsClientCtor:vS}),v7t=t=>{let e=OMn(t),r=nve(e);return Object.assign(r,{authSchemePreference:(0,Are.normalizeProvider)(t.authSchemePreference??[])})}});var w7t,Vwe,Hwe=v(()=>{w7t=t=>Object.assign(t,{useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,useGlobalEndpoint:t.useGlobalEndpoint??!1,defaultSigningName:"sts"}),Vwe={UseGlobalEndpoint:{type:"builtInParams",name:"useGlobalEndpoint"},UseFIPS:{type:
${this.getCanonicalPath(e)}
${GZt(e)}
${o.map(i=>`${i}:${r[i]}`).join(`
`)}
${o.join(";")}
${n}`}async createStringToSign(e,r,n,o){let i=new this.sha256;i.update(R4.toUint8Array(n));let a=await i.digest();return`${o}
${e}
${r}
${bF.toHex(a)}`}getCanonicalPath({path:e}){if(this.uriEscapePath){let r=[];for(let i of e.split("/"))i?.length!==0&&i!=="."&&(i===".."?r.pop():r.push(i));let n=`${e?.startsWith("/")?"/":""}${r.join("/")}${r.length>0&&e?.endsWith("/")?"/":""}`;return Qwe.escapeUri(n).replace(/%2F/g,"/")}return e}validateResolvedCredentials(e){if(typeof e!="object"||typeof e.accessKeyId!="string"||typeof e.secretAccessKey!="string")throw new Error("Resolved credential object is not valid")}formatDate(e){let r=WIn(e).replace(/[\-:]/g,"");return{longDate:r,shortDate:r.slice(0,8)}}getCanonicalHeaderList(e){return Object.keys(e).sort().join(";")}},JKe=class extends iSe{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",new zKe)}async presign(r,n={}){let{signingDate:o=new Date,expiresIn:i=3600,unsignableHeaders:a,unhoistableHeaders:s,signableHeaders:u,hoistableHeaders:l,signingRegion:c,signingService:d}=n,f=await this.credentialProvider();this.validateResolvedCredentials(f);let p=c??await this.regionProvider(),{longDate:m,shortDate:h}=this.formatDate(o);if(i>HZt)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");let y=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);let b=BKe(g,a,u);return g.query[NZt]=this.getCanonicalHeaderList(b),g.query[KKe]=await this.getSignature(m,y,this.getSigningKey(f,p,h,d),this.createCanonicalRequest(g,b,await nSe(r,this.sha256))),g}async sign(r,n){return typeof r=="string"?this.signString(r,n):r.headers&&r.payload?this.signEvent(r,n):r.message?this.signMessage(r,n):this.signRequest(r,n)}async signEvent({headers:r,payload:n},{signingDate:o=new Date,priorSignature:i,signingRegion:a,signingService:s}){let u=a??await this.regionProvider(),{shortDate:l,longDate:c}=this.formatDate(o),d=rSe(l,u,s??this.service),f=await nSe({headers:{},body:n},this.sha256),p=new this.sha256;p.update(r);let m=bF.toHex(await p.digest()),h=[BZt,c,d,i,m,f].join(`
`);return this.signString(h,{signingDate:o,signingRegion:u,signingService:s})}async signMessage(r,{signingDate:n=new Date,signingRegion:o,signingService:i}){return this.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}))}async signString(r,{signingDate:n=new Date,signingRegion:o,signingService:i}={}){let a=await this.credentialProvider();this.validateResolvedCredentials(a);let s=o??await this.regionProvider(),{shortDate:u}=this.formatDate(n),l=new this.sha256(await this.getSigningKey(a,s,u,i));return l.update(R4.toUint8Array(r)),bF.toHex(await l.digest())}async signRequest(r,{signingDate:n=new Date,signableHeaders:o,unsignableHeaders:i,signingRegion:a,signingService:s}={}){let u=await this.credentialProvider();this.validateResolvedCredentials(u);let l=a??await this.regionProvider(),c=HKe(r),{longDate:d,shortDate:f}=this.formatDate(n),p=rSe(f,l,s??this.service);c.headers[ZKe]=d,u.sessionToken&&(c.headers[FZt]=u.sessionToken);let m=await nSe(c,this.sha256);!WZt(oSe,c.headers)&&this.applyChecksum&&(c.headers[oSe]=m);let h=BKe(c,i,o),y=await this.getSignature(d,p,this.getSigningKey(u,l,f,s),this.createCanonicalRequest(c,h,m));return c.headers[XKe]=`${eSe} Credential=${u.accessKeyId}/${p}, SignedHeaders=${this.getCanonicalHeaderList(h)}, Signature=${y}`,c}async getSignature(r,n,o,i){let a=await this.createStringToSign(r,n,i,eSe),s=new this.sha256(await o);return s.update(R4.toUint8Array(a)),bF.toHex(await s.digest())}getSigningKey(r,n,o,i){return JZt(this.sha256,r,o,n,i||this.service)}},GIn={SignatureV4a:null};li.ALGORITHM_IDENTIFIER=eSe;li.ALGORITHM_IDENTIFIER_V4A=VIn;li.ALGORITHM_QUERY_PARAM=RZt;li.ALWAYS_UNSIGNABLE_HEADERS=kZt;li.AMZ_DATE_HEADER=ZKe;li.AMZ_DATE_QUERY_PARAM=WKe;li.AUTH_HEADER=XKe;li.CREDENTIAL_QUERY_PARAM=AZt;li.DATE_HEADER=DZt;li.EVENT_ALGORITHM_IDENTIFIER=BZt;li.EXPIRES_QUERY_PARAM=jZt;li.GENERATED_HEADERS=$Zt;li.HOST_HEADER=BIn;li.KEY_TYPE_IDENTIFIER=YKe;li.MAX_CACHE_SIZE=VZt;li.MAX_PRESIGNED_TTL=HZt;li.PROXY_HEADER_PATTERN=qZt;li.REGION_SET_PARAM=UIn;li.SEC_HEADER_PATTERN=UZt;li.SHA256_HEADER=oSe;li.SIGNATURE_HEADER=LZt;li.SIGNATURE_QUERY_PARAM=KKe;li.SIGNED_HEADERS_QUERY_PARAM=NZt;li.SignatureV4=JKe;li.SignatureV4Base=iSe;li.TOKEN_HEADER=FZt;li.TOKEN_QUERY_PARAM=GKe;li.UNSIGNABLE_PATTERNS=zIn;li.UNSIGNED_PAYLOAD=zZt;li.clearCredentialCache=HIn;li.createScope=rSe;li.getCanonicalHeaders=BKe;li.getCanonicalQuery=GZt;li.getPayloadHash=nSe;li.getSigningKey=JZt;li.hasHeader=WZt;li.moveHeadersToQuery=KZt;li.prepareRequest=HKe;li.signatureV4aContainer=GIn});var cc=S((ema,ZZt)=>{"use strict";ZZt.exports={ArrayIsArray(t){return Array.isArray(t)},ArrayPrototypeIncludes(t,e){return t.includes(e)},ArrayPrototypeIndexOf(t,e){return t.indexOf(e)},ArrayPrototypeJoin(t,e){return t.join(e)},ArrayPrototypeMap(t,e){return t.map(e)},ArrayPrototypePop(t,e){return t.pop(e)},ArrayPrototypePush(t,e){return t.push(e)},ArrayPrototypeSlice(t,e,r){return t.slice(e,r)},Error,FunctionPrototypeCall(t,e,...r){return t.call(e,...r)},FunctionPrototypeSymbolHasInstance(t,e){return Function.prototype[Symbol.hasInstance].call(t,e)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(t,e){return Object.defineProperties(t,e)},ObjectDefineProperty(t,e,r){return Object.defineProperty(t,e,r)},ObjectGetOwnPropertyDescriptor(t,e){return Object.getOwnPropertyDescriptor(t,e)},ObjectKeys(t){return Object.keys(t)},ObjectSetPrototypeOf(t,e){return Object.setPrototypeOf(t,e)},Promise,PromisePrototypeCatch(t,e){return t.catch(e)},PromisePrototypeThen(t,e,r){return t.then(e,r)},PromiseReject(t){return Promise.reject(t)},PromiseResolve(t){return Promise.resolve(t)},ReflectApply:Reflect.apply,RegExpPrototypeTest(t,e){return t.test(e)},SafeSet:Set,String,StringPrototypeSlice(t,e,r){return t.slice(e,r)},StringPrototype
`;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)=>{"use strict";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="The operation was aborted",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' must be a string"),Array.isArray(e)||(e=[e]);let n="The ";t.endsWith(" argument")?n+=`${t} `:n+=`"${t}" ${t.includes(".")?"property":"argument"} `,n+="must be ";let o=[],i=[],a=[];for(let u of e)A4(typeof u=="string","All expected entries have to be of type string"),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>
`)>=0)return!1;return!0}function KDn(t,e){var r;if(t.indent===" ")r=" ";else if(typeof t.indent=="number"&&t.indent>0)r=cT.call(Array(t.indent+1)," ");else return null;return{base:r,prev:cT.call(Array(e+1),r)}}function SGe(t,e){if(t.length===0)return"";var r=`
`+e.prev+e.base;return r+cT.call(t,","+r)+`
`+e.prev}function qSe(t,e){var r=wGe(t),n=[];if(r){n.length=t.length;for(var o=0;o<t.length;o++)n[o]=e1(t,o)?e(t[o],t):""}var i=typeof gGe=="function"?gGe(t):[],a;if(F5){a={};for(var s=0;s<i.length;s++)a["$"+i[s]]=i[s]}for(var u in t)e1(t,u)&&(r&&String(Number(u))===u&&u<t.length||F5&&a["$"+u]instanceof Symbol||(Ctr.call(/[^\w$]/,u)?n.push(e(u,t)+": "+e(t[u],t)):n.push(u+": "+e(t[u],t))));if(typeof gGe=="function")for(var l=0;l<i.length;l++)xtr.call(t,i[l])&&n.push("["+e(i[l])+"]: "+e(t[i[l]],t));return n}});var Atr=S((Dma,Rtr)=>{"use strict";var GDn=ine(),XDn=H4(),zSe=function(t,e,r){for(var n=t,o;(o=n.next)!=null;n=o)if(o.key===e)return n.next=o.next,r||(o.next=t.next,t.next=o),o},ZDn=function(t,e){if(t){var r=zSe(t,e);return r&&r.value}},YDn=function(t,e,r){var n=zSe(t,e);n?n.value=r:t.next={key:e,next:t.next,value:r}},QDn=function(t,e){return t?!!zSe(t,e):!1},e$n=function(t,e){if(t)return zSe(t,e,!0)};Rtr.exports=function(){var e,r={assert:function(n){if(!r.has(n))throw new XDn("Side channel does not contain "+GDn(n))},delete:function(n){var o=e&&e.next,i=e$n(e,n);return i&&o&&o===i&&(e=void 0),!!i},get:function(n){return ZDn(e,n)},has:function(n){return QDn(e,n)},set:function(n,o){e||(e={next:void 0}),YDn(e,n,o)}};return r}});var TGe=S(($ma,Ntr)=>{"use strict";Ntr.exports=Object});var Dtr=S((Lma,jtr)=>{"use strict";jtr.exports=Error});var Ltr=S((Fma,$tr)=>{"use strict";$tr.exports=EvalError});var ktr=S((kma,Ftr)=>{"use strict";Ftr.exports=RangeError});var Utr=S((qma,qtr)=>{"use strict";qtr.exports=ReferenceError});var ztr=S((Uma,Btr)=>{"use strict";Btr.exports=SyntaxError});var Htr=S((Bma,Vtr)=>{"use strict";Vtr.exports=URIError});var Wtr=S((zma,Jtr)=>{"use strict";Jtr.exports=Math.abs});var Gtr=S((Vma,Ktr)=>{"use strict";Ktr.exports=Math.floor});var Ztr=S((Hma,Xtr)=>{"use strict";Xtr.exports=Math.max});var Qtr=S((Jma,Ytr)=>{"use strict";Ytr.exports=Math.min});var trr=S((Wma,err)=>{"use strict";err.exports=Math.pow});var nrr=S((Kma,rrr)=>{"use strict";rrr.exports=Math.round});var irr=S((Gma,orr)=>{"use strict";orr.exports=Number.isNaN||function(e){return e!==e}});var srr=S((Xma,arr)=>{"use strict";var t$n=irr();arr.exports=function(e){return t$n(e)||e===0?e:e<0?-1:1}});var lrr=S((Zma,urr)=>{"use strict";urr.exports=Object.getOwnPropertyDescriptor});var EGe=S((Yma,crr)=>{"use strict";var VSe=lrr();if(VSe)try{VSe([],"length")}catch{VSe=null}crr.exports=VSe});var frr=S((Qma,drr)=>{"use strict";var HSe=Object.defineProperty||!1;if(HSe)try{HSe({},"a",{value:1})}catch{HSe=!1}drr.exports=HSe});var mrr=S((eha,prr)=>{"use strict";prr.exports=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},r=Symbol("test"),n=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var o=42;e[r]=o;for(var i in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var a=Object.getOwnPropertySymbols(e);if(a.length!==1||a[0]!==r||!Object.prototype.propertyIsEnumerable.call(e,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var s=Object.getOwnPropertyDescriptor(e,r);if(s.value!==o||s.enumerable!==!0)return!1}return!0}});var yrr=S((tha,grr)=>{"use strict";var hrr=typeof Symbol<"u"&&Symbol,r$n=mrr();grr.exports=function(){return typeof hrr!="function"||typeof Symbol!="function"||typeof hrr("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:r$n()}});var PGe=S((rha,brr)=>{"use strict";brr.exports=typeof Reflect<"u"&&Reflect.getPrototypeOf||null});var MGe=S((nha,_rr)=>{"use strict";var n$n=TGe();_rr.exports=n$n.getPrototypeOf||null});var Srr=S((oha,wrr)=>{"use strict";var o$n="Function.prototype.bind called on incompatible ",i$n=Object.prototype.toString,a$n=Math.max,s$n="[object Function]",vrr=function(e,r){for(var n=[],o=0;o<e.length;o+=1)n[o]=e[o];for(var i=0;i<r.length;i+=1)n[i+e.length]=r[i];return n},u$n=function(e,r){
`,this.streamTerminator=n.streamTerminator):this.messageTerminator=n.messageTerminator,o?.addEventListener("abort",()=>this.controller.abort())}iterMessages(){return Knr(this,arguments,function*(){var r,n,o,i;this.controller.signal;let a=Gnr(this.stream),s="",u=!1;try{for(var l=!0,c=Wnr(a),d;d=yield xC(c.next()),r=d.done,!r;l=!0){i=d.value,l=!1;let f=i;s+=this.decodeChunk(f);let p;for(;(p=s.indexOf(this.messageTerminator))>=0;){let m=s.slice(0,p+1);if(s=s.slice(p+this.messageTerminator.length),!m.trim())continue;if(!u&&this.prefix!=null){let y=m.indexOf(this.prefix);if(y===-1)continue;u=!0,m=m.slice(y+this.prefix.length)}if(this.streamTerminator!=null&&m.includes(this.streamTerminator))return yield xC(void 0);let h=yield xC(this.parse(JSON.parse(m)));yield yield xC(h),u=!1}}}catch(f){n={error:f}}finally{try{!l&&!r&&(o=c.return)&&(yield xC(o.call(c)))}finally{if(n)throw n.error}}})}[Symbol.asyncIterator](){return Knr(this,arguments,function*(){var r,n,o,i;try{for(var a=!0,s=Wnr(this.iterMessages()),u;u=yield xC(s.next()),r=u.done,!r;a=!0)i=u.value,a=!1,yield yield xC(i)}catch(l){n={error:l}}finally{try{!a&&!r&&(o=s.return)&&(yield xC(o.call(s)))}finally{if(n)throw n.error}}})}decodeChunk(e){let r="";if(typeof TextDecoder<"u"){let n=new TextDecoder("utf8");r+=n.decode(e)}else HFn.RUNTIME.type==="node"&&typeof e<"u"&&(r+=Buffer.isBuffer(e)?e:Buffer.from(e));return r}};Fv.Stream=r9e;function Gnr(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{next(){return Jnr(this,void 0,void 0,function*(){try{let r=yield e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}})},return(){return Jnr(this,void 0,void 0,function*(){let r=e.cancel();return e.releaseLock(),yield r,{done:!0,value:void 0}})},[Symbol.asyncIterator](){return this}}}});var Xnr=S(d0e=>{"use strict";Object.defineProperty(d0e,"__esModule",{value:!0});d0e.Stream=void 0;var WFn=n9e();Object.defineProperty(d0e,"Stream",{enumerable:!0,get:function(){return WFn.Stream}})});var Znr=S(yne=>{"use strict";var KFn=yne&&yne.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(yne,"__esModule",{value:!0});yne.encodeAsFormParameter=XFn;var GFn=KFn(HGe());function XFn(t){let r=GFn.default.stringify(t,{encode:!1}).split("&").map(n=>{let[o,i]=n.split("=");return[o,i]});return Object.fromEntries(r)}});var eor=S((Kha,Qnr)=>{"use strict";var o9e=Object.defineProperty,ZFn=Object.getOwnPropertyDescriptor,YFn=Object.getOwnPropertyNames,QFn=Object.prototype.hasOwnProperty,ekn=(t,e)=>{for(var r in e)o9e(t,r,{get:e[r],enumerable:!0})},tkn=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of YFn(e))!QFn.call(t,o)&&o!==r&&o9e(t,o,{get:()=>e[o],enumerable:!(n=ZFn(e,o))||n.enumerable});return t},rkn=t=>tkn(o9e({},"__esModule",{value:!0}),t),Ynr={};ekn(Ynr,{Blob:()=>ikn,File:()=>akn,FormData:()=>okn});Qnr.exports=rkn(Ynr);var nkn=function(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:window}(),{FormData:okn,Blob:ikn,File:akn}=nkn});var mor=S((Gha,por)=>{"use strict";var s9e=Object.defineProperty,skn=Object.getOwnPropertyDescriptor,ukn=Object.getOwnPropertyNames,lkn=Object.prototype.hasOwnProperty,ckn=(t,e)=>{for(var r in e)s9e(t,r,{get:e[r],enumerable:!0})},dkn=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ukn(e))!lkn.call(t,o)&&o!==r&&s9e(t,o,{get:()=>e[o],enumerable:!(n=skn(e,o))||n.enumerable});return t},fkn=t=>dkn(s9e({},"__esModule",{value:!0}),t),u9e=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},Pc=(t,e,r)=>(u9e(t,e,"read from private field"),r?r.call(t):e.get(t)),pT=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},bne=(t,e,r,n)=>(u9e(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),i9e=(t,e,r)=>(u9e(t,e,"access private method"),r),sor={};ckn(sor,{FormDataEncoder:()=>vkn,isFile:()=>Z4,isFormData:()=>cor});por.exports=fkn(sor);var t1=t=>typeof t=="function",pkn=t=>t1(t[Symbol.asyncIterator]),tor=65536;function*uor(t){if(t.byteLength<=tor){yield t;return}let e=
`||e===`
`&&n[r-1]!=="\r"?`\r
`:e),ykn=t=>Object.prototype.toString.call(t).slice(8,-1).toLowerCase();function oor(t){if(ykn(t)!=="object")return!1;let e=Object.getPrototypeOf(t);return e==null?!0:(e.constructor&&e.constructor.toString())===Object.toString()}function ior(t,e){if(typeof e=="string"){for(let[r,n]of Object.entries(t))if(e.toLowerCase()===r.toLowerCase())return n}}var bkn=t=>new Proxy(t,{get:(e,r)=>ior(e,r),has:(e,r)=>ior(e,r)!==void 0}),cor=t=>!!(t&&t1(t.constructor)&&t[Symbol.toStringTag]==="FormData"&&t1(t.append)&&t1(t.getAll)&&t1(t.entries)&&t1(t[Symbol.iterator])),aor=t=>String(t).replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/"/g,"%22"),Z4=t=>!!(t&&typeof t=="object"&&t1(t.constructor)&&t[Symbol.toStringTag]==="File"&&t1(t.stream)&&t.name!=null),_kn={enableAdditionalHeaders:!1},f0e={writable:!1,configurable:!1},EF,_ne,p0e,vne,X4,wne,Sne,m0e,h0e,l9e,a9e,dor,vkn=class{constructor(t,e,r){if(pT(this,h0e),pT(this,a9e),pT(this,EF,`\r
`),pT(this,_ne,void 0),pT(this,p0e,void 0),pT(this,vne,"-".repeat(2)),pT(this,X4,new TextEncoder),pT(this,wne,void 0),pT(this,Sne,void 0),pT(this,m0e,void 0),!cor(t))throw new TypeError("Expected first argument to be a FormData instance.");let n;if(oor(e)?r=e:n=e,n||(n=gkn()),typeof n!="string")throw new TypeError("Expected boundary argument to be a string.");if(r&&!oor(r))throw new TypeError("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)}`));let o={"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]of Pc(this,Sne)){let r=Z4(e)?e:Pc(this,X4).encode(lor(e));yield i9e(this,h0e,l9e).call(this,t,r),yield r,yield Pc(this,_ne)}yield Pc(this,wne)}async*encode(){for(let t of this.values())Z4(t)?yield*hkn(t.stream()):yield*uor(t)}[Symbol.iterator](){return this.values()}[Symbol.asyncIterator](){return this.encode()}};EF=new WeakMap;_ne=new WeakMap;p0e=new WeakMap;vne=new WeakMap;X4=new WeakMap;wne=new WeakMap;Sne=new WeakMap;m0e=new WeakMap;h0e=new WeakSet;l9e=function(t,e){let r="";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){let n=Z4(e)?e.size:e.byteLength;n!=null&&!isNaN(n)&&(r+=`${Pc(this,EF)}Content-Length: ${n}`)}return Pc(this,X4).encode(`${r}${Pc(this,EF).repeat(2)}`)};a9e=new WeakSet;dor=function(){let t=0;for(let[e,r]of Pc(this,Sne)){let n=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)}return String(t+Pc(this,wne).byteLength)}});var gor=S((Zha,hor)=>{"use strict";hor.exports=typeof self=="object"?self.FormData:window.FormData});var yor=S(dg=>{"use strict";var wkn=dg&&dg.__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]}),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(){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"&&wkn(r,e,n[o]);return Skn(r,e),r}}(),PF=dg&&dg.__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())})};Object.defineProperty(dg,"__esModule",{value:!0});dg.WebFormData=dg.Node16FormData=dg.Node18FormData=void 0;dg.newFormData=Ckn;var g0e=V5();function c9e(t){return typeof t=="object"&&t!=null&&"name"in t}function Ckn(){return PF(this,void 0,void 0,function*(){let t;return g0e.RUNTIME.type==="node"&&g0e.RUNTIME.parsedVersion!=null&&g0e.RUNTIME.parsedVersion>=18?t=new y0e:g0e.RUNTIME.type==="node"?t=new b0e:t=new _0e,yield t.setup(),t})}var y0e=class{setup(){return PF(this,void 0,void 0,function*(){this.fd=new(yield Promise.resolve().then(()=>Q5(eor()))).FormData})}append(e
`)),{ok:!0,value:e}):n}}});var m9e=S(p9e=>{"use strict";Object.defineProperty(p9e,"__esModule",{value:!0});p9e.stringifyValidationError=Ikn;function Ikn(t){return t.path.length===0?t.message:`${t.path.join(" -> ")}: ${t.message}`}});var g9e=S(w0e=>{"use strict";Object.defineProperty(w0e,"__esModule",{value:!0});w0e.JsonError=void 0;var Rkn=m9e(),h9e=class t extends Error{constructor(e){super(e.map(Rkn.stringifyValidationError).join("; ")),this.errors=e,Object.setPrototypeOf(this,t.prototype)}};w0e.JsonError=h9e});var b9e=S(S0e=>{"use strict";Object.defineProperty(S0e,"__esModule",{value:!0});S0e.ParseError=void 0;var Akn=m9e(),y9e=class t extends Error{constructor(e){super(e.map(Akn.stringifyValidationError).join("; ")),this.errors=e,Object.setPrototypeOf(this,t.prototype)}};S0e.ParseError=y9e});var xor=S(Y4=>{"use strict";Object.defineProperty(Y4,"__esModule",{value:!0});Y4.getSchemaUtils=Cne;Y4.nullable=vor;Y4.optional=wor;Y4.optionalNullable=Sor;Y4.transform=Cor;var _9e=fh(),Nkn=g9e(),jkn=b9e();function Cne(t){return{nullable:()=>vor(t),optional:()=>wor(t),optionalNullable:()=>Sor(t),transform:e=>Cor(t,e),parseOrThrow:(e,r)=>{let n=t.parse(e,r);if(n.ok)return n.value;throw new jkn.ParseError(n.errors)},jsonOrThrow:(e,r)=>{let n=t.json(e,r);if(n.ok)return n.value;throw new Nkn.JsonError(n.errors)}}}function vor(t){let e={parse:(r,n)=>r==null?{ok:!0,value:null}:t.parse(r,n),json:(r,n)=>r==null?{ok:!0,value:null}:t.json(r,n),getType:()=>_9e.SchemaType.NULLABLE};return Object.assign(Object.assign({},e),Cne(e))}function wor(t){let e={parse:(r,n)=>r==null?{ok:!0,value:void 0}:t.parse(r,n),json:(r,n)=>n?.omitUndefined&&r===void 0?{ok:!0,value:void 0}:r==null?{ok:!0,value:null}:t.json(r,n),getType:()=>_9e.SchemaType.OPTIONAL};return Object.assign(Object.assign({},e),Cne(e))}function Sor(t){let e={parse:(r,n)=>r===void 0?{ok:!0,value:void 0}:r===null?{ok:!0,value:null}:t.parse(r,n),json:(r,n)=>r===void 0?{ok:!0,value:void 0}:r===null?{ok:!0,value:null}:t.json(r,n),getType:()=>_9e.SchemaType.OPTIONAL_NULLABLE};return Object.assign(Object.assign({},e),Cne(e))}function Cor(t,e){let r={parse:(n,o)=>{let i=t.parse(n,o);return i.ok?{ok:!0,value:e.transform(i.value)}:i},json:(n,o)=>{let i=e.untransform(n);return t.json(i,o)},getType:()=>t.getType()};return Object.assign(Object.assign({},r),Cne(r))}});var p_=S(CS=>{"use strict";Object.defineProperty(CS,"__esModule",{value:!0});CS.ParseError=CS.JsonError=CS.transform=CS.optional=CS.getSchemaUtils=void 0;var v9e=xor();Object.defineProperty(CS,"getSchemaUtils",{enumerable:!0,get:function(){return v9e.getSchemaUtils}});Object.defineProperty(CS,"optional",{enumerable:!0,get:function(){return v9e.optional}});Object.defineProperty(CS,"transform",{enumerable:!0,get:function(){return v9e.transform}});var Dkn=g9e();Object.defineProperty(CS,"JsonError",{enumerable:!0,get:function(){return Dkn.JsonError}});var $kn=b9e();Object.defineProperty(CS,"ParseError",{enumerable:!0,get:function(){return $kn.ParseError}})});var Tor=S(w9e=>{"use strict";Object.defineProperty(w9e,"__esModule",{value:!0});w9e.bigint=qkn;var Lkn=fh(),Oor=gb(),Fkn=mT(),kkn=p_();function qkn(){let t={parse:(e,{breadcrumbsPrefix:r=[]}={})=>typeof e=="bigint"?{ok:!0,value:e}:typeof e=="number"?{ok:!0,value:BigInt(e)}:{ok:!1,errors:[{path:r,message:(0,Oor.getErrorMessageForIncorrectType)(e,"bigint | number")}]},json:(e,{breadcrumbsPrefix:r=[]}={})=>typeof e!="bigint"?{ok:!1,errors:[{path:r,message:(0,Oor.getErrorMessageForIncorrectType)(e,"bigint")}]}:{ok:!0,value:e},getType:()=>Lkn.SchemaType.BIGINT};return Object.assign(Object.assign({},(0,Fkn.maybeSkipValidation)(t)),(0,kkn.getSchemaUtils)(t))}});var Eor=S(C0e=>{"use strict";Object.defineProperty(C0e,"__esModule",{value:!0});C0e.bigint=void 0;var Ukn=Tor();Object.defineProperty(C0e,"bigint",{enumerable:!0,get:function(){return Ukn.bigint}})});var Por=S(C9e=>{"use strict";Object.defineProperty(C9e,"__esModule",{value:!0});C9e.date=Jkn;var Bkn=fh(),S9e=gb(),zkn=mT(),Vkn=p_(),Hkn=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(0
`);o.enqueue(s)}catch(i){o.error(i)}})},cancel(){return Ine(this,void 0,void 0,function*(){var o;yield(o=r.return)===null||o===void 0?void 0:o.call(r)})}})}};pg.StreamUtils=Q9e;function wir(t,e){return Ane(this,arguments,function*(){var n,o,i,a;if(!t.body)throw e?.abort(),new oK.CohereError({message:"Attempted to iterate over a response with no body"});let s=new e7e,u=new MF,l=t7e(t.body);try{for(var c=!0,d=Rne(JUn(l)),f;f=yield Ll(d.next()),n=f.done,!n;c=!0){a=f.value,c=!1;let p=a;for(let m of u.decode(p)){let h=s.decode(m);h&&(yield yield Ll(h))}}}catch(p){o={error:p}}finally{try{!c&&!n&&(i=d.return)&&(yield Ll(i.call(d)))}finally{if(o)throw o.error}}for(let p of u.flush()){let m=s.decode(p);m&&(yield yield Ll(m))}})}function JUn(t){return Ane(this,arguments,function*(){var r,n,o,i;let a=new Uint8Array;try{for(var s=!0,u=Rne(t),l;l=yield Ll(u.next()),r=l.done,!r;s=!0){i=l.value,s=!1;let c=i;if(c==null)continue;let d=c instanceof ArrayBuffer?new Uint8Array(c):typeof c=="string"?new TextEncoder().encode(c):c,f=new Uint8Array(a.length+d.length);f.set(a),f.set(d,a.length),a=f;let p;for(;(p=WUn(a))!==-1;)yield yield Ll(a.slice(0,p)),a=a.slice(p)}}catch(c){n={error:c}}finally{try{!s&&!r&&(o=u.return)&&(yield Ll(o.call(u)))}finally{if(n)throw n.error}}a.length>0&&(yield yield Ll(a))})}function WUn(t){for(let n=0;n<t.length-2;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)return n+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)return n+4}return-1}var e7e=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=GUn(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},MF=class t{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){let r=this.decodeText(e);if(this.trailingCR&&(r="\r"+r,this.trailingCR=!1),r.endsWith("\r")&&(this.trailingCR=!0,r=r.slice(0,-1)),!r)return[];let n=t.NEWLINE_CHARS.has(r[r.length-1]||""),o=r.split(t.NEWLINE_REGEXP);return n&&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){var r;if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new oK.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(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return(r=this.textDecoder)!==null&&r!==void 0||(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new oK.CohereError({message:`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`})}throw new oK.CohereError({message:"Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error."})}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}};pg.LineDecoder=MF;MF.NEWLINE_CHARS=new Set([`
`,"\r"]);MF.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function KUn(t){let e=new MF,r=[];for(let n of t)r.push(...e.decode(n));return r}function GUn(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}function t7e(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{next(){return Ine(this,void 0,void 0,function*(){try{let r=yield e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}})},return(){return Ine(this,void 0,void 0,function*(){let r=e.cancel();return e.releaseLock(),yield r,{done:!0,value:void 0}})},[Symbol.asyncIterator](){return this}}}});var jne=S(hT=>{"use strict";var XUn=hT&&hT.__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]}),ZUn=hT&&hT.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),YUn=hT&&hT.__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"&&XUn(r,e,n[o]);return ZUn(r,e),r}}();Object.defineProperty(hT,"__esModule",{value:!0});hT.Document=void 0;var Nne=YUn(te());hT.Document=Nne.serialization.object({data:Nne.serialization.record(Nne.serialization.string(),Nne.serialization.unknown()),id:Nne.serialization.string().optional()})});var r7e=S(gT=>{"use strict";var QUn=gT&&gT.__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]}),eBn=gT&&gT.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),tBn=gT&&gT.__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"&&QUn(r,e,n[o]);return eBn(r,e),r}}();Object.defineProperty(gT,"__esModule",{value:!0});gT.V2ChatStreamRequestDocumentsItem=void 0;var Cir=tBn(te()),rBn=jne();gT.V2ChatStreamRequestDocumentsItem=Cir.serialization.undiscriminatedUnion([Cir.serialization.string(),rBn.Document])});var n7e=S(yT=>{"use strict";var nBn=yT&&yT.__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]}),oBn=yT&&yT.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),iBn=yT&&yT.__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"&&nBn(r,e,n[o]);return oBn(r,e),r}}();Object.defineProperty(yT,"__esModule",{value:!0});yT.V2ChatStreamRequestSafetyMode=void 0;var aBn=iBn(te());yT.V2ChatStreamRequestSafetyMode=aBn.serialization.enum_(["CONTEXTUAL","STRICT","OFF"])});var o7e=S(bT=>{"use strict";var sBn=bT&&bT.__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(
`)}}}}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){case 400:throw new Re.BadRequestError(u.error.body,u.rawResponse);case 401:throw new Re.UnauthorizedError(u.error.body,u.rawResponse);case 403:throw new Re.ForbiddenError(u.error.body,u.rawResponse);case 404:throw new Re.NotFoundError(u.error.body,u.rawResponse);case 422:throw new Re.UnprocessableEntityError(u.error.body,u.rawResponse);case 429:throw new Re.TooManyRequestsError(u.error.body,u.rawResponse);case 498:throw new Re.InvalidTokenError(u.error.body,u.rawResponse);case 499:throw new Re.ClientClosedRequestError(u.error.body,u.rawResponse);case 500:throw new Re.InternalServerError(u.error.body,u.rawResponse);case 501:throw new Re.NotImplementedError(u.error.body,u.rawResponse);case 503:throw new Re.ServiceUnavailableError(u.error.body,u.rawResponse);case 504:throw new Re.GatewayTimeoutError(u.error.body,u.rawResponse);default:throw new Mo.CohereError({statusCode:u.error.statusCode,body:u.error.body,rawResponse:u.rawResponse})}switch(u.error.reason){case"non-json":throw new Mo.CohereError({statusCode:u.error.statusCode,body:u.error.rawBody,rawResponse:u.rawResponse});case"timeout":throw new Mo.CohereTimeoutError("Timeout exceeded when calling POST /v1/chat.");case"unknown":throw new Mo.CohereError({message:u.error.errorMessage,rawResponse:u.rawResponse})}})}chat(e,r){return ct.HttpResponsePromise.fromPromise(this.__chat(e,r))}__chat(e,r){return C_(this,void 0,void 0,function*(){var n,o,i;let{accepts:a}=e,s=Xsr(e,["accepts"]),u=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/chat"),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,Accepts:a??void 0},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){case 400:throw new Re.BadRequestError(u.error.body,u.rawResponse);case 401:throw new Re.UnauthorizedError(u.error.body,u.rawResponse);case 403:throw new Re.ForbiddenError(u.error.body,u.rawResponse);case 404:throw new Re.NotFoundError(u.error.body,u.rawResponse);case 422:throw new Re.UnprocessableEntityError(u.error.body,u.rawResponse);case 429:throw new Re.TooManyRequestsError(u.error.body,u.rawResponse);case 498:throw new Re.InvalidTokenError(u.error.body,u.rawResponse);case 499:throw new Re.ClientClosedRequestError(u.error.body,u.rawResponse);case 500:throw new Re.InternalServerError(u.error.body,u.rawResponse);case 501:throw new Re.NotImplementedError(u.error.body,u.rawResponse);case 503:throw new Re.ServiceUnavailableError(u.error.body,u.rawResponse);case 504:throw new Re.GatewayTimeoutError(u.error.body,u.rawResponse);default:throw new Mo.CohereError({statusCode:u.error.statusCode,body:u.error.body,rawResponse:u.rawResponse})}switch(u.error.reason){case"non-json":throw new Mo.CohereError({statusCode:u.error.statusCode,body:u.error.rawBody,rawResponse:u.rawResponse});case"timeout":throw new Mo.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("Timeout exceeded when calling POST /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("Timeout exceeded when calling POST /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+=` due to ${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+=`Candidate was blocked due to ${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(`Error parsing JSON response: "${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){var o=n.split(":"),i=o.shift().trim();if(i){var a=o.join(":").trim();try{e.append(i,a)}catch(s){console.warn("Response "+s.message)}}}),e}function eR(t,e){if(!(this instanceof eR))throw new TypeError('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===void 0?200:e.status,this.status<200||this.status>599)throw new RangeError("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===void 0?"":""+e.statusText,this.headers=new Tm(e.headers),this.url=e.url||"",this._initBody(t)}function Alr(t,e){return new Promise(function(r,n){var o=new E2(t,e);if(o.signal&&o.signal.aborted)return n(new T2("Aborted","AbortError"));var i=new XMLHttpRequest;function a(){i.abort()}i.onload=function(){var l={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"in i?i.responseURL:l.headers.get("X-Request-URL");var c="response"in i?i.response:i.responseText;setTimeout(function(){r(new eR(c,l))},0)},i.onerror=function(){setTimeout(function(){n(new TypeError("Network request failed"))},0)},i.ontimeout=function(){setTimeout(function(){n(new TypeError("Network request timed out"))},0)},i.onabort=function(){setTimeout(function(){n(new T2("Aborted","AbortError"))},0)};function s(l){try{return l===""&&Sg.location.href?Sg.location.href:l}catch{return l}}if(i.open(o.method,s(o.url),!0),o.credentials==="include"?i.withCredentials=!0:o.credentials==="omit"&&(i.withCredentials=!1),"responseType"in i&&(bb.blob?i.responseType="blob":bb.arrayBuffer&&(i.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof Tm||Sg.Headers&&e.headers instanceof Sg.Headers)){var u=[];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)})}else o.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(typeof o._bodyInit>"u"?null:o._bodyInit)})}var Sg,bb,Elr,Mlr,zno,Wno,T2,Nlr=v(()=>{Sg=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof window<"u"&&window||{},bb={searchParams:"URLSearchParams"in Sg,iterable:"Symbol"in Sg&&"iterator"in Symbol,blob:"FileReader"in Sg&&"Blob"in Sg&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in Sg,arrayBuffer:"ArrayBuffer"in Sg};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){return t&&Elr.indexOf(Object.prototype.toString.call(t))>-1});Tm.prototype.append=function(t,e){t=DK(t),e=jQe(e);var r=this.map[t];this.map[t]=r?r+", "+e:e};Tm.prototype.delete=function(t){delete this.map[DK(t)]};Tm.prototype.get=function(t){return t=DK(t),this.has(t)?this.map[t]:null};Tm.prototype.has=function(t){return this.map.hasOwnProperty(DK(t))};Tm.prototype.set=function(t,e){this.map[DK(t)]=jQe(e)};Tm.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)};Tm.prototype.keys=function(){var t=[];return this.forEach(function(e,r){t.push(r)}),DQe(t)};Tm.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),DQe(t)};Tm.prototype.entries=function(){var t=[];return this.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(){return new E2(this,{body:this._bodyInit})};Rlr.call(E2.prototype);Rlr.call(eR.pro
`);r=a.pop()??"";for(let s of a)try{yield JSON.parse(s)}catch{console.warn("invalid json: ",s)}}for(let o of r.split(`
`).filter(i=>i!==""))try{yield JSON.parse(o)}catch{console.warn("invalid json: ",o)}},too=t=>{if(!t)return $lr;let e=t.includes("://");t.startsWith(":")&&(t=`http://127.0.0.1${t}`,e=!0),e||(t=`http://${t}`);let r=new URL(t),n=r.port;n||(e?n=r.protocol==="https:"?"443":"80":n=Dlr);let o="";r.username&&(o=r.username,r.password&&(o+=`:${r.password}`),o+="@");let i=`${r.protocol}//${o}${r.hostname}:${n}${r.pathname}`;return i.endsWith("/")&&(i=i.slice(0,-1)),i},roo=Object.defineProperty,noo=(t,e,r)=>e in t?roo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,LQe=(t,e,r)=>(noo(t,typeof e!="symbol"?e+"":e,r),r),LK=class{constructor(e){LQe(this,"config"),LQe(this,"fetch"),LQe(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e?.headers},e?.proxy||(this.config.host=too(e?.host??$lr)),this.fetch=e?.fetch??fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,r){r.stream=r.stream??!1;let n=`${this.config.host}/api/${e}`;if(r.stream){let i=new AbortController,a=await $K(this.fetch,n,r,{signal:i.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");let s=eoo(a.body),u=new kQe(i,s,()=>{let l=this.ongoingStreamedRequests.indexOf(u);l>-1&&this.ongoingStreamedRequests.splice(l,1)});return this.ongoingStreamedRequests.push(u),u}return await(await $K(this.fetch,n,r,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!="string"){let r=new Uint8Array(e),n="",o=r.byteLength;for(let i=0;i<o;i++)n+=String.fromCharCode(r[i]);return btoa(n)}return e}async generate(e){return e.images&&(e.images=await Promise.all(e.images.map(this.encodeImage.bind(this)))),this.processStreamableRequest("generate",e)}async chat(e){if(e.messages)for(let r of e.messages)r.images&&(r.images=await Promise.all(r.images.map(this.encodeImage.bind(this))));return this.processStreamableRequest("chat",e)}async create(e){return this.processStreamableRequest("create",{...e})}async pull(e){return this.processStreamableRequest("pull",{name:e.model,stream:e.stream,insecure:e.insecure})}async push(e){return this.processStreamableRequest("push",{name:e.model,stream:e.stream,insecure:e.insecure})}async delete(e){return await Qno(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await $K(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await jlr(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await $K(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await $K(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await $K(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await jlr(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}},Jxa=new LK});var BQe,Llr=v(()=>{Tlr();Qa();YI();rxe();id();_v();g1();nO();fO();Wv();nb();BQe=class extends md{constructor(e){super(e??{});x(this,"model","llama3");x(this,"numa");x(this,"numCtx");x(this,"numBatch");x(this,"numGpu");x(this,"mainGpu");x(this,"lowVram");x(this,"f16Kv");x(this,"logitsAll");x(this,"vocabOnly");x(this,"useMmap");x(this,"useMlock");x(this,"embeddingOnly");x(this,"numThread");x(this,"numKeep");x(this,"seed");x(this,"numPredict");x(this,"topK");x(this,"topP");x(this,"tfsZ");x(this,"typicalP");x(this,"repeatLastN");x(this,"temperature");x(this,"repeatPenalty");x(this,"presencePenalty");x(this,"frequencyPenalty");x(this,"mirostat");x(this,"mirostatTau");x(this,"mirostatEta");x(this,"penalizeNewline");x(this,"streaming");x(this,"format");x(this,"keepAlive");x(this,"client");x(this,"checkOrPullModel",!1);x(this,"baseUrl","http://127.0.0.1:11434");x(this,"think");this.client=new LK({fetch:e?.fetch,host:e?.baseUrl,headers:e?.headers}),this.baseUr
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
`,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} status code (no body)`: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} must be an integer`);if(e<0)throw new Vt(`${t} must be a positive integer`);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>"
`):[]}};Kv=new WeakMap,Gv=new WeakMap;P2.NEWLINE_CHARS=new Set([`
`,"\r"]);P2.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function Ioe(){}function cxe(t,e,r){return!e||dxe[t]>dxe[r]?Ioe:e[t].bind(e)}function Kc(t){let e=t.logger,r=t.logLevel??"off";if(!e)return hoo;let n=hcr.get(e);if(n&&n[0]===r)return n[1];let o={error:cxe("error",e,r),warn:cxe("warn",e,r),info:cxe("info",e,r),debug:cxe("debug",e,r)};return hcr.set(e,[r,o]),o}var dxe,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))return t;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=new WeakMap;_1=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t)});async function*goo(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Vt("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 Vt("Attempted to iterate over a response with no body");let r=new set,n=new P2,o=YQe(t.body);for await(let i of yoo(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*yoo(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"?XK(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let i;for(;(i=pcr(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function boo(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var Aoe,aR,set,uet=v(()=>{IS();nR();Moe();mcr();Moe();nxe();lxe();Roe();nR();aR=class t{constructor(e,r,n){this.iterator=e,Aoe.set(this,void 0),this.controller=r,Hr(this,Aoe,n,"f")}static fromSSEResponse(e,r,n){let o=!1,i=n?Kc(n):console;async function*a(){if(o)throw new Vt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let s=!1;try{for await(let u of goo(e,r))if(!s){if(u.data.startsWith("[DONE]")){s=!0;continue}if(u.event===null||!u.event.startsWith("thread.")){let l;try{l=JSON.parse(u.data)}catch(c){throw i.error("Could not parse message into JSON:",u.data),i.error("From chunk:",u.raw),c}if(l&&l.error)throw new Em(void 0,l.error,void 0,e.headers);yield l}else{let l;try{l=JSON.parse(u.data)}catch(c){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),c}if(u.event=="error")throw new Em(void 0,l.error,l.message,void 0);yield{event:u.event,data:l}}}s=!0}catch(u){if(Eoe(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 P2,u=YQe(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 Vt("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(Eoe(u))return;throw u}finally{s||r.abort()}}return new t(a,r,n)}[(Aoe=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,xe(this,Aoe,"f")),new t(()=>o(r),this.controller,xe(this,Aoe,"f"))]}toReadableStream(){let e=this,r;return ZQe({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=XK(JSON.stringify(o)+`
`);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};set=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=boo(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function fxe(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:o,startTime:i}=e,a=await(async()=>{if(e.options.stream)return Kc(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller,t):aR.fromSSEResponse(r,e.controller,t);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let u=r.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){let d=await r.json();return cet(d,r)}return await r.text()})();return Kc(t).debug(`[${n}] response parsed`,_1({retryOfRequestLogID:o,url:r.url,status:r.status,body:a,durationMs:Date.now()-i})),a}function cet(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var det=v(()=>{uet();Roe()});var Noe,M2,pxe=v(()=>{IS();det();M2=class t extends Promise{constructor(e,r,n=fxe){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,Noe.set(this,void 0),Hr(this,Noe,e,"f")}_thenUnwrap(e){return new t(xe(this,Noe,"f"),this.responsePromise,async(r,n)=>cet(e(await this.parseResponse(r,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(xe(this,Noe,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};Noe=new WeakMap});var mxe,joe,Doe,sR,ri,v1,Iu=v(()=>{IS();nR();det();pxe();b1();joe=class{constructor(e,r,n,o){mxe.set(this,void 0),Hr(this,mxe,e,"f"),this.options=o,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new Vt("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await xe(this,mxe,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(mxe=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},Doe=class extends M2{constructor(e,r,n){super(e,r,async(o,i)=>new n(o,i.response,await fxe(o,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},sR=class extends joe{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},ri=class extends joe{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),r=e[e.length-1]?.id;return r?{...this.options,query:{...KQe(this.options.query),after:r}}:null}},v1=class extends joe{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...KQe(this.options.query),after:e}}:null}}});function ZK(t,e,r){return met(),new File(t,e??"unknown_file",r)}function $oe(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}function voo(t){let e=typeof t=="fu
${i.map(f=>f.error).join(`
`)}
${a}
${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("no tool call snapshot");if(!i.type)throw new Error("tool call snapshot missing `type`");if(i.type==="function"){let a=xe(this,S1,"f")?.tools?.find(s=>Foe(s)&&s.func
This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
`);this.baseURL=s.baseURL,this.timeout=s.timeout??Jtt.DEFAULT_TIMEOUT,this.logger=s.logger??console;let u="warn";this.logLevel=u,this.logLevel=aet(s.logLevel,"ClientOptions.logLevel",this)??aet(NC("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??Zlr(),Hr(this,Fxe,Qlr,"f"),this._options=s,this.apiKey=typeof r=="string"?r:"Missing Key",this.organization=n,this.project=o,this.webhookSecret=i}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){}async authHeaders(e){return mt([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return oet(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${WF}`}defaultIdempotencyKey(){return`stainless-node-retry-${HQe()}`}makeStatusError(e,r,n,o){return Em.generate(e,r,n,o)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let r;try{r=await e()}catch(n){throw n instanceof Vt?n:new Vt(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof r!="string"||!r)throw new Vt(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,n){let o=!xe(this,Htt,"m",ndr).call(this)&&n||this.baseURL,i=Ulr(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return Blr(a)||(r={...a,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(i.search=this.stringifyQuery(r)),i.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(o=>({method:e,path:r,...o})))}request(e,r=null){return new M2(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let o=await e,i=o.maxRetries??this.maxRetries;r==null&&(r=i),await this.prepareOptions(o);let{req:a,url:s,timeout:u}=await this.buildRequest(o,{retryCount:i-r});await this.prepareRequest(a,{url:s,options:o});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),c=n===void 0?"":`, retryOf: ${n}`,d=Date.now();if(Kc(this).debug(`[${l}] sending request`,_1({retryOfRequestLogID:n,method:o.method,url:s,options:o,headers:a.headers})),o.signal?.aborted)throw new Ic;let f=new AbortController,p=await this.fetchWithTimeout(s,a,u,f).catch(Poe),m=Date.now();if(p instanceof globalThis.Error){let g=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new Ic;let b=Eoe(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(r)return Kc(this).info(`[${l}] connection ${b?"timed out":"failed"} - ${g}`),Kc(this).debug(`[${l}] connection ${b?"timed out":"failed"} (${g})`,_1({retryOfRequestLogID:n,url:s,durationMs:m-d,message:p.message})),this.retryRequest(o,r,n??l);throw Kc(this).info(`[${l}] connection ${b?"timed out":"failed"} - error; no more retries left`),Kc(this).debug(`[${l}] connection ${b?"timed out":"failed"} (error; no more retries left)`,_1({retryOfRequestLogID:n,url:s,durationMs:m-d,message:p.message})),b?new tR:new JF({cause:p})}let h=[...p.headers.entries()].filter(([g])=>g==="x-request-id").map(([g,b])=>", "+g+": "+JSON.stringify(b)).join(""),y=`[${l}${c}${h}] ${a.method} ${s} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${m-d}ms`;if(!p.ok){let g=await this.shouldRetry(p);if(r&&g){let P=`retrying, ${r} attempts remaining`;return await Ylr(p.body),Kc(this).info(`${y} - ${P}`),Kc(this).debug(`[${l}] response error (${P})`,_1({retryOfRequestLogID:n,url:p.ur
`)}function cdr(t,e){let r=[];for(let[n,o]of Object.entries(t.properties??{}))o.description&&e<2&&r.push(`// ${o.description}`),t.required?.includes(n)?r.push(`${n}: ${qxe(o,e)},`):r.push(`${n}?: ${qxe(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
`)}function qxe(t,e){if(Tio(t))return t.anyOf.map(r=>qxe(r,e)).join(" | ");switch(t.type){case"string":return t.enum?t.enum.map(r=>`"${r}"`).join(" | "):"string";case"number":return t.enum?t.enum.map(r=>`${r}`).join(" | "):"number";case"integer":return t.enum?t.enum.map(r=>`${r}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",cdr(t,e+2),"}"].join(`
`);case"array":return t.items?`${qxe(t.items,e)}[]`:"any[]";default:return""}}function Uxe(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}function A8(t){return"type"in t&&t.type!=="function"}function ddr(t){return typeof t=="object"&&t!==null&&"extras"in t&&typeof t.extras=="object"&&t.extras!==null&&"providerToolDefinition"in t.extras&&typeof t.extras.providerToolDefinition=="object"&&t.extras.providerToolDefinition!==null}function fdr(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function Y2(t){return typeof t=="object"&&t!==null&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null&&"customTool"in t.metadata&&typeof t.metadata.customTool=="object"&&t.metadata.customTool!==null}function Bxe(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function pdr(t){if(t.type==="custom_tool_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:t.name,isCustomTool:!0,args:{input:t.input}}}function mdr(t){if(t.type==="computer_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:"computer_use",isComputerTool:!0,args:{action:t.action}}}function hdr(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function gdr(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isCustomTool"in t&&t.isCustomTool===!0}function ydr(t){let e=()=>{if(t.custom.format){if(t.custom.format.type==="grammar")return{type:"grammar",definition:t.custom.format.grammar.definition,syntax:t.custom.format.grammar.syntax};if(t.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:t.custom.name,description:t.custom.description,format:e()}}function bdr(t){let e=()=>{if(t.format){if(t.format.type==="grammar")return{type:"grammar",grammar:{definition:t.format.definition,syntax:t.format.syntax}};if(t.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:t.name,description:t.description,format:e()}}}var N8=v(()=>{g1();Wv();nb()});var Ktt=v(()=>{Yg()});var Wxe={};Rn(Wxe,{ZodISODate:()=>Vxe,ZodISODateTime:()=>zxe,ZodISODuration:()=>Jxe,ZodISOTime:()=>Hxe,date:()=>Xtt,datetime:()=>Gtt,duration:()=>Ytt,time:()=>Ztt});function Gtt(t){return F4e(zxe,t)}function Xtt(t){return k4e(Vxe,t)}function Ztt(t){return q4e(Hxe,t)}function Ytt(t){return U4e(Jxe,t)}var zxe,Vxe,Hxe,Jxe,Kxe=v(()=>{Yg();Gxe();zxe=Se("ZodISODateTime",(t,e)=>{Uze.init(t,e),Wu.init(t,e)});Vxe=Se("ZodISODate",(t,e)=>{Bze.init(t,e),Wu.init(t,e)});Hxe=Se("ZodISOTime",(t,e)=>{zze.init(t,e),Wu.init(t,e)});Jxe=Se("ZodISODuration",(t,e)=>{Vze.init(t,e),Wu.init(t,e)})});var vdr,Pio,j8,Qtt=v(()=>{Yg();Yg();vdr=(t,e)=>{OQ.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>EQ(t,r)},flatten:{value:r=>TQ(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},Pio=Se("ZodError",vdr),j8=Se("ZodError",vdr,{Parent:Error})});var ert,trt,rrt,nrt,ort=v(()=>{Yg();Qtt();ert=xme(j8),trt=Ome(j8),rrt=Tme(j8),nrt=Eme(j8)});function irt(t){return D4e(Qoe,t)}function Iio(t){return Ume(urt,t)}function Rio(t){return $Q(Xxe,t)}function Aio(t){return Bme(R1,t)}function Nio(t){return zme(R1,t)}function jio(t){return Vme(R1,t)}function Dio(t){return Hme(R1,t)}function $io(t){return Jme(lrt,t)}function Lio(t){return Wme(crt,t)}function Fio(t){return Kme(drt,t)}function kio(t){return Gme(frt,t)}function qio(t){return Xme(prt,t)}function Uio(t){return Zme(mrt,t)}function Bio(t){return Yme(hrt,t)}function zio(t){return Qme(grt,t)}function Vio(t){return ehe(yrt,t)}function Hio(t){return the(brt,t)}function Jio(t){return rhe(_rt,t)}function Wio(t){return nhe(vrt,t)}function Kio(t){return ohe(wrt,t)}function Gio(t){return ihe(Srt,t)}function Xio(t){return ahe(Crt,t)}function Zio(t){return she(xrt,t)}function Yio(t,e,r={}){return _2e(wdr,t,e,r)}function Sdr(t){return B4e(eie,t)}function art(t){return V4e(D8,t)}function Qio(t){r
]))`;continue}else if(o[l]==="$"){i+=`($|(?=[\r
]))`;continue}}if(n.s&&o[l]==="."){i+=s?`${o[l]}\r
`:`[${o[l]}\r
]`;continue}i+=o[l],o[l]==="\\"?a=!0:s&&o[l]==="]"?s=!1:!s&&o[l]==="["&&(s=!0)}try{let l=new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return i}});function lOe(t,e){if(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]:Tn(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:Tn(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===Ie.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(sOe(t.keyType._def,e)).reduce((o,[i,a])=>i==="type"?o:{...o,[i]:a},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===Ie.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}var cOe=v(()=>{cO();hd();uOe()});function Mfr(t,e){if(e.mapStrategy==="record")return lOe(t,e);let r=Tn(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=Tn(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var Qrt=v(()=>{hd();cOe()});function Ifr(t){let e=t.values,n=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var ent=v(()=>{});function Rfr(){return{not:{}}}var tnt=v(()=>{});function Afr(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var rnt=v(()=>{});function jfr(t,e){if(e.target==="openApi3")return Nfr(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in oie&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=oie[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((i,a,s)=>s.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return Nfr(t,e)}var oie,Nfr,dOe=v(()=>{hd();oie={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Nfr=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Tn(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function Dfr(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:oie[t.innerType._def.typeName],nullable:!0}:{type:[oie[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Tn(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Tn(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var nnt=v(()=>{hd();dOe()});function $fr(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Frt(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?
`))}let n={name:t.function.name,args:r,type:"tool_call"};return e?.returnId&&(n.id=t.id),n}function ck(t){if(t.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:t.id,type:"function",function:{name:t.name,arguments:JSON.stringify(t.args)}}}function AS(t,e){return{name:t.function?.name,args:t.function?.arguments,id:t.id,error:e,type:"invalid_tool_call"}}var bnt,qC,npr=v(()=>{RY();Rw();eN();TW();uL();CVe();bnt=class extends sL{constructor(e){super(e);x(this,"returnId",!1);x(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);x(this,"lc_serializable",!0);this.returnId=e?.returnId??this.returnId}static lc_name(){return"JsonOutputToolsParser"}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,r=!0){let n=e[0].message,o;if(Pl(n)&&n.tool_calls?.length?o=n.tool_calls.map(a=>{let{id:s,...u}=a;return this.returnId?{id:s,...u}:u}):n.additional_kwargs.tool_calls!==void 0&&(o=JSON.parse(JSON.stringify(n.additional_kwargs.tool_calls)).map(s=>kC(s,{returnId:this.returnId,partial:r}))),!o)return[];let i=[];for(let a of o)if(a!==void 0){let s={type:a.name,args:a.args,id:a.id};i.push(s)}return i}},qC=class extends bnt{constructor(e){super(e);x(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);x(this,"lc_serializable",!0);x(this,"returnId",!1);x(this,"keyName");x(this,"returnSingle",!1);x(this,"zodSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}static lc_name(){return"JsonOutputKeyToolsParser"}async _validateResult(e){if(this.zodSchema===void 0)return e;let r=await Y$(this.zodSchema,e);if(r.success)return r.data;throw new th(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(r.error?.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){let n=(await super.parsePartialResult(e)).filter(i=>i.type===this.keyName),o=n;if(n.length)return this.returnId||(o=n.map(i=>i.args)),this.returnSingle?o[0]:o}async parseResult(e){let n=(await super.parsePartialResult(e,!1)).filter(a=>a.type===this.keyName),o=n;return n.length?(this.returnId||(o=n.map(a=>a.args)),this.returnSingle?this._validateResult(o[0]):await Promise.all(o.map(a=>this._validateResult(a)))):void 0}}});var rso,$8=v(()=>{Bo();npr();rso={};Rt(rso,{JsonOutputKeyToolsParser:()=>qC,JsonOutputToolsParser:()=>bnt,convertLangChainToolCallToOpenAI:()=>ck,makeInvalidToolCall:()=>AS,parseToolCall:()=>kC})});var rV,iie=v(()=>{ak();N8();sk();uk();ynt();rpr();dR();Wv();nb();ku();YI();Jv();_v();fO();$8();rV=class extends md{constructor(e){super(e??{});x(this,"temperature");x(this,"topP");x(this,"frequencyPenalty");x(this,"presencePenalty");x(this,"n");x(this,"logitBias");x(this,"model","gpt-3.5-turbo");x(this,"modelKwargs");x(this,"stop");x(this,"stopSequences");x(this,"user");x(this,"timeout");x(this,"streaming",!1);x(this,"streamUsage",!0);x(this,"maxTokens");x(this,"logprobs");x(this,"topLogprobs");x(this,"apiKey");x(this,"organization");x(this,"__includeRawResponse");x(this,"client");x(this,"clientConfig");x(this,"supportsStrictToolCalling");x(this,"audio");x(this,"modalities");x(this,"reasoning");x(this,"zdrEnabled");x(this,"service_tier");x(this,"promptCacheKey");x(this,"promptCacheRetention");x(this,"verbosity");x(this,"defaultOptions");x(this,"lc_serializable",!0);let r=typeof e?.configuration?.apiKey=="string"||typeof e?.configuration?.apiKey=="function"?e?.configuration?.apiKey:void 0;this.apiKey=e?.apiKey??r??vn("OPENAI_API_KEY"),this.organization=e?.configuration?.organization??vn("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelKwargs=e?.modelKwargs??{},this.timeout=e?.timeout,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.frequencyPenalty=e?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=e?.presencePenalty??this.presencePenalty,this.logprobs=e?.logprobs,this.topLogprobs=e?.topLogprobs,this.n=e?.n??this.n,this.log
Details: ${m.message}`),phe(m)&&(h=`${h}
${Kt.prettifyError(m)}`),new H3(h,JSON.stringify(e))}else{let m=qu(o,this.schema);if(!m.valid){let h="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(h=`${h}
Details: ${m.errors.map(y=>`${y.keywordLocation}: ${y.error}`).join(`
`)}`),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("Array of shell commands to execute"),timeout_ms:Kt.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:Kt.number().optional().describe("Optional maximum number of characters to return from each command")})});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
without CORS Error: `+Sn(n)+`
with CORS Error: `+Sn(o);throw new Error(i)}}}}});function qpr(t){return t!==void 0&&uie.includes(t)?Fpr[t]:void 0}var Fpr,kpr,uie,SOe=v(()=>{Fpr={arabic:"ar",armenian:"am",bulgarian:"bg",danish:"dk",dutch:"nl",english:"en",finnish:"fi",french:"fr",german:"de",greek:"gr",hungarian:"hu",indian:"in",indonesian:"id",irish:"ie",italian:"it",lithuanian:"lt",nepali:"np",norwegian:"no",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"rs",slovenian:"ru",spanish:"es",swedish:"se",tamil:"ta",turkish:"tr",ukrainian:"uk",sanskrit:"sk"},kpr={dutch:/[^A-Za-zàèéìòóù0-9_'-]+/gim,english:/[^A-Za-zàèéìòóù0-9_'-]+/gim,french:/[^a-z0-9äâàéèëêïîöôùüûœç-]+/gim,italian:/[^A-Za-zàèéìòóù0-9_'-]+/gim,norwegian:/[^a-z0-9_æøåÆØÅäÄöÖüÜ]+/gim,portuguese:/[^a-z0-9à-úÀ-Ú]/gim,russian:/[^a-z0-9а-яА-ЯёЁ]+/gim,spanish:/[^a-z0-9A-Zá-úÁ-ÚñÑüÜ]+/gim,swedish:/[^a-z0-9_åÅäÄöÖüÜ-]+/gim,german:/[^a-z0-9A-ZäöüÄÖÜß]+/gim,finnish:/[^a-z0-9äöÄÖ]+/gim,danish:/[^a-z0-9æøåÆØÅ]+/gim,hungarian:/[^a-z0-9áéíóöőúüűÁÉÍÓÖŐÚÜŰ]+/gim,romanian:/[^a-z0-9ăâîșțĂÂÎȘȚ]+/gim,serbian:/[^a-z0-9čćžšđČĆŽŠĐ]+/gim,turkish:/[^a-z0-9çÇğĞıİöÖşŞüÜ]+/gim,lithuanian:/[^a-z0-9ąčęėįšųūžĄČĘĖĮŠŲŪŽ]+/gim,arabic:/[^a-z0-9أ-ي]+/gim,nepali:/[^a-z0-9अ-ह]+/gim,irish:/[^a-z0-9áéíóúÁÉÍÓÚ]+/gim,indian:/[^a-z0-9अ-ह]+/gim,armenian:/[^a-z0-9ա-ֆ]+/gim,greek:/[^a-z0-9α-ωά-ώ]+/gim,indonesian:/[^a-z0-9]+/gim,ukrainian:/[^a-z0-9а-яА-ЯіїєІЇЄ]+/gim,slovenian:/[^a-z0-9螚ȎŠ]+/gim,bulgarian:/[^a-z0-9а-яА-Я]+/gim,tamil:/[^a-z0-9அ-ஹ]+/gim,sanskrit:/[^a-z0-9A-Zāīūṛḷṃṁḥśṣṭḍṇṅñḻḹṝ]+/gim},uie=Object.keys(Fpr)});function Ru(t,e){if(e.length<jnt)Array.prototype.push.apply(t,e);else{let r=e.length;for(let n=0;n<r;n+=jnt)Array.prototype.push.apply(t,e.slice(n,n+jnt))}}function Hpr(t,...e){return t.replace(/%(?:(?<position>\d+)\$)?(?<width>-?\d*\.?\d*)(?<type>[dfs])/g,function(...r){let n=r[r.length-1],{width:o,type:i,position:a}=n,s=a?e[Number.parseInt(a)-1]:e.shift(),u=o===""?0:Number.parseInt(o);switch(i){case"d":return s.toString().padStart(u,"0");case"f":{let l=s,[c,d]=o.split(".").map(f=>Number.parseFloat(f));return typeof d=="number"&&d>=0&&(l=l.toFixed(d)),typeof c=="number"&&c>=0?l.toString().padStart(u,"0"):l.toString()}case"s":return u<0?s.toString().padEnd(-u," "):s.toString().padStart(u," ");default:return s}})}function Rso(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Aso(){return typeof process<"u"&&process.release&&process.release.name==="node"}function Vpr(){return BigInt(Math.floor(performance.now()*1e6))}function sV(t){return typeof t=="number"&&(t=BigInt(t)),t<Upr?`${t}ns`:t<Bpr?`${t/Upr}\u03BCs`:t<zpr?`${t/Bpr}ms`:`${t/zpr}s`}function BC(){return Rso()?Vpr():Aso()||typeof process<"u"&&typeof process?.hrtime?.bigint=="function"?process.hrtime.bigint():typeof performance<"u"?Vpr():BigInt(0)}function lie(){return`${Mso}-${Iso++}`}function k8(t,e){return Object.hasOwn===void 0?Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0:Object.hasOwn(t,e)?t[e]:void 0}function Jpr(t,e){return e[1]===t[1]?t[0]-e[0]:e[1]-t[1]}function q8(t){if(t.length===0)return[];if(t.length===1)return t[0];for(let r=1;r<t.length;r++)if(t[r].length<t[0].length){let n=t[0];t[0]=t[r],t[r]=n}let e=new Map;for(let r of t[0])e.set(r,1);for(let r=1;r<t.length;r++){let n=0;for(let o of t[r]){let i=e.get(o);i===r&&(e.set(o,i+1),n++)}if(n===0)return[]}return t[0].filter(r=>{let n=e.get(r);return n!==void 0&&e.set(r,0),n===t.length})}function COe(t,e){let r={},n=e.length;for(let o=0;o<n;o++){let i=e[o],a=i.split("."),s=t,u=a.length;for(let l=0;l<u;l++)if(s=s[a[l]],typeof s=="object"){if(s!==null&&"lat"in s&&"lon"in s&&typeof s.lat=="number"&&typeof s.lon=="number"){s=r[i]=s;break}else if(!Array.isArray(s)&&s!==null&&l===u-1){s=void 0;break}}else if((s===null||typeof s!="object")&&l<u-1){s=void 0;break}typeof s<"u"&&(r[i]=s)}return r}function U8(t,e){return COe(t,[e])[e]}fu
- `),Dso={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported.
Supported languages are:
- ${jso}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmer property must be a function.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.oramasearch.com/open-source/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Custom stop words array must only contain strings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boost value must be a number greater than, or less than 0.",INVALID_FILTER_OPERATION:"You can only use one operation per filter, you requested %d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sort is disabled. Please read the documentation at https://docs.oramasearch for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead.
Input vectors must be of the size declared in the schema, as calculating similarity between vectors of different sizes can lead to unexpected results.`,WRONG_SEARCH_PROPERTY_TYPE:'Property "%s" is not searchable. Only "string" properties are searchable.',FACET_NOT_SUPPORTED:`Facet doens't support the type "%s".`,INVALID_DISTANCE_SUFFIX:'Invalid distance suffix "%s". Valid suffixes are: cm, m, km, mi, yd, ft.',INVALID_SEARCH_MODE:'Invalid search mode "%s". Valid modes are: "fulltext", "vector", "hybrid".',MISSING_VECTOR_AND_SECURE_PROXY:"No vector was provided and no secure proxy was configured. Please provide a vector or configure an Orama Secure Proxy to perform hybrid search.",MISSING_TERM:'"term" is a required parameter when performing hybrid search. Please provide a search term.',INVALID_VECTOR_INPUT:'Invalid "vector" property. Expected an object with "value" and "property" properties, but got "%s" instead.',PLUGIN_CRASHED:"A plugin crashed during initialization. Please check the error message for more information:",PLUGIN_SECURE_PROXY_NOT_FOUND:`Could not find '@orama/secure-proxy-plugin' installed in your Orama instance.
Please install it before proceeding with creating an answer session.
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL:`Could not find a chat model defined in the secure proxy plugin configuration.
Please provide a chat model before proceeding with creating an answer session.
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages."}});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",[`
`,`
`," ",""]);this.separators=r?.separators??this.separators,this.keepSeparator=r?.keepSeparator??!0}static lc_name(){return"RecursiveCharacterTextSplitter"}async _splitText(r,n){let o=[],i=n[n.length-1],a;for(let c=0;c<n.length;c+=1){let d=n[c];if(d===""){i=d;break}if(r.includes(d)){i=d,a=n.slice(c+1);break}}let s=this.splitOnSeparator(r,i),u=[],l=this.keepSeparator?"":i;for(let c of s)if(await this.lengthFunction(c)<this.chunkSize)u.push(c);else{if(u.length){let d=await this.mergeSplits(u,l);o.push(...d),u=[]}if(!a)o.push(c);else{let d=await this._splitText(c,a);o.push(...d)}}if(u.length){let c=await this.mergeSplits(u,l);o.push(...c)}return o}async splitText(r){return this._splitText(r,this.separators)}static fromLanguage(r,n){return new Pot({...n,separators:Pot.getSeparatorsForLanguage(r)})}static getSeparatorsForLanguage(r){if(r==="cpp")return[`
class `,`
void `,`
int `,`
float `,`
double `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
`,`
`," ",""];if(r==="go")return[`
func `,`
var `,`
const `,`
type `,`
if `,`
for `,`
switch `,`
case `,`
`,`
`," ",""];if(r==="java")return[`
class `,`
public `,`
protected `,`
private `,`
static `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
`,`
`," ",""];if(r==="js")return[`
function `,`
const `,`
let `,`
var `,`
class `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
default `,`
`,`
`," ",""];if(r==="php")return[`
function `,`
class `,`
if `,`
foreach `,`
while `,`
do `,`
switch `,`
case `,`
`,`
`," ",""];if(r==="proto")return[`
message `,`
service `,`
enum `,`
option `,`
import `,`
syntax `,`
`,`
`," ",""];if(r==="python")return[`
class `,`
def `,`
def `,`
`,`
`," ",""];if(r==="rst")return[`
===
`,`
---
`,`
***
`,`
.. `,`
`,`
`," ",""];if(r==="ruby")return[`
def `,`
class `,`
if `,`
unless `,`
while `,`
for `,`
do `,`
begin `,`
rescue `,`
`,`
`," ",""];if(r==="rust")return[`
fn `,`
const `,`
let `,`
if `,`
while `,`
for `,`
loop `,`
match `,`
const `,`
`,`
`," ",""];if(r==="scala")return[`
class `,`
object `,`
def `,`
val `,`
var `,`
if `,`
for `,`
while `,`
match `,`
case `,`
`,`
`," ",""];if(r==="swift")return[`
func `,`
class `,`
struct `,`
enum `,`
if `,`
for `,`
while `,`
do `,`
switch `,`
case `,`
`,`
`," ",""];if(r==="markdown")return[`
## `,`
### `,`
#### `,`
##### `,`
###### `,"```\n\n",`
***
`,`
---
`,`
___
`,`
`,`
`," ",""];if(r==="latex")return[`
\\chapter{`,`
\\section{`,`
\\subsection{`,`
\\subsubsection{`,`
\\begin{enumerate}`,`
\\begin{itemize}`,`
\\begin{description}`,`
\\begin{list}`,`
\\begin{quote}`,`
\\begin{quotation}`,`
\\begin{verse}`,`
\\begin{verbatim}`,`
\\begin{align}`,"$$","$",`
`,`
`," ",""];if(r==="html")return["<body>","<div>","<p>","<br>","<li>","<h1>","<h2>","<h3>","<h4>","<h5>","<h6>","<span>","<table>","<tr>","<td>","<th>","<ul>","<ol>","<header>","<footer>","<nav>","<head>","<style>","<script>","<meta>","<title>"," ",""];if(r==="sol")return[`
pragma `,`
using `,`
contract `,`
interface `,`
library `,`
constructor `,`
type `,`
function `,`
event `,`
modifier `,`
error `,`
struct `,`
enum `,`
if `,`
for `,`
while `,`
do while `,`
assembly `,`
`,`
`," ",""];throw new Error(`Language ${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:`
NOTE TITLE: [[${l.title}]]
METADATA:${JSON.stringify(l.metadata)}
NOTE BLOCK CONTENT:
`,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
${e.join(`
`)}`)}}});var aG,kot=v(()=>{Fot();mR();Zt();_t();aG=class t{constructor(){this.mentions=new Map,this.brevilabsClient=pc.getInstance()}static getInstance(){return t.instance||(t.instance=new t),t.instance}extractAllUrls(e){let r=/https?:\/\/[^\s"'<>]+/g;return(e.match(r)||[]).map(n=>n.replace(/,+$/,"")).filter((n,o,i)=>i.indexOf(n)===o)}extractUrls(e){let r=/https?:\/\/[^\s"'<>]+/g;return(e.match(r)||[]).map(n=>n.replace(/,+$/,"")).filter((n,o,i)=>i.indexOf(n)===o)}async processUrl(e){try{return await this.brevilabsClient.url4llm(e)}catch(r){let n=Sn(r);return ne(`Error processing URL ${e}: ${n}`),{response:e,elapsed_time_ms:0,error:n}}}async processYoutubeUrl(e){try{return{transcript:(await this.brevilabsClient.youtube4llm(e)).response.transcript}}catch(r){let n=Sn(r);return ne(`Error processing YouTube URL ${e}: ${n}`),{transcript:"",error:n}}}async processUrlList(e){let r="",n=[],o={};if(e.length===0)return{urlContext:r,imageUrls:n,processedErrorUrls:o};let i=e.map(async s=>{if(await _R.isImageUrl(s,app.vault))return n.push(s),{type:"image",url:s};if(NRt(s)){if(!this.mentions.has(s)){let u=await this.processYoutubeUrl(s);this.mentions.set(s,{type:"youtube",original:s,processed:u.transcript,error:u.error})}return{type:"youtube",data:this.mentions.get(s)}}if(!this.mentions.has(s)){let u=await this.processUrl(s);this.mentions.set(s,{type:"url",original:s,processed:u.response,error:u.error})}return{type:"url",data:this.mentions.get(s)}});return(await Promise.all(i)).forEach(s=>{if(s.type==="image")return;let u=s.data;u&&(u.processed&&(s.type==="youtube"?r+=`
<youtube_transcript>
<url>${u.original}</url>
<transcript>
${u.processed}
</transcript>
</youtube_transcript>`:r+=`
<url_content>
<url>${u.original}</url>
<content>
${u.processed}
</content>
</url_content>`),u.error&&(o[u.original]=u.error))}),{urlContext:r,imageUrls:n,processedErrorUrls:o}}async processUrls(e){let r=this.extractUrls(e);return this.processUrlList(r)}getMentions(){return this.mentions}clearMentions(){this.mentions.clear()}}});var Ugr,MTe,Bgr=v(()=>{_t();Ugr=L(mV()),MTe=class t{constructor(){this.cacheDir=".copilot/pdf-cache"}static getInstance(){return t.instance||(t.instance=new t),t.instance}async ensureCacheDir(){await app.vault.adapter.exists(this.cacheDir)||(B("Creating PDF cache directory:",this.cacheDir),await app.vault.adapter.mkdir(this.cacheDir))}getCacheKey(e){let r=`${e.path}:${e.stat.size}:${e.stat.mtime}`,n=(0,Ugr.MD5)(r).toString();return B("Generated cache key for PDF:",{path:e.path,key:n}),n}getCachePath(e){return`${this.cacheDir}/${e}.json`}async get(e){try{let r=this.getCacheKey(e),n=this.getCachePath(r);if(await app.vault.adapter.exists(n)){B("Cache hit for PDF:",e.path);let o=await app.vault.adapter.read(n);return JSON.parse(o)}return B("Cache miss for PDF:",e.path),null}catch(r){return ne("Error reading from PDF cache:",r),null}}async set(e,r){try{await this.ensureCacheDir();let n=this.getCacheKey(e),o=this.getCachePath(n);B("Caching PDF response for:",e.path),await app.vault.adapter.write(o,JSON.stringify(r))}catch(n){ne("Error writing to PDF cache:",n)}}async clear(){try{if(await app.vault.adapter.exists(this.cacheDir)){let e=await app.vault.adapter.list(this.cacheDir);B("Clearing PDF cache, removing files:",e.files.length);for(let r of e.files)await app.vault.adapter.remove(r)}}catch(e){ne("Error clearing PDF cache:",e)}}}});function $1(t){if(!t||typeof t!="object")return!1;let e=t.message||t.toString();return e.includes("Request rate limit exceeded")||e.includes("RATE_LIMIT_EXCEEDED")||e.includes("429")||t.status===429}function zgr(t){let r=(t?.message||t?.toString()||"").match(/Try again in ([\d\w\s]+)/);return r?r[1]:"some time"}var xie=v(()=>{});var Vgr,RTe,Hgr,ITe,Jgr=v(()=>{Vgr=require("obsidian"),ITe=class{constructor(e){this.vault=e;aqe(this,RTe)}async load(e){let r=await this.vault.read(e),{nodes:n=[],edges:o=[]}=JSON.parse(r),i=await Promise.all(n.map(async u=>{if(u.type==="file"&&u.file){let l=this.vault.getAbstractFileByPath(u.file),c=l instanceof Vgr.TFile?await this.vault.cachedRead(l):"";return{...u,content:c}}return u.type==="text"?{...u,content:u.text??""}:{...u,content:""}})),a=[...o];Awt(this,RTe,Hgr).call(this,i,a);let s=Object.fromEntries(i.map(u=>[u.id,u]));return{nodes:i,edges:a,byId:s}}buildPrompt(e){let r=new Map,n=e.nodes.filter(s=>s.type==="group");for(let s of n){let u=e.nodes.filter(l=>{if(l.id===s.id)return!1;let c=l.x+l.width/2,d=l.y+l.height/2;return c>=s.x&&d>=s.y&&c<=s.x+s.width&&d<=s.y+s.height});r.set(s.label||s.id,u)}let o=`This canvas contains the following elements:
`,i=s=>{switch(s.type){case"file":return`- File: ${s.file}
Content:
${s.content}
`;case"text":return`- Text: "${s.text}"
`;case"link":return`- Link: ${s.url}
`;default:return""}};n.forEach(s=>{let u=s.label||s.id,l=r.get(u)||[];o+=`Group "${u}" contains:
`,l.forEach(c=>{o+=i(c)}),o+=`
`});let a=e.nodes.filter(s=>s.type==="group"?!1:!Array.from(r.values()).flat().some(u=>u.id===s.id));return a.length>0&&(o+=`Elements outside of groups:
`,a.forEach(s=>{o+=i(s)})),o+=`
When describing this canvas, please:
`,o+=`- Use the actual titles/names of elements instead of their IDs
`,o+=`- Pay attention to the content and relationships between elements
`,o+=`- Describe files by their names, links by their URLs, and text nodes by their content
`,o}};RTe=new WeakSet,Hgr=function(e,r){let n=e.filter(o=>o.type==="group");for(let o of n)for(let i of e){if(i.id===o.id)continue;let a=i.x+i.width/2,s=i.y+i.height/2;a>=o.x&&s>=o.y&&a<=o.x+o.width&&s<=o.y+o.height&&r.push({id:crypto.randomUUID(),fromNode:o.id,toNode:i.id,label:"contains"})}}});var Wgr,qot,ATe,Uot,sG,Oie,vk,NTe=v(()=>{Bgr();iG();_t();xie();Wgr=require("obsidian");Jgr();qot=class{constructor(){this.supportedExtensions=["md"]}async parseFile(e,r){return await r.read(e)}},ATe=class{constructor(e){this.supportedExtensions=["pdf"];this.brevilabsClient=e,this.pdfCache=MTe.getInstance()}async parseFile(e,r){try{B("Parsing PDF file:",e.path);let n=await this.pdfCache.get(e);if(n)return B("Using cached PDF content for:",e.path),n.response;let o=await r.readBinary(e);B("Calling pdf4llm API for:",e.path);let i=await this.brevilabsClient.pdf4llm(o);return await this.pdfCache.set(e,i),i.response}catch(n){return ne(`Error extracting content from PDF ${e.path}:`,n),`[Error: Could not extract content from PDF ${e.basename}]`}}async clearCache(){B("Clearing PDF cache"),await this.pdfCache.clear()}},Uot=class{constructor(){this.supportedExtensions=["canvas"]}async parseFile(e,r){try{B("Parsing Canvas file:",e.path);let n=new ITe(r),o=await n.load(e);return n.buildPrompt(o)}catch(n){return ne(`Error parsing Canvas file ${e.path}:`,n),`[Error: Could not parse Canvas file ${e.basename}]`}}},sG=class sG{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}static resetRateLimitNoticeTimer(){sG.lastRateLimitNoticeTime=0}async parseFile(e,r){try{if(B(`[Docs4LLMParser] Project ${this.currentProject?.name}: Parsing ${e.extension} file: ${e.path}`),!this.currentProject)throw ne("[Docs4LLMParser] No project context for parsing file: ",e.path),new Error("No project context provided for file parsing");let n=await this.projectContextCache.getOrReuseFileContext(this.currentProject,e.path);if(n)return B(`[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.`);let o=await r.readBinary(e);B(`[Docs4LLMParser] Project ${this.currentProject.name}: Calling docs4llm API for: ${e.path}`);let i=await this.brevilabsClient.docs4llm(o,e.extension);if(!i||!i.response)throw new Error("Empty response from docs4llm API");let a="";if(typeof i.response=="string")a=i.response;else if(Array.isArray(i.response)){let s=[];for(let u of i.response)u.content&&(u.content.md?s.push(u.content.md):u.content.text&&s.push(u.content.text));a=s.join(`
`)}else typeof i.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);return await this.projectContextCache.setFileContext(this.currentProject,e.path,a),B(`[Docs4LLMParser] Project ${this.currentProject.name}: Successfully processed and cached: ${e.path}`),a}catch(n){throw ne(`[Docs4LLMParser] Project ${this.currentProject?.name}: Error processing file ${e.path}:`,n),$1(n)&&this.showRateLimitNotice(n),n}}showRateLimitNotice(e){let r=Date.now();if(r-sG.lastRateLimitNoticeTime<6e4)return;sG.lastRateLimitNoticeTime=r;let n=zgr(e);new Wgr.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)}async clearCache(){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=new Map;this.isProjectMode=n,this.currentProject=o,this.registerParser(new qot),this.registerParser(new Oie(e,o)),n||this.registerParser(new ATe(e)),this.registerParser(new Uot)}registerParser(e){for(let r of e.supportedExtensions)this.parsers.set(r,e)}async parseFile(e,r){let n=this.parsers.get(e.extension);if(!n)throw new Error(`No parser found for file type: ${e.extension}`);return await n.parseFile(e,r)}supportsExtension(e){return this.parsers.has(e)}async clearPDFCache(){let e=this.parsers.get("pdf");e instanceof ATe&&await e.clearCache()}}});var Wot={};Rn(Wot,{createToolCallMarker:()=>DTe,decodeResultFromMarker:()=>Vot,decodeToolCallMarkerResults:()=>Jlo,ensureEncodedToolCallMarkerResults:()=>jTe,parseToolCallMarkers:()=>Hot,updateToolCallMarker:()=>Jot});function zot(t){try{return`ENC:${encodeURIComponent(t)}`}catch{return t}}function Vot(t){if(typeof t!="string"||!t.startsWith("ENC:"))return t;try{return decodeURIComponent(t.slice(4))}catch{return t}}function Hlo(t){return`Tool '${t}' ${Vlo}`}function Jlo(t){return!t||typeof t!="string"?t:t.replace(/<!--TOOL_CALL_END:([^:]+):(ENC:[\s\S]*?)-->/g,(e,r,n)=>{let o=Vot(n)||n;return`<!--TOOL_CALL_END:${r}:${o}-->`})}function jTe(t){return!t||typeof t!="string"?t:t.replace(/<!--TOOL_CALL_END:([^:]+):([\s\S]*?)-->/g,(e,r,n)=>{if(n.startsWith("ENC:"))return e;let o=zot(n);return`<!--TOOL_CALL_END:${r}:${o}-->`})}function Bot(t,e=0,r=""){let n=[],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}return i<t.length&&n.push({type:"text",content:t.slice(i)}),n.length===0&&n.push({type:"text",content:t}),n}function Hot(t,e){let r=[],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(typeof m=="string"?m:""),b=(typeof y=="string"?y.length:0)>5e3?Hlo(u):y??void 0;r.push({type:"toolCall",content:p,toolCall:{id:s,toolName:u,displayName:l,emoji:c,confirmationMessage:d||void 0,isExecuting:f==="true",result:b,startIndex:i.index,endIndex:i.index+a.length}}),o=i.index+a.length}if(o<t.length){let a=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})})}return r.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}}function DTe(t,e,r,n,o="",i=!0,a="",s=""){let u=s&&zot(s);return`<!--TOOL_CALL_START:${t}:${e}:${r}:${n}:${o}:${i}-->${a}<!--TOOL_CAL
`,{turns:Array.isArray(c)?c.length:0});let d=2e3;try{let{parseToolCallMarkers:f}=await Promise.resolve().then(()=>(Tie(),Wot)),m=f(e).segments.map(y=>y.type==="text"?y.content:"").join("").trim();m||(m=e||"");let h=m.length>d?m.slice(0,d)+"... (truncated)":m;B(`Final AI response (truncated):
`,h)}catch{let f=typeof e=="string"?e:String(e??""),p=f.length>d?f.slice(0,d)+"... (truncated)":f;B(`Final AI response (truncated):
`,p)}return e}async handleError(e,r){let n=Sn(e);ne("Error during LLM invocation:",n);let o=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){let o=e.search("Troubleshooting URL");return e=o!==-1?e.slice(0,o):e,this.isAuthenticationError(n,r)&&(e=`Something went wrong. Please check if you have set your API key.
Path: Settings > copilot plugin > Basic Tab > Set Keys.
Or check model config
Error Details: `+e),e}isAuthenticationError(e,r){let n=e?.response,o=n?.data?.error??e?.error,i=n?.status??o?.status,a=typeof i=="string"?Number.parseInt(i,10):i,s=typeof o=="object"&&o!==null?o:void 0,u=(typeof s?.message=="string"?s.message:r).toLowerCase(),l=typeof s?.code=="string"?s.code.toLowerCase():"",c=typeof s?.type=="string"?s.type.toLowerCase():"";return a===401?!0:["api key","apikey","unauthorized","authentication","invalid authentication"].some(f=>u.includes(f)||l.includes(f)||c.includes(f))}}});var vR,Mie=v(()=>{_t();vR=class{static convert(e,r={}){let{includeSystemMessage:n=!0,mergeUserContent:o=!0,debug:i=!1}=r,a=[],s=e.layers.find(f=>f.id==="L1_SYSTEM"),u=e.layers.find(f=>f.id==="L2_PREVIOUS"),l=e.layers.find(f=>f.id==="L3_TURN"),c=e.layers.find(f=>f.id==="L4_STRIP"),d=e.layers.find(f=>f.id==="L5_USER");if(n&&s&&s.text){let f=[s.text];u&&u.text&&(f.push(`
## Context Library
The following notes are available for reference:
`+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){let f=[];if(l&&l.segments.length>0&&u){let p=new Set(u.segments.map(y=>y.id)),m=[],h=[];for(let y of l.segments)p.has(y.id)?m.push(y.id):h.push(y);if(m.length>0||h.length>0){let y=[];m.length>0&&y.push(`Context attached to this message:
`+m.map(g=>`- ${g}`).join(`
`)+`
Find them in the Context Library in the system prompt above.`),h.length>0&&y.push(h.map(g=>g.content).join(`
`)),f.push(y.join(`
`)),i&&B(`[LayerToMessagesConverter] Added L3: ${m.length} references, ${h.length} new items`)}}else l&&l.text&&(f.push(l.text),i&&B("[LayerToMessagesConverter] Added L3 (all new context)"));f.length>0&&d&&d.text&&f.push(`---
[User query]:`),d&&d.text&&(f.push(d.text),i&&B("[LayerToMessagesConverter] Added L5 (user message)")),f.length>0&&a.push({role:"user",content:f.join(`
`)})}else l&&l.text&&a.push({role:"user",content:l.text}),d&&d.text&&a.push({role:"user",content:d.text});return i&&(B(`[LayerToMessagesConverter] Converted envelope to ${a.length} messages`),a.forEach((f,p)=>{let m=f.content.substring(0,100);B(` Message ${p+1} [${f.role}]: ${m}...`)})),a}static extractUserContent(e){let r=e.layers.find(i=>i.id==="L3_TURN"),n=e.layers.find(i=>i.id==="L5_USER"),o=[];return r&&r.text&&o.push(r.text),n&&n.text&&o.push(n.text),o.join(`
`)}static extractFullContext(e){let r=e.layers.find(a=>a.id==="L2_PREVIOUS"),n=e.layers.find(a=>a.id==="L3_TURN"),o=e.layers.find(a=>a.id==="L5_USER"),i=[];return r&&r.text&&i.push(r.text),n&&n.text&&i.push(n.text),o&&o.text&&i.push(o.text),i.join(`
`)}static extractSystemMessage(e){return e.layers.find(n=>n.id==="L1_SYSTEM")?.text||""}static getLayerHashes(e){return e.layerHashes}}});function Kot(t){let e=[];for(let r of t)if(r){if(typeof r._getType=="function"){let n=r._getType();n==="human"?e.push({role:"user",content:r.content}):n==="ai"&&e.push({role:"assistant",content:r.content})}else if(r.content!==void 0){let n=Wlo(r);n&&e.push({role:n,content:r.content})}}return e}function Wlo(t){return t.role==="human"||t.role==="user"||t.sender==="user"?"user":t.role==="ai"||t.role==="assistant"||t.sender==="AI"?"assistant":null}function Klo(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(r=>r.type==="text").map(r=>r.text||"").join(" ")||"[Image content]":String(t||"")}function Kgr(t){return t.map(e=>({role:e.role,content:Klo(e.content)}))}async function wk(t,e){let n=(await t.loadMemoryVariables({})).history||[];if(!n.length)return[];let o=Kot(n);for(let i of o)e.push({role:i.role,content:i.content});return o}var uG=v(()=>{});var bd,yV=v(()=>{bd=class t{constructor(){this.tools=new Map}static getInstance(){return t.instance||(t.instance=new t),t.instance}register(e){this.tools.set(e.metadata.id,e)}registerAll(e){e.forEach(r=>this.register(r))}getAllTools(){return Array.from(this.tools.values())}getEnabledTools(e,r){let n=[];for(let[o,i]of this.tools){let{metadata:a,tool:s}=i;if(a.isAlwaysEnabled){(!a.requiresVault||r)&&n.push(s);continue}e.has(o)&&(!a.requiresVault||r)&&n.push(s)}return n}getToolsByCategory(){let e=new Map;for(let r of this.tools.values()){let n=r.metadata.category;e.has(n)||e.set(n,[]),e.get(n).push(r)}return e}getConfigurableTools(){return Array.from(this.tools.values()).filter(e=>!e.metadata.isAlwaysEnabled)}getCopilotCommandMappings(){let e=new Map;for(let r of this.tools.values()){let n=r.metadata.copilotCommands;if(n)for(let o of n){let i=o.toLowerCase();e.has(i)||e.set(i,r)}}return e}getToolMetadata(e){return this.tools.get(e)?.metadata}clear(){this.tools.clear()}}});function Glo(t){let e=new WeakSet;return JSON.stringify(t,(r,n)=>{if(typeof n=="object"&&n!==null){if(e.has(n))return"[Circular]";e.add(n)}return typeof n=="bigint"?n.toString():n},2)}function Xlo(t,e){let r=[];e&&(r.push(`msg:${e.messageId??"N/A"} | conv:${e.conversationId??"N/A"} | v${e.version}`),r.push(""));let n=bd.getInstance(),o=new Set(n.getAllTools().map(c=>c.tool.name)),i=c=>{let d=[],f=/<(\w+)>([\s\S]*?)<\/\1>/g,p;for(;(p=f.exec(c))!==null;){let m=p[1],h=p[2];if(o.has(m)){let y=h.length>200?h.substring(0,200).trim()+"...[truncated]":h.trim();d.push({tool:m,preview:y})}}return d},a=c=>typeof c.content=="string"?c.content:Array.isArray(c.content)?c.content.filter(f=>f.type==="text").map(f=>f.text).join(`
`):"",s=Array.isArray(t)?t:[],u=0;for(let c=0;c<s.length;c++){let d=s[c],f=a(d);if(d.role==="system"){r.push("\u2501\u2501\u2501 SYSTEM MESSAGE \u2501\u2501\u2501"),r.push("");let p=e?.layers.find(h=>h.id==="L1_SYSTEM"),m=e?.layers.find(h=>h.id==="L2_PREVIOUS");if(p&&f.includes(p.text)){let h=p.hash.substring(0,8);r.push(`\u{1F512} L1_SYSTEM (${h}) [CACHEABLE]`);let y=f.indexOf(p.text)+p.text.length,g=p.text.length>300?p.text.substring(0,300)+"...[truncated]":p.text;if(r.push(g),r.push(""),m&&m.text){let w=m.hash.substring(0,8);r.push(`\u{1F512} L2_PREVIOUS (${w}) [CACHEABLE]`);let O=m.text.length>300?m.text.substring(0,300)+"...[truncated]":m.text;r.push(O),r.push("")}let b=f.substring(y),_=i(b);if(_.length>0){r.push("--- PER-TURN ADDITIONS (not cached) ---"),r.push("");for(let w of _)r.push(`\u{1F4E6} TOOL: ${w.tool} (turn-specific RAG)`),r.push(w.preview),r.push("")}}else{let h=i(f);if(h.length>0){let y=f.match(/<(\w+)>/);if(y){let g=f.substring(0,y.index);if(g.trim()){let b=g.length>300?g.substring(0,300)+"...[truncated]":g;r.push(b),r.push("")}}r.push("--- PER-TURN ADDITIONS (not cached) ---"),r.push("");for(let g of h)r.push(`\u{1F4E6} TOOL: ${g.tool}`),r.push(g.preview),r.push("")}else{let y=f.length>300?f.substring(0,300)+"...[truncated]":f;r.push(y),r.push("")}}}else(d.role==="user"||d.role==="assistant")&&c<s.length-1&&u++}u>0&&(r.push("\u2501\u2501\u2501 CHAT HISTORY (L4) \u2501\u2501\u2501"),r.push(""),r.push(`${u} message(s)`),r.push(""));let l=s[s.length-1];if(l&&l.role==="user"){r.push("\u2501\u2501\u2501 USER MESSAGE \u2501\u2501\u2501"),r.push("");let c=a(l),d=i(c);if(d.length>0){r.push("--- PER-TURN TOOL RESULTS ---"),r.push("");for(let m of d)r.push(`\u{1F4E6} TOOL: ${m.tool}`),r.push(m.preview),r.push("")}let f=e?.layers.find(m=>m.id==="L3_TURN"),p=e?.layers.find(m=>m.id==="L5_USER");if(f&&f.text&&c.includes(f.text)){let m=f.hash.substring(0,8);r.push(`\u26A1 L3_TURN (${m})`);let h=f.text.length>300?f.text.substring(0,300)+"...[truncated]":f.text;r.push(h),r.push("")}if(p&&p.text&&c.includes(p.text)){let m=p.hash.substring(0,8);r.push(`\u26A1 L5_USER (${m})`),r.push(p.text),r.push("")}}return r.join(`
`)}function Sk(t){let{messages:e,modelName:r,contextEnvelope:n}=t;try{lG={timestamp:new Date().toISOString(),modelName:r,serializedMessages:Glo(e),messagesArray:e,contextEnvelope:n}}catch{lG={timestamp:new Date().toISOString(),modelName:r,serializedMessages:String(e),messagesArray:e,contextEnvelope:n}}}function cG(){lG=null}async function $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}var lG,F1=v(()=>{_t();yV();lG=null});function Ggr(t){let e=t.response_metadata||{};return e.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}}function Xgr(t){let e=t.response_metadata||{};return e.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}var Zgr=v(()=>{});function Zlo(){return 1e4}function Ylo(t,e){let r=e??Zlo();if(!t||t.length<=r)return t;let n=t.substring(0,r),o=t.length-r;return`${n}
... (truncated ${o.toLocaleString()} characters)`}function Qlo(t,e,r){let n=Ylo(e,r);return`Tool '${t}' result: ${n}`}function Got(t,e=!1){return t.map(r=>e?Qlo(r.toolName,r.result):`Tool '${r.toolName}' result: ${r.result}`).join(`
`)}function eco(t){return`<errorChunk>${t}</errorChunk>`}function dG(t,e){let r=eco(t);return e?`${e}
${r}`:`
${r}`}var LTe=v(()=>{});var T_,bV=v(()=>{Zgr();LTe();T_=class{constructor(e,r,n=!1){this.updateCurrentAiMessage=e;this.modelAdapter=r;this.excludeThinking=n;this.hasOpenThinkBlock=!1;this.fullResponse="";this.errorResponse="";this.shouldTruncate=!1;this.wasTruncated=!1;this.tokenUsage=null}handleClaudeChunk(e){let r="",n=!1;for(let o of e)switch(o.type){case"text":r+=o.text;break;case"thinking":if(n=!0,this.excludeThinking)break;this.hasOpenThinkBlock||(this.fullResponse+=`
<think>`,this.hasOpenThinkBlock=!0),o.thinking!==void 0&&(this.fullResponse+=o.thinking),this.updateCurrentAiMessage(this.fullResponse);break}return r&&this.hasOpenThinkBlock&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),r&&(this.fullResponse+=r),n}handleDeepseekChunk(e){return typeof e.content=="string"&&(this.fullResponse+=e.content),e.additional_kwargs?.reasoning_content?(this.excludeThinking||(this.hasOpenThinkBlock||(this.fullResponse+=`
<think>`,this.hasOpenThinkBlock=!0),e.additional_kwargs.reasoning_content!==void 0&&(this.fullResponse+=e.additional_kwargs.reasoning_content)),!0):!1}handleOpenRouterChunk(e){return e.additional_kwargs?.delta?.reasoning?(this.excludeThinking||(this.hasOpenThinkBlock||(this.fullResponse+=`
<think>`,this.hasOpenThinkBlock=!0),this.fullResponse+=e.additional_kwargs.delta.reasoning),!0):(typeof e.content=="string"&&e.content&&this.hasOpenThinkBlock&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),typeof e.content=="string"&&e.content&&(this.fullResponse+=e.content),!1)}processChunk(e){if(this.shouldTruncate)return;Ggr(e).wasTruncated&&(this.wasTruncated=!0);let n=Xgr(e);n&&(this.tokenUsage=n);let o=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){let r=e.lastIndexOf("</use_tool>");if(r===-1)return e;let n=e.substring(0,r+11);return this.modelAdapter?.sanitizeResponse?this.modelAdapter.sanitizeResponse(n,1):n}processErrorChunk(e){this.errorResponse=dG(e)}close(){return this.hasOpenThinkBlock&&(this.fullResponse+="</think>"),this.errorResponse&&(this.fullResponse+=this.errorResponse),this.updateCurrentAiMessage(this.fullResponse),{content:this.fullResponse,wasTruncated:this.wasTruncated,tokenUsage:this.tokenUsage}}}});var Iie,Ygr=v(()=>{Or();Mie();_t();ot();Zt();Pie();uG();F1();bV();qs();Iie=class extends L1{async constructMessages(e){if(!e.contextEnvelope)throw new Error("[LLMChainRunner] Context envelope is required but not available. Cannot proceed with LLM chain.");B("[LLMChainRunner] Using envelope-based context");let r=vR.convert(e.contextEnvelope,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),n=[],o=r.find(s=>s.role==="system");o&&n.push(o);let i=this.chainManager.memoryManager.getMemory();await wk(i,n);let a=r.find(s=>s.role==="user");if(a)if(e.content&&Array.isArray(e.content)){let s=e.content.map(u=>u.type==="text"?{...u,text:a.content}:u);n.push({role:"user",content:s})}else n.push(a);return n}async run(e,r,n,o,i){let a=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)}let l=new T_(n,void 0,u);try{let f=await this.constructMessages(e),m=this.chainManager.chatModelManager.getChatModel()?.modelName;Sk({messages:f,modelName:m,contextEnvelope:e.contextEnvelope}),B(`Final Request to AI:
`,f);let h=await rh(()=>this.chainManager.chatModelManager.getChatModel().stream(f,{signal:r.signal}));for await(let y of h){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}):await this.handleError(f,l.processErrorChunk.bind(l))}let c=l.close(),d={wasTruncated:c.wasTruncated,tokenUsage:c.tokenUsage??void 0};return r.signal.aborted&&r.signal.reason==="new-chat"?(n(""),""):(await this.handleResponse(c.content,e,r,o,n,void 0,void 0,d),c.content)}}});async function FTe(t,e){let r=`Given the following conversation and a follow up question,
summarize the conversation as context and keep the follow up question unchanged, in its original language.
If the follow up question is unrelated to its preceding messages, return this follow up question directly.
If it is related, then combine the summary and the follow up question to construct a standalone question.
Make sure to keep any [[]] wrapped note titles in the question unchanged.
If there's nothing in the chat history, just return the follow up question.
Chat History:
{chat_history}
Follow Up Input: {question}
Standalone question:`,n=e.map(({role:o,content:i})=>`${o}: ${i}`).join(`
`);return await rh(async()=>{let i=await(await Nm.instance.getCurrentChainManager().chatModelManager.getChatModelWithTemperature(0)).invoke([{role:"user",content:r.replace("{chat_history}",n).replace("{question}",t)}]),a=Az(i.content);return JW(a)})}var Xot=v(()=>{k1();Zt()});var tco,vV,kTe=v(()=>{Bo();z$();rO();Qh();tco={};Rt(tco,{BaseRetriever:()=>vV});vV=class extends Vo{constructor(e){super(e);x(this,"callbacks");x(this,"tags");x(this,"metadata");x(this,"verbose");this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,r){throw new Error("Not implemented!")}async invoke(e,r){let n=Qo(JA(r)),i=await(await rc.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,n.runId,void 0,void 0,void 0,n.runName);try{let a=await this._getRelevantDocuments(e,i);return await i?.handleRetrieverEnd(a),a}catch(a){throw await i?.handleRetrieverError(a),a}}}});var Yot,Zot,Ck,qTe=v(()=>{_t();Or();Yot=require("obsidian");Mot();Zot={maxChars:jz,overlap:0,maxBytesTotal:10*1024*1024},Ck=class{constructor(e){this.app=e;this.cache=new Map;this.memoryUsage=0;this.splitter=Sie.fromLanguage("markdown",{chunkSize:jz,chunkOverlap:0,separators:[`
`,`
`,". "," ",""],keepSeparator:!1})}async getChunks(e,r={}){try{if(!Array.isArray(e))return Be("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));let n=e.filter(a=>!(!a||typeof a!="string"||a.includes("..")||a.startsWith("/")));if(n.length===0)return Be("ChunkManager: No valid note paths provided"),[];let o={...Zot,...r},i=[];for(let a of n){let s=this.cache.get(a);if(!s&&(s=await this.generateChunksForNote(a,o),s.length>0)){let u=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)}return B(`ChunkManager: Retrieved ${i.length} chunks from ${n.length} notes (${this.formatMemoryUsage()})`),i}catch(n){return Be("ChunkManager: Failed to get chunks",n),[]}}async getChunkText(e){return(await this.ensureChunkExists(e))?.content||""}async ensureChunkExists(e){let[r]=e.split("#"),o=(await this.getValidatedChunks(r)).find(i=>i.id===e);return o||Be(`ChunkManager: Chunk ${e} not found after regeneration`),o||null}async getValidatedChunks(e){let r=this.cache.get(e);if(!r&&(B(`ChunkManager: Cache miss for ${e}, regenerating...`),r=await this.regenerateChunks(e),!r||r.length===0))return Be(`ChunkManager: Failed to regenerate chunks for ${e}`),[];let n=this.app.vault.getAbstractFileByPath(e);return n&&n instanceof Yot.TFile&&r.length>0&&n.stat.mtime>r[0].mtime&&(B(`ChunkManager: File ${e} modified, regenerating chunks`),r=await this.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);return n?n.find(i=>i.id===e)?.content||"":(Be(`ChunkManager: Chunk not in cache: ${e} (use async getChunkText for auto-regeneration)`),"")}async regenerateChunks(e){try{let r=await this.generateChunksForNote(e,Zot);if(r.length>0){let n=this.calculateChunkBytes(r);if(this.memoryUsage+n<=Zot.maxBytesTotal){let o=this.cache.get(e);o&&(this.memoryUsage-=this.calculateChunkBytes(o)),this.cache.set(e,r),this.memoryUsage+=n}else Be(`ChunkManager: Cannot cache regenerated chunks for ${e}, would exceed memory budget`)}return r}catch(r){return Be(`ChunkManager: Failed to regenerate chunks for ${e}`,r),[]}}clearCache(){this.cache.clear(),this.memoryUsage=0,B("ChunkManager: Cache cleared")}async generateChunksForNote(e,r){try{let n=this.app.vault.getAbstractFileByPath(e);if(!n||!(n instanceof Yot.TFile))return[];let o=await this.safeReadFile(n);if(!o?.trim())return[];let a=(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){let l=await this.processContentSection(o,"",n,u,r);return s.push(...l),s}for(let l=0;l<a.length;l++){let c=a[l],d=a[l+1],f=c.position.start.offset,p=d?.position.start.offset||o.length,m=o.substring(f,p),h=await this.processContentSection(m,c.heading,n,u,r);s.push(...h),u+=h.length}return s}catch(n){return Be(`ChunkManager: Failed to chunk note ${e}`,n),[]}}async processContentSection(e,r,n,o,i){let a=n.basename,s=[],u=`
NOTE TITLE: [[${a}]]
NOTE BLOCK CONTENT:
`,l=u+e;if(l.length<=i.maxChars){let c=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})}else try{(await this.splitter.createDocuments([e],[],{chunkHeader:u,appendChunkOverlapHeader:i.overlap>0})).forEach((d,f)=>{let p=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);let d=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})}return s}calculateChunkBytes(e){return e.reduce((r,n)=>r+Buffer.byteLength(n.content,"utf8"),0)}async safeReadFile(e){try{return(await this.app.vault.cachedRead(e))?.trim()||""}catch(r){return Be(`ChunkManager: Failed to read ${e.path}`,r),""}}generateChunkId(e,r){return`${e}#${r}`}calculateContentHash(e){let r=e.length.toString(16),n=e.slice(0,32).replace(/\s/g,"").substring(0,8);return r+n}formatMemoryUsage(){return`${(this.memoryUsage/1024/1024).toFixed(1)}MB`}}});var rco,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){let n=e._tree,o=Array.from(n.keys());this.set=e,this._type=r,this._path=o.length>0?[{node:n,keys:o}]:[]}next(){let e=this.dive();return this.backtrack(),e}dive(){if(this._path.length===0)return{done:!0,value:void 0};let{node:e,keys:r}=fG(this._path);if(fG(r)===Og)return{done:!1,value:this.result()};let n=e.get(fG(r));return this._path.push({node:n,keys:Array.from(n.keys())}),this.dive()}backtrack(){if(this._path.length===0)return;let e=fG(this._path).keys;e.pop(),!(e.length>0)&&(this._path.pop(),this.backtrack())}key(){return this.set._prefix+this._path.map(({keys:e})=>fG(e)).filter(e=>e!==Og).join("")}value(){return fG(this._path).node.get(Og)}result(){switch(this._type){case oyr:return this.value();case nyr:return this.key();default:return[this.key(),this.value()]}}[Symbol.iterator](){return this}},fG=t=>t[t.length-1],nco=(t,e,r)=>{let n=new Map;if(e===void 0)return n;let o=e.length+1,i=o+r,a=new Uint8Array(i*o).fill(r+1);for(let s=0;s<o;++s)a[s]=s;for(let s=1;s<i;++s)a[s*o]=s;return iyr(t,e,r,n,a,1,o,""),n},iyr=(t,e,r,n,o,i,a,s)=>{let u=i*a;e:for(let l of t.keys())if(l===Og){let c=o[u-1];c<=r&&n.set(s,[t.get(l),c])}else{let c=i;for(let d=0;d<l.length;++d,++c){let f=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(let b=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)continue e}iyr(t.get(l),e,r,n,o,c,a,s+l)}},Aie=class t{constructor(e=new Map,r=""){this._size=void 0,this._tree=e,this._prefix=r}atPrefix(e){if(!e.startsWith(this._prefix))throw new Error("Mismatched prefix");let[r,n]=zTe(this._tree,e.slice(this._prefix.length));if(r===void 0){let[o,i]=ait(n);for(let a of o.keys())if(a!==Og&&a.startsWith(i)){let s=new Map;return s.set(a.slice(i.length),o.get(a)),new t(s,e)}}return new t(r,e)}clear(){this._size=void 0,this._tree.clear()}delete(e){return this._size=void 0,oco(this._tree,e)}entries(){return new Rie(this,rco)}forEach(e){for(let[r,n]of this)e(r,n,this)}fuzzyGet(e,r){return nco(this._tree,e,r)}get(e){let r=nit(this._tree,e);return r!==void 0?r.get(Og):void 0}has(e){let r=nit(this._tree,e);return r!==void 0&&r.has(Og)}keys(){return new Rie(this,nyr)}set(e,r){if(typeof e!="string")throw new Error("key must be a string");return this._size=void 0,Qot(this._tree,e).set(Og,r),this}get size(){if(this._size)return this._size;this._size=0;let e=this.entries();for(;!e.next().done;)this._size+=1;return this._size}update(e,r){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;let n=Qot(this._tree,e);return n.set(Og,r(n.get(Og))),this}fetch(e,r){if(typeof e!=
`).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=`Analyze this search query and provide:
1. SALIENT TERMS from the original query (for ranking)
2. Alternative queries and related terms (for finding more results)
Query: "{query}"
Instructions:
SALIENT TERMS (for ranking - ONLY from original query):
- Extract meaningful words FROM THE ORIGINAL QUERY ONLY
- Include: nouns, proper nouns, technical terms, domain concepts
- Exclude: action verbs (find, search, get), pronouns (my, your), articles (the, a), prepositions (in, on, for), conjunctions (and, or)
- These terms determine search ranking - must be from original query
EXPANDED (for recall - can add new related terms):
- Alternative phrasings of the query
- Related/synonym terms to find more documents
Example: "find my piano notes"
- Salient (from original): piano, notes
- Expanded queries: "piano lesson notes", "piano practice sheets"
- Expanded terms: music, sheet, practice, lesson
Example: "\u67E5\u627E\u6211\u7684\u5B66\u4E60\u7B14\u8BB0"
- Salient (from original): \u5B66\u4E60, \u7B14\u8BB0
- Expanded queries: "\u4E2A\u4EBA\u7B14\u8BB0\u6587\u6863"
- Expanded terms: \u6587\u6863, \u8BB0\u5F55, \u8D44\u6599
Format:
<salient>
<term>word_from_original_query</term>
</salient>
<queries>
<query>alternative query</query>
</queries>
<expanded>
<term>related_term_for_recall</term>
</expanded>`;KTe=GTe});var jie,XTe,hyr=v(()=>{_t();vb();jie=class jie{constructor(e){this.app=e}async batchCachedReadGrep(e,r){let{inclusions:n,exclusions:o}=Xc(),a=this.app.vault.getMarkdownFiles().filter(d=>bl(d,n,o)),s=new Set,u=jie.CONFIG.BATCH_SIZE,l=e.map(d=>d.toLowerCase());for(let d=0;d<a.length&&s.size<r;d+=u){let f=a.slice(d,d+u);await Promise.all(f.map(async p=>{if(!(s.size>=r))try{let m=p.path.toLowerCase(),h=!1;for(let y of l)if(m.includes(y)){s.add(p.path),h=!0;break}if(!h){let g=(await this.app.vault.cachedRead(p)).toLowerCase();for(let b of l)if(g.includes(b)){s.add(p.path);break}}}catch(m){B(`GrepScanner: Skipping file ${p.path}: ${m}`)}})),d%jie.CONFIG.YIELD_INTERVAL===0&&await new Promise(p=>setTimeout(p,0))}let c=Array.from(s).slice(0,r);return c.length>0&&B(` Grep: ${c.length} files match [${e.slice(0,3).join(", ")}${e.length>3?"...":""}]`),c}async grep(e,r=200){return this.batchCachedReadGrep([e],r)}async fileContainsAny(e,r){try{let n=e.path.toLowerCase(),o=0;for(let s of r)n.includes(s.toLowerCase())&&o++;if(o>0)return!0;let a=(await this.app.vault.cachedRead(e)).toLowerCase();return r.some(s=>a.includes(s.toLowerCase()))}catch{return!1}}};jie.CONFIG={BATCH_SIZE:30,YIELD_INTERVAL:100};XTe=jie});var pco,ZTe,gyr=v(()=>{_t();pco={enabled:!0,minDocsForBoost:2,maxBoostFactor:1.15,minRelevanceRatio:.4},ZTe=class{constructor(e){this.config=pco;this.app=e||null}setConfig(e){this.config={...this.config,...e}}applyBoosts(e){if(!this.config.enabled||e.length===0)return e;let r=this.calculateFolderStats(e);return this.logBoostedFolders(r),e.map(n=>{let o=this.extractFolder(n.id),i=r.get(o);if(i){let a=n.score*i.boostFactor;return{...n,score:a,explanation:n.explanation?{...n.explanation,folderBoost:{folder:i.folderPath,documentCount:i.documentCount,totalDocsInFolder:i.totalDocsInFolder,relevanceRatio:i.relevanceRatio,boostFactor:i.boostFactor},finalScore:a}:void 0}}return n})}calculateFolderStats(e){let r=new Map;for(let i of e){let a=this.extractFolder(i.id);r.set(a,(r.get(a)||0)+1)}let n=this.getTotalDocsPerFolder(),o=new Map;for(let[i,a]of r.entries()){let s=n.get(i)||a,u=a/s;if(a>=this.config.minDocsForBoost&&u>=this.config.minRelevanceRatio){let c=1+(1+Math.log2(a+1)-1)*Math.sqrt(u),d=Math.min(c,this.config.maxBoostFactor);o.set(i,{folderPath:i,documentCount:a,totalDocsInFolder:s,relevanceRatio:u,boostFactor:d})}}return o}getTotalDocsPerFolder(){let e=new Map;if(!this.app)return e;let r=this.app.vault.getMarkdownFiles();for(let n of r){let o=this.extractFolder(n.path);e.set(o,(e.get(o)||0)+1)}return e}extractFolder(e){return e.substring(0,e.lastIndexOf("/"))||""}logBoostedFolders(e){let r=Array.from(e.values()).sort((n,o)=>o.relevanceRatio-n.relevanceRatio);r.length>0&&(B(`Folder boost: Boosting ${r.length} folders with significant relevance`),r.slice(0,5).forEach(n=>{let o=(n.relevanceRatio*100).toFixed(1);B(` ${n.folderPath||"(root)"}: ${n.documentCount}/${n.totalDocsInFolder} docs (${o}% relevant, ${n.boostFactor.toFixed(2)}x boost)`)}))}getFolderBoosts(e){return this.config.enabled?this.calculateFolderStats(e):new Map}}});var mco,YTe,yyr=v(()=>{_t();mco={enabled:!0,maxCandidates:10,backlinkWeight:1,coCitationWeight:.5,sharedTagWeight:.3,boostStrength:.1,maxBoostMultiplier:1.2},YTe=class{constructor(e,r={}){this.metadataCache=e.metadataCache,this.config={...mco,...r}}applyBoost(e){if(!this.config.enabled||e.length===0)return e;let r=this.filterCandidates(e);if(r.length<2)return e;let n=new Set(r.map(s=>s.id)),o=new Map;for(let s of r){let u=this.calculateConnections(s.id,n);o.set(s.id,u)}let i=e.map(s=>{let u=o.get(s.id);return!u||u.boostMultiplier===1?s:{...s,score:s.score*u.boostMultiplier,explanation:s.explanation?{...s.explanation,graphConnections:{backlinks:u.backlinks.length,coCitations:u.coCitations.length,sharedTags:u.sharedTags.length,score:u.connectionScore,boostMultiplier:u.boostMultiplier}}:void 0}}),a=i.filter(s=>{let u=o.get(s.id);return u&&u.boostMultiplier>1});return a.length>0&&B(`GraphBoostCalculator: Boosted ${a.length} notes based on connections`),i}calculateConnections(e,r){let
`))}if(r.protocol==="http:"||r.protocol==="https:")return{type:"url",url:t};throw new Error([`Invalid image URL protocol: ${JSON.stringify(r.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
`))}function 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(`Message type "${i.type}" is not supported.`);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:{
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
`,t}function yit(t){let e;return t.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}var Wyr=v(()=>{});function fr(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 Me(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 q1=v(()=>{});var bit,Kyr=v(()=>{bit=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return bit=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 U1(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var Fie,gG=v(()=>{Fie=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 nn,_h,Tg,xk,yG,bG,_G,vG,wG,SG,CG,xG,OG,VC=v(()=>{gG();nn=class extends Error{},_h=class t extends nn{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}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} status code (no body)`:o||"(no status code or body)"}static generate(e,r,n,o){if(!e||!o)return new xk({message:n,cause:Fie(r)});let i=r;return e===400?new bG(e,i,n,o):e===401?new _G(e,i,n,o):e===403?new vG(e,i,n,o):e===404?new wG(e,i,n,o):e===409?new SG(e,i,n,o):e===422?new CG(e,i,n,o):e===429?new xG(e,i,n,o):e>=500?new OG(e,i,n,o):new t(e,i,n,o)}},Tg=class extends _h{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},xk=class extends _h{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},yG=class extends xk{constructor({message:e}={}){super({message:e??"Request timed out."})}},bG=class extends _h{},_G=class extends _h{},vG=class extends _h{},wG=class extends _h{},SG=class extends _h{},CG=class extends _h{},xG=class extends _h{},OG=class extends _h{}});function wit(t){return typeof t!="object"?{}:t??{}}function Xyr(t){if(!t)return!0;for(let e in t)return!1;return!0}function Zyr(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var Sco,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(typeof e!="number"||!Number.isInteger(e))throw new nn(`${t} must be an integer`);if(e<0)throw new nn(`${t} must be a positive integer`);return e},oEe=t=>{try{return JSON.parse(t)}catch{return}}});var Qyr,ebr=v(()=>{Qyr=t=>new Promise(e=>setTimeout(e,t))});var Ok,Sit=v(()=>{Ok="0.65.0"});function Cco(){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 Oco(){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+
`):[]}};Qv=new WeakMap,ew=new WeakMap;B1.NEWLINE_CHARS=new Set([`
`,"\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} was set to ${JSON.stringify(t)}, expected one of ${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)+`
`);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};Mit=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=Aco(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function lEe(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:o,startTime:i}=e,a=await(async()=>{if(e.options.stream)return vh(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller):wR.fromSSEResponse(r,e.controller);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let u=r.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){let d=await r.json();return Rit(d,r)}return await r.text()})();return vh(t).debug(`[${n}] response parsed`,z1({retryOfRequestLogID:o,url:r.url,status:r.status,body:a,durationMs:Date.now()-i})),a}function Rit(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var Ait=v(()=>{Iit();uEe()});var zie,xV,cEe=v(()=>{q1();Ait();xV=class t extends Promise{constructor(e,r,n=lEe){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,zie.set(this,void 0),fr(this,zie,e,"f")}_thenUnwrap(e){return new t(Me(this,zie,"f"),this.responsePromise,async(r,n)=>Rit(e(await this.parseResponse(r,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(Me(this,zie,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};zie=new WeakMap});var dEe,Nit,Vie,LS,Tk=v(()=>{q1();VC();Ait();cEe();CV();Nit=class{constructor(e,r,n,o){dEe.set(this,void 0),fr(this,dEe,e,"f"),this.options=o,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new nn("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await Me(this,dEe,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(dEe=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},Vie=class extends xV{constructor(e,r,n){super(e,r,async(o,i)=>new n(o,i.response,await lEe(o,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},LS=class extends Nit{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let r=this.first_id;return r?{...this.options,query:{...wit(this.options.query),before_id:r}}:null}let e=this.last_id;return e?{...this.options,query:{...wit(this.options.query),after_id:e}}:null}}});function OV(t,e,r){return Dit(),new File(t,e??"unknown_file",r)}function Hie(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}function jco(t){let e=typeof t=="function"?t:t.fetch,r=hbr.get(e);if(r)return r;let n=(async()=>{try{let o="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new o(i).text()}catch{return!0}})();return hbr.set(e,n),n}var Dit,$it,gbr,hbr,Dco,$co,jit,fEe=v(()=>{TG();Dit=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versi
${i.map(f=>f.error).join(`
`)}
${a}
${d}`)}return a},Cy=Bco(Sbr)});var PG,kit=v(()=>{SR();Tk();CR();fEe();EG();PG=class extends _d{list(e={},r){let{betas:n,...o}=e??{};return this._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??{};return this._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??{};return this._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??{};return this._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;return this._client.post("/v1/files",gbr({body:o,...r,headers:ea([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},r?.headers])},this._client))}}});var MG,qit=v(()=>{SR();Tk();CR();EG();MG=class extends _d{retrieve(e,r={},n){let{betas:o}=r??{};return this._client.get(Cy`/v1/models/${e}?beta=true`,{...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?beta=true",LS,{query:o,...r,headers:ea([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers])})}}});var IG,Uit=v(()=>{VC();TG();Eit();IG=class t{constructor(e,r){this.iterator=e,this.controller=r}async*decoder(){let e=new B1;for await(let r of this.iterator)for(let n of e.decode(r))yield JSON.parse(n);for(let r of e.flush())yield JSON.parse(r)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,r){if(!e.body)throw r.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");return new t(kie(e.body),r)}}});var Jie=v(()=>{VC()});var RG,Bit=v(()=>{SR();Tk();CR();Uit();Jie();EG();RG=class extends _d{create(e,r){let{betas:n,...o}=e;return this._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??{};return this._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??{};return this._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??{};return this._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??{};return this._client.post(Cy`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:ea([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString()},n?.headers])})}async results(e,r={},n){let o=await this.retrieve(e);if(!o.results_url)throw new nn(`No batch \`results_url\`; Has it finished processing? ${o.processing_status} - ${o.id}`);let{betas:i}=r??{};return this._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))}}});var zit=v(()=>{Iit()});var Jco,AG,Wco,Kco,mEe,Vit=v(()=>{Jco=t=>{let e=0,r=[];for(;e<t.length;){let n=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+
Please migrate to a newer model. Visit https://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
Please migrate to a newer model. Visit https://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 is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
`);this.baseURL=i.baseURL,this.timeout=i.timeout??cat.DEFAULT_TIMEOUT,this.logger=i.logger??console;let a="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){return new this.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(){return this._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"))throw new Error('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')}async authHeaders(e){return ea([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return ea([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return ea([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([r,n])=>typeof n<"u").map(([r,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(r)}=`;throw new nn(`Cannot stringify type ${typeof n}; 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){let o=!Me(this,lat,"m",Fbr).call(this)&&n||this.baseURL,i=Gyr(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return Xyr(a)||(r={...a,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(i.search=this.stringifyQuery(r)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new nn("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");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(o=>({method:e,path:r,...o})))}request(e,r=null){return new xV(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let o=await e,i=o.maxRetries??this.maxRetries;r==null&&(r=i),await this.prepareOptions(o);let{req:a,url:s,timeout:u}=await this.buildRequest(o,{retryCount:i-r});await this.prepareRequest(a,{url:s,options:o});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),c=n===void 0?"":`, 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)throw new Tg;let f=new AbortController,p=await this.fetchWithTimeout(s,a,u,f).catch(Fie),m=Date.now();if(p instanceof globalThis.Error){let g=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new Tg;let b=U1(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(r)return vh(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
`);o.enqueue(s)}catch(i){o.error(i)}},async cancel(){await r.return?.()}})}},Sat=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=mdo(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},qG=class t{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){let r=this.decodeText(e);if(this.trailingCR&&(r="\r"+r,this.trailingCR=!1),r.endsWith("\r")&&(this.trailingCR=!0,r=r.slice(0,-1)),!r)return[];let n=t.NEWLINE_CHARS.has(r[r.length-1]||""),o=r.split(t.NEWLINE_REGEXP);return 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){if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new Eg(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new Eg(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new Eg("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}};qG.NEWLINE_CHARS=new Set([`
`,"\r","\v","\f","","","","\x85","\u2028","\u2029"]);qG.NEWLINE_REGEXP=/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g});async function Oat(t,e,r){if(t=await t,i_r(t))return t;if(o_r(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=gae(o)?[await o.arrayBuffer()]:[o];return new NEe(i,e,r)}let n=await gdo(t);if(e||(e=bdo(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new NEe(n,e,r)}async function gdo(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(gae(t))e.push(await t.arrayBuffer());else if(_do(t))for await(let r of t)e.push(r);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${ydo(t)}`);return e}function ydo(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function bdo(t){return Cat(t.name)||Cat(t.filename)||Cat(t.path)?.split(/[\\/]/).pop()}var o_r,i_r,gae,hdo,Cat,_do,Tat,AV,a_r,xat,FEe=v(()=>{aae();aae();o_r=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",i_r=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&gae(t),gae=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",hdo=t=>i_r(t)||o_r(t)||_at(t);Cat=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},_do=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Tat=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody",AV=async t=>{let e=await a_r(t.body);return yat(e,t)},a_r=async t=>{let e=new hat;return await Promise.all(Object.entries(t||{}).map(([r,n])=>xat(e,r,n))),e},xat=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(hdo(r)){let n=await Oat(r);t.append(e,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>xat(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>xat(t,`${e}[${n}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}}});async function f_r(t){let{response:e}=t;if(t.options.stream)return UG("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):LEe.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 UG("response",e.status,e.url,e.headers,a),a}let i=await e.text();return UG("response",e.status,e.url,e.headers,i),i}function Odo(){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 Rdo(t){if(!t)return!0;for(let e in t)return!1;return!0}function Ado(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function d_r(t,e){for(let r in e){if(!Ado(e,r))continue;let n=r.toLowerCase();if(!n)continue;let o=e[r];o===null?delete t[n]:o!==void 0&&(t[n]=o)}}function UG(t,...e){typeof process<"u"&&process?.env?.DEBUG==="true"&&console.log(`Groq:DEBUG:${t}`,...e)}var wdo,Sdo,kEe,UEe,BEe,s_r,Pat,Cdo,xdo,u_r,l_r,c_r,Tdo,Edo,P
This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
new Groq({ apiKey, dangerouslyAllowBrowser: true })`);super({baseURL:o.baseURL,timeout:o.timeout??6e4,httpAgent:o.httpAgent,maxRetries:o.maxRetries,fetch:o.fetch}),this.completions=new jV(this),this.chat=new Nk(this),this.embeddings=new DV(this),this.audio=new ER(this),this.models=new LV(this),this.batches=new NV(this),this.files=new $V(this),this._options=o,this.apiKey=r}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}};g_r=hu;hu.Groq=g_r;hu.DEFAULT_TIMEOUT=6e4;hu.GroqError=Eg;hu.APIError=wh;hu.APIConnectionError=Ak;hu.APIConnectionTimeoutError=FG;hu.APIUserAbortError=RV;hu.NotFoundError=cae;hu.ConflictError=dae;hu.RateLimitError=pae;hu.BadRequestError=sae;hu.AuthenticationError=uae;hu.InternalServerError=mae;hu.PermissionDeniedError=lae;hu.UnprocessableEntityError=fae;hu.toFile=Oat;hu.fileFromPath=jEe;hu.Completions=jV;hu.Chat=Nk;hu.Embeddings=DV;hu.Audio=ER;hu.Models=LV;hu.Batches=NV;hu.Files=$V;y_r=hu});function zdo(t){if(t.role!=="system"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function")throw new Error(`Unsupported message role: ${t.role}. Expected "system", "assistant", "user", or "function"`);return t.role}function v_r(t){switch(t.type){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!nd.isInstance(t))throw new Error("Invalid generic chat message");return zdo(t);default:throw new Error(`Unknown message type: ${t.type}`)}}function __r(t){return t.map(e=>{let r={role:v_r(e),content:e.content,name:e.name,function_call:e.additional_kwargs.function_call,tool_calls:e.additional_kwargs.tool_calls,tool_call_id:e.tool_call_id};return Pl(e)&&e.tool_calls?.length?r.tool_calls=e.tool_calls.map(ck):(e.additional_kwargs.tool_calls!=null&&(r.tool_calls=e.additional_kwargs.tool_calls),e.tool_call_id!=null&&(r.tool_call_id=e.tool_call_id)),r})}function Vdo(t,e,r){let n=t.tool_calls;switch(t.role){case"assistant":{let o=[],i=[];for(let a of n??[])try{o.push(kC(a,{returnId:!0}))}catch(s){i.push(AS(a,s.message))}return new eo({content:t.content||"",additional_kwargs:{tool_calls:n},tool_calls:o,invalid_tool_calls:i,usage_metadata:e,response_metadata:r})}default:return new nd(t.content||"",t.role??"unknown")}}function Hdo(t,e,r,n){let o=t.role??e,i=t.content??"",a;t.function_call?a={function_call:t.function_call}:t.tool_calls?a={tool_calls:t.tool_calls}:a={},t.audio&&(a.audio={...t.audio,index:r.choices[0].index});let s,u=n,l,c=r.x_groq;c?.usage&&(s={input_tokens:c.usage.prompt_tokens,output_tokens:c.usage.completion_tokens,total_tokens:c.usage.total_tokens},l={completion_time:c.usage.completion_time,prompt_time:c.usage.prompt_time,queue_time:c.usage.queue_time,total_time:c.usage.total_time}),c?.id&&(u=c.id);let d={usage:s,timing:l};if(o==="user")return new mv({content:i,response_metadata:d});if(o==="assistant"){let f=[];if(Array.isArray(t.tool_calls))for(let p of t.tool_calls)f.push({name:p.function?.name,args:p.function?.arguments,id:p.id,index:p.index,type:"tool_call_chunk"});return new Ir({content:i,tool_call_chunks:f,additional_kwargs:a,id:u,response_metadata:d})}else return o==="system"?new Wy({content:i,response_metadata:d}):o==="developer"?new Wy({content:i,response_metadata:d,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new pv({content:i,additional_kwargs:a,name:t.name,response_metadata:d}):o==="tool"?new Iw({content:i,additional_kwargs:a,tool_call_id:t.tool_call_id,response_metadata:d}):new fv({content:i,role:o,response_metadata:d})}function Jdo(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}var qdo,Udo,Bdo,Uat,w_r=v(()=>{nb();YI();Qa();id();ku();Wv();b_r();_v();fO();$8();g1();qdo=["frequency_penalty","function_call","functions","logit_bias","logprobs","max_completion_tokens","max_tokens","n","parallel_tool_calls","presence_penalty","reasoning_format"
${xst(this.cause)}`:this.toString()}};WC.SDKValidationError=Cst;function xst(t,e=0){let r=" ".repeat(e);r=e>0?`\u2502${r}`:r,r+=" ".repeat(e);let n="",o=s=>n+=`
${r}${s}`,i=t.issues.length,a=i===1?`${i} issue found`:`${i} issues found`;i&&o(`\u250C ${a}:`);for(let s of t.issues){let u=s.path.join(".");switch(u=u?`<root>.${u}`:"<root>",o(`\u2502 \u2022 [${u}]: ${s.message} (${s.code})`),s.code){case"invalid_literal":case"invalid_type":{o(`\u2502 Want: ${s.expected}`),o(`\u2502 Got: ${s.received}`);break}case"unrecognized_keys":{o(`\u2502 Keys: ${s.keys.join(", ")}`);break}case"invalid_enum_value":{o(`\u2502 Allowed: ${s.options.join(", ")}`),o(`\u2502 Got: ${s.received}`);break}case"invalid_union_discriminator":{o(`\u2502 Allowed: ${s.options.join(", ")}`);break}case"invalid_union":{let l=s.unionErrors.length;o(`\u2502 \u2716\uFE0E Attemped to deserialize into one of ${l} union members:`),s.unionErrors.forEach((c,d)=>{o(`\u2502 \u2716\uFE0E Member ${d+1} of ${l}`),o(`${xst(c,e+1)}`)})}}}return t.issues.length&&o("\u2514\u2500*"),n.slice(1)}});var Tst=S(NR=>{"use strict";var Omo=NR&&NR.__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]}),Tmo=NR&&NR.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Emo=NR&&NR.__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"&&Omo(r,e,n[o]);return Tmo(r,e),r}}();Object.defineProperty(NR,"__esModule",{value:!0});NR.ResponseValidationError=void 0;var Pmo=Emo(Q()),Mmo=dPe(),Imo=fPe(),Ost=class extends Mmo.MistralError{constructor(e,r){super(e,r),this.name="ResponseValidationError",this.cause=r.cause,this.rawValue=r.rawValue,this.rawMessage=r.rawMessage}pretty(){return this.cause instanceof Pmo.ZodError?`${this.rawMessage}
${(0,Imo.formatZodError)(this.cause)}`:this.toString()}};NR.ResponseValidationError=Ost});var Pst=S(pPe=>{"use strict";Object.defineProperty(pPe,"__esModule",{value:!0});pPe.SDKError=void 0;var Rmo=dPe(),Est=class extends Rmo.MistralError{constructor(e,r){e&&(e+=": "),e+=`Status ${r.response.status}`;let n=r.response.headers.get("content-type")||'""';n!=="application/json"&&(e+=` Content-Type ${n.includes(" ")?`"${n}"`:n}`);let o=r.body||'""';e+=o.length>100?`
`:". ";let i=o;if(o.length>1e4){let a=o.substring(0,1e4),s=o.length-1e4;i=`${a}...and ${s} more chars`}e+=`Body: ${i}`,e=e.trim(),super(e,r),this.name="SDKError"}};pPe.SDKError=Est});var pr=S(Dm=>{"use strict";Object.defineProperty(Dm,"__esModule",{value:!0});Dm.jsonErr=jmo;Dm.json=Dmo;Dm.jsonl=$mo;Dm.jsonlErr=Lmo;Dm.textErr=Fmo;Dm.text=kmo;Dm.bytesErr=qmo;Dm.bytes=Umo;Dm.streamErr=Bmo;Dm.stream=zmo;Dm.sseErr=Vmo;Dm.sse=Hmo;Dm.nilErr=Jmo;Dm.nil=Wmo;Dm.fail=Kmo;Dm.match=Gmo;Dm.unpackHeaders=mPe;var Amo=Tst(),wvr=Pst(),Svr=vd(),Cvr=WG(),xvr=hst(),Nmo={jsonl:"application/jsonl",json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function jmo(t,e,r){return{...r,err:!0,enc:"json",codes:t,schema:e}}function Dmo(t,e,r){return{...r,enc:"json",codes:t,schema:e}}function $mo(t,e,r){return{...r,enc:"jsonl",codes:t,schema:e}}function Lmo(t,e,r){return{...r,err:!0,enc:"jsonl",codes:t,schema:e}}function Fmo(t,e,r){return{...r,err:!0,enc:"text",codes:t,schema:e}}function kmo(t,e,r){return{...r,enc:"text",codes:t,schema:e}}function qmo(t,e,r){return{...r,err:!0,enc:"bytes",codes:t,schema:e}}function Umo(t,e,r){return{...r,enc:"bytes",codes:t,schema:e}}function Bmo(t,e,r){return{...r,err:!0,enc:"stream",codes:t,schema:e}}function zmo(t,e,r){return{...r,enc:"stream",codes:t,schema:e}}function Vmo(t,e,r){return{...r,err:!0,enc:"sse",codes:t,schema:e}}function Hmo(t,e,r){return{...r,enc:"sse",codes:t,schema:e}}function Jmo(t,e,r){return{...r,err:!0,enc:"nil",codes:t,schema:e}}function Wmo(t,e,r){return{...r,enc:"nil",codes:t,schema:e}}function Kmo(t){return{enc:"fail",codes:t}}function Gmo(...t){return async function(r,n,o){let i,a;for(let d of t){let{codes:f}=d,p="ctype"in d?d.ctype:Nmo[d.enc];if(p&&(0,Cvr.matchResponse)(r,f,p)){a=d;break}else if(!p&&(0,Cvr.matchStatusCode)(r,f)){a=d;break}}if(!a)return[{ok:!1,error:new wvr.SDKError("Unexpected Status or Content-Type",{response:r,request:n,body:await r.text().catch(()=>"")})},i];let s=a.enc,u="";switch(s){case"json":u=await r.text(),i=JSON.parse(u);break;case"jsonl":i=r.body;break;case"bytes":i=new Uint8Array(await r.arrayBuffer());break;case"stream":i=r.body;break;case"text":u=await r.text(),i=u;break;case"sse":i=r.body;break;case"nil":u=await r.text(),i=void 0;break;case"fail":u=await r.text(),i=u;break;default:throw new Error(`Unsupported response type: ${s}`)}if(a.enc==="fail")return[{ok:!1,error:new wvr.SDKError("API error occurred",{request:n,response:r,body:u})},i];let l=a.key||o?.resultKey,c;if("err"in a?c={...o?.extraFields,...a.hdrs?{Headers:mPe(r.headers)}:null,...(0,xvr.isPlainObject)(i)?i:null,request$:n,response$:r,body$:u}:l?c={...o?.extraFields,...a.hdrs?{Headers:mPe(r.headers)}:null,[l]:i}:a.hdrs?c={...o?.extraFields,...a.hdrs?{Headers:mPe(r.headers)}:null,...(0,xvr.isPlainObject)(i)?i:null}:c=i,"err"in a){let d=Ovr(c,f=>a.schema.parse(f),"Response validation failed",{request:n,response:r,body:u});return[d.ok?{ok:!1,error:d.value}:d,i]}else return[Ovr(c,d=>a.schema.parse(d),"Response validation failed",{request:n,response:r,body:u}),i]}}var Xmo=/, */;function mPe(t){let e={};for(let[r,n]of t.entries())e[r]=n.split(Xmo);return e}function Ovr(t,e,r,n){try{return(0,Svr.OK)(e(t))}catch(o){return(0,Svr.ERR)(new Amo.ResponseValidationError(r,{cause:o,rawValue:t,rawMessage:r,...n}))}}});var le=S(Bk=>{"use strict";Object.defineProperty(Bk,"__esModule",{value:!0});Bk.invariant=Zmo;Bk.remap=Ymo;Bk.combineSignals=Qmo;Bk.abortSignalAny=Tvr;Bk.compactMap=eho;Bk.allRequired=tho;var Mst=class extends Error{constructor(e){super(e),this.name="InvariantError"}};function Zmo(t,e){if(!t)throw new Mst(e)}function Ymo(t,e){let r={};if(!Object.keys(e).length)return r=t,r;for(let[n,o]of Object.entries(t)){let i=e[n];i!==null&&(r[i??n]=o)}return r}function Qmo(...t){let e=[];for(let r of t)r&&e.push(r);switch(e.length){case 0:case 1:return e[0]||null;default:return"any"in AbortSignal&&typeof AbortSignal.any=="function"?AbortSignal.any(e):Tvr(e)}}function Tvr(t){let e=new AbortController,r=e.signal;i
`)),e(i)}});var dNr=S(sj=>{"use strict";var ADo=sj&&sj.__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]}),NDo=sj&&sj.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),mRe=sj&&sj.__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"&&ADo(r,e,n[o]);return NDo(r,e),r}}();Object.defineProperty(sj,"__esModule",{value:!0});sj.agentsStream=BDo;var jDo=mRe(Q()),DDo=wr(),$Do=pq(),Wae=mRe(pr()),LDo=le(),FDo=Z(),lNr=mr(),kDo=cr(),cNr=mRe(kt()),qDo=mRe(Gn()),UDo=hr();function BDo(t,e,r){return new UDo.APIPromise(zDo(t,e,r))}async function zDo(t,e,r){let n=(0,FDo.safeParse)(e,b=>cNr.AgentsCompletionStreamRequest$outboundSchema.parse(b),"Input validation failed");if(!n.ok)return[n,{status:"invalid"}];let o=n.value,i=(0,DDo.encodeJSON)("body",o,{explode:!0}),a=(0,kDo.pathToFunc)("/v1/agents/completions#stream")(),s=new Headers((0,LDo.compactMap)({"Content-Type":"application/json",Accept:"text/event-stream"})),u=await(0,lNr.extractSecurity)(t._options.apiKey),l=u==null?{}:{apiKey:u},c=(0,lNr.resolveGlobalSecurity)(l),d={options:t._options,baseURL:r?.serverURL??t._baseURL??"",operationID:"stream_agents",oAuth2Scopes:[],resolvedSecurity:c,securitySource:t._options.apiKey,retryConfig:r?.retries||t._options.retryConfig||{strategy:"none"},retryCodes:r?.retryCodes||["429","500","502","503","504"]},f=t._createRequest(d,{security:c,method:"POST",baseURL:r?.serverURL,path:a,headers:s,body:i,userAgent:t._options.userAgent,timeoutMs:r?.timeoutMs||t._options.timeoutMs||-1},r);if(!f.ok)return[f,{status:"invalid"}];let p=f.value,m=await t._do(p,{context:d,errorCodes:["422","4XX","5XX"],retryConfig:d.retryConfig,retryCodes:d.retryCodes});if(!m.ok)return[m,{status:"request-error",request:p}];let h=m.value,y={HttpMeta:{Response:h,Request:p}},[g]=await Wae.match(Wae.sse(200,jDo.instanceof(ReadableStream).transform(b=>new $Do.EventStream(b,_=>_.data==="[DONE]"?{done:!0}:{value:cNr.CompletionEvent$inboundSchema.parse(_)}))),Wae.jsonErr(422,qDo.HTTPValidationError$inboundSchema),Wae.fail("4XX"),Wae.fail("5XX"))(h,p,{extraFields:y});return g.ok?[g,{status:"complete",request:p,response:h}]:[g,{status:"complete",request:p,response:h}]}});var pNr=S(hRe=>{"use strict";Object.defineProperty(hRe,"__esModule",{value:!0});hRe.Agents=void 0;var VDo=uNr(),HDo=dNr(),JDo=Rc(),fNr=vd(),elt=class extends JDo.ClientSDK{async complete(e,r){return(0,fNr.unwrapAsync)((0,VDo.agentsComplete)(this,e,r))}async stream(e,r){return(0,fNr.unwrapAsync)((0,HDo.agentsStream)(this,e,r))}};hRe.Agents=elt});var Kae=S(tlt=>{"use strict";Object.defineProperty(tlt,"__esModule",{value:!0});tlt.isReadableStream=WDo;function WDo(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.getReader=="function"&&typeof e.cancel=="function"&&typeof e.tee=="function"}});var yNr=S(uj=>{"use strict";var KDo=uj&&uj.__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]}),GDo=uj&&uj.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),gNr=uj&&uj.__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)f
]))`;continue}else if(n[u]==="$"){o+=`($|(?=[\r
]))`;continue}}if(r.s&&n[u]==="."){o+=a?`${n[u]}\r
`:`[${n[u]}\r
]`;continue}o+=n[u],n[u]==="\\"?i=!0:a&&n[u]==="]"?a=!1:!a&&n[u]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}});var eNe=S(QAe=>{"use strict";Object.defineProperty(QAe,"__esModule",{value:!0});QAe.parseRecordDef=void 0;var jse=Q(),cFr=rm(),XWo=YAe(),ZWo=VAe();function YWo(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===jse.ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:(0,cFr.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:(0,cFr.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===jse.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=(0,XWo.parseStringDef)(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===jse.ZodFirstPartyTypeKind.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===jse.ZodFirstPartyTypeKind.ZodBranded&&t.keyType._def.type._def.typeName===jse.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=(0,ZWo.parseBrandedDef)(t.keyType._def,e);return{...r,propertyNames:o}}}return r}QAe.parseRecordDef=YWo});var qlt=S(tNe=>{"use strict";Object.defineProperty(tNe,"__esModule",{value:!0});tNe.parseMapDef=void 0;var dFr=rm(),QWo=eNe();function e6o(t,e){if(e.mapStrategy==="record")return(0,QWo.parseRecordDef)(t,e);let r=(0,dFr.parseDef)(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=(0,dFr.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}tNe.parseMapDef=e6o});var Ult=S(rNe=>{"use strict";Object.defineProperty(rNe,"__esModule",{value:!0});rNe.parseNativeEnumDef=void 0;function t6o(t){let e=t.values,n=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}rNe.parseNativeEnumDef=t6o});var Blt=S(nNe=>{"use strict";Object.defineProperty(nNe,"__esModule",{value:!0});nNe.parseNeverDef=void 0;function r6o(){return{not:{}}}nNe.parseNeverDef=r6o});var zlt=S(oNe=>{"use strict";Object.defineProperty(oNe,"__esModule",{value:!0});oNe.parseNullDef=void 0;function n6o(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}oNe.parseNullDef=n6o});var iNe=S(yq=>{"use strict";Object.defineProperty(yq,"__esModule",{value:!0});yq.parseUnionDef=yq.primitiveMappings=void 0;var o6o=rm();yq.primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function i6o(t,e){if(e.target==="openApi3")return fFr(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in yq.primitiveMappings&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=yq.primitiveMappings[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((i,a,s)=>s.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(n
Received: ${JSON.stringify(i,null,2)}`)};if(typeof i=="string")return i;if(Array.isArray(i)){let u=e(a),l=[];return i.forEach(c=>{if(c.type==="text"||c.type==="image_url")l.push(s(c,u));else throw new Error('Mistral only supports types "text" or "image_url" for complex message types.')}),l}throw new Error(`Message content must be a string or an array.
Received: ${JSON.stringify(i,null,2)}`)},n=i=>{if(Pl(i)&&i.tool_calls?.length)return i.tool_calls.map(a=>({...a,id:yae(a.id??"")})).map(ck)},o=new Set;for(let i of t)"tool_call_id"in i&&typeof i.tool_call_id=="string"&&o.add(yae(i.tool_call_id));return t.flatMap(i=>{let a=n(i),s=r(i.content,i.getType());if("tool_call_id"in i&&typeof i.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===void 0)return[{role:e(i.getType()),content:s}];{let u=a.filter(l=>o.has(yae(l.id??"")));return u.length===0?typeof s=="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}]})}function Z7o(t,e){let{message:r}=t;if(r===void 0)throw new Error("No message found in response");let n=[];"toolCalls"in r&&Array.isArray(r.toolCalls)&&(n=r.toolCalls);let o=Bat(r.content);switch(r.role){case"assistant":{let i=[],a=[];for(let s of n)try{let u=kC(s,{returnId:!0});i.push({...u,id:u.id??JEe().replace(/-/g,"")})}catch(u){a.push(AS(s,u.message))}return new eo({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}:void 0})}default:return new Hs({content:o})}}function Y7o(t,e){if(!t.content&&!t.toolCalls)return e?new Ir({content:"",usage_metadata:e?{input_tokens:e.promptTokens,output_tokens:e.completionTokens,total_tokens:e.totalTokens}:void 0}):null;let r=t.toolCalls?.length?t.toolCalls?.map((s,u)=>({...s,index:u,id:s.id??JEe().replace(/-/g,""),type:"function"})):void 0,n="assistant";t.role&&(n=t.role);let o=Bat(t.content),i,a=[];if(r!==void 0)for(let s of r){let u=s.function?.arguments,l=u===void 0||typeof u=="string"?u:JSON.stringify(u);a.push({name:s.function?.name,args:l,id:s.id,index:s.index,type:"tool_call_chunk"})}else i={};return n==="user"?new mv({content:o}):n==="assistant"?new Ir({content:o,tool_call_chunks:a,additional_kwargs:i,usage_metadata:e?{input_tokens:e.promptTokens,output_tokens:e.completionTokens,total_tokens:e.totalTokens}:void 0}):n==="tool"?new Iw({content:o,additional_kwargs:i,tool_call_id:r?.[0].id??""}):n==="function"?new pv({content:o,additional_kwargs:i}):new fv({content:o,role:n})}function Qkr(t){if(!(!t||!t.length))return t.map(e=>{if("function"in e)return{type:e.type??"function",function:e.function};if(bg(e)){let r=e.description??`Tool: ${e.name}`;return{type:"function",function:{name:e.name,description:r,parameters:Ya(e.schema)?Ni(e.schema):e.schema}}}throw new Error(`Unknown tool type passed to ChatMistral: ${JSON.stringify(e,null,2)}`)})}var eqr,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=class extends md{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");let r=e?.apiKey??vn("MISTRAL_API_KEY");if(!r)throw new Error("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=
`):[]}};lw=new WeakMap;MH.NEWLINE_CHARS=new Set([`
`,"\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)+`
`);o.enqueue(s)}catch(i){o.error(i)}},async cancel(){await r.return?.()}})}};Yct=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=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(`Unexpected data type: ${typeof t}; 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(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(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(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${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++};return a()},Pdt=t=>BXo(t,Eh.ALL^Eh.NUM)});function VXo(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 jr(`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 jr(`missing role for choice ${d}`);if(h){let{arguments:_,name:w}=h;if(_==null)throw new jr(`missing function_call.arguments for choice ${d}`);if(!w)throw new jr(`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 jr(`missing choices[${d}].tool_calls[${w}].id
${b1e(t)}`);if(T==null)throw new jr(`missing choices[${d}].tool_calls[${w}].type
${b1e(t)}`);if(j==null)throw new jr(`missing choices[${d}].tool_calls[${w}].function.name
${b1e(t)}`);if(I==null)throw new jr(`missing choices[${d}].tool_calls[${w}].function.arguments
${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}:{}};return Hqr(u,e)}function b1e(t){return JSON.stringify(t)}var Z9,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")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},vu=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Q9=class t extends X9{constructor(e){super(),km.add(this),xD.set(this,void 0),Y9.set(this,void 0),Eq.set(this,void 0),Z9(this,xD,e,"f"),Z9(this,Y9,[],"f")}get currentChatCompletionSnapshot(){return vu(this,Eq,"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())),vu(this,km,"m",Mdt).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)vu(this,km,"m",Idt).call(this,a);if(i.controller.signal?.aborted)throw new nm;return this._addChatCompletion(vu(this,km,"m",y1e).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),vu(this,km,"m",Mdt).call(this),this._connected();let o=QR.fromReadableStream(e,this.controller),i;for await(let a of o)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)throw new nm;return this._addChatCompletion(vu(this,km,"m",y1e).call(this))}[(xD=new WeakMap,Y9=new WeakMap,Eq=new WeakMap,km=new WeakSet,Mdt=function(){this.ended||Z9(this,Eq,void 0,"f")},g1e=function(r){let n=vu(this,Y9,"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},vu(this,Y9,"f")[r.index]=n,n)},Idt=function(r){if(this.ended)return;let n=vu(this,km,"m",Yqr).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=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(let s of o.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
This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
`);super({baseURL:a.baseURL,timeout:a.timeout??6e5,httpAgent:a.httpAgent,maxRetries:a.maxRetries,fetch:a.fetch}),this.completions=new LH(this),this.chat=new SD(this),this.embeddings=new FH(this),this.files=new Mq(this),this.images=new VH(this),this.audio=new tA(this),this.moderations=new JH(this),this.models=new Rq(this),this.fineTuning=new ux(this),this.vectorStores=new fw(this),this.beta=new sx(this),this.batches=new xq(this),this.uploads=new Dq(this),this.responses=new jq(this),this.evals=new iA(this),this._options=a,this.apiKey=r,this.organization=n,this.project=o}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return Bct(e,{arrayFormat:"brackets"})}};bUr=ko;ko.OpenAI=bUr;ko.DEFAULT_TIMEOUT=6e5;ko.OpenAIError=jr;ko.APIError=Fm;ko.APIConnectionError=_q;ko.APIConnectionTimeoutError=vq;ko.APIUserAbortError=nm;ko.NotFoundError=Yse;ko.ConflictError=Qse;ko.RateLimitError=tue;ko.BadRequestError=Gse;ko.AuthenticationError=Xse;ko.InternalServerError=rue;ko.PermissionDeniedError=Zse;ko.UnprocessableEntityError=eue;ko.toFile=rdt;ko.fileFromPath=YNe;ko.Completions=LH;ko.Chat=SD;ko.ChatCompletionsPage=Cq;ko.Embeddings=FH;ko.Files=Mq;ko.FileObjectsPage=UH;ko.Images=VH;ko.Audio=tA;ko.Moderations=JH;ko.Models=Rq;ko.ModelsPage=HH;ko.FineTuning=ux;ko.VectorStores=fw;ko.VectorStoresPage=WH;ko.VectorStoreSearchResponsesPage=KH;ko.Beta=sx;ko.Batches=xq;ko.BatchesPage=IH;ko.Uploads=Dq;ko.Responses=jq;ko.Evals=iA;ko.EvalListResponsesPage=qH;_Ur=ko});var M1e,wUr=v(()=>{Qa();id();oV();vUr();_t();M1e=class extends UC{constructor(e){let{enableReasoning:r=!1,reasoningEffort:n,...o}=e;super(o),this.enableReasoning=r,this.reasoningEffort=n,this.openaiClient=new _Ur({apiKey:e.apiKey,baseURL:e.configuration?.baseURL||"https://openrouter.ai/api/v1",defaultHeaders:e.configuration?.defaultHeaders,fetch:e.configuration?.fetch,dangerouslyAllowBrowser:!0})}invocationParams(e){let r=super.invocationParams(e);if(this.enableReasoning)if(this.reasoningEffort){let n=this.reasoningEffort==="minimal"?"low":this.reasoningEffort;return B(`OpenRouter reasoning enabled with effort: ${n}`),{...r,reasoning:{effort:n}}}else return B("OpenRouter reasoning enabled with max_tokens: 1024"),{...r,reasoning:{max_tokens:1024}};return r}async*_streamResponseChunks(e,r,n){let o=this.invocationParams(r),i=this.toOpenRouterMessages(e),a=await this.openaiClient.chat.completions.create({...o,messages:i,stream:!0,stream_options:{...o.stream_options??{},include_usage:!0}}),s;for await(let u of a){u.usage&&(s=u.usage);let l=u.choices?.[0],c=l?.delta;if(!l||!c)continue;let d=this.normalizeReasoningChunk(c?.reasoning),f=this.extractReasoningDetails(l),p=this.extractDeltaContent(c.content),m=this.buildMessageChunk({rawChunk:u,delta:c,content:p,finishReason:l.finish_reason,reasoningDetails:f,reasoningText:d}),h=new yi({message:m,text:typeof m.content=="string"?m.content:"",generationInfo:{finish_reason:l.finish_reason,system_fingerprint:u.system_fingerprint,model:u.model}});yield h,h.text&&await n?.handleLLMNewToken(h.text)}if(s&&(yield this.buildUsageGenerationChunk(s)),r.signal?.aborted)throw new Error("AbortError")}toOpenRouterMessages(e){return e.map(r=>{let n=typeof r._getType=="function"?r._getType():r.role??"user",o=n==="human"?"user":n==="ai"?"assistant":n;return r.tool_call_id?{role:"tool",content:r.content,tool_call_id:r.tool_call_id}:r.additional_kwargs?.function_call?{role:o,content:r.content,function_call:r.additional_kwargs.function_call}:{role:o,content:r.content}})}buildMessageChunk(e){let{rawChunk:r,delta:n,content:o,finishReason:i,reasoningText:a,reasoningDetails:s}=e,u=this.extractToolCallChunks(n.tool_calls),l={};n.function_call&&(l.function_call=n.function_call),Array.isArray(n.tool_calls)&&(l.tool_calls=n.tool_calls);let c={};a&&(c.reasoning=a),s&&s.length>0&&(c.reasoning_details=s),Object.keys(c).length>0&&(l.delta={...l.delta,...c})
`).map(r=>r.trim()).filter(r=>r.length>0):[]}parseEventStreamBuffer(e){let r=[];if(e.length<12)return{messages:r,remainingBytes:e};let n=new DataView(e.buffer,e.byteOffset,e.byteLength),o=0;for(;o+12<=e.length;){let a=n.getUint32(o,!1),s=n.getUint32(o+4,!1);if(o+a>e.length)break;if(a<=0||s<0||s+12>a){Be(`parseEventStreamBuffer: Invalid message structure at offset ${o}: totalLength=${a}, headersLength=${s}`);break}let u=o+12+s,l=o+a-4;if(u>l||l>e.length){Be(`parseEventStreamBuffer: Invalid payload bounds at offset ${o}`);break}if(u<e.length){let c=e.subarray(u,l),d=this.decodeUtf8(c).trim();d.length>0&&r.push(d)}if(o+=a,a===0)break}let i=o<e.length?e.subarray(o):new Uint8Array(0);return{messages:r,remainingBytes:i}}decodeEventStreamMessages(e){let{messages:r}=this.parseEventStreamBuffer(e);return r}buildChunkMetadata(e){let r={provider:"amazon-bedrock"};typeof e?.type=="string"&&(r.event_type=e.type),e?.index!==void 0&&(r.event_index=e.index);let n=this.extractStopReason(e);n&&(r.stop_reason=n);let o=this.extractUsage(e);return o&&(r.usage=o),r}extractStreamText(e){if(!e||typeof e!="object")return null;let r=[e.delta?.thinking,e.content_block_delta?.delta?.thinking,e.contentBlockDelta?.delta?.thinking,e.delta?.reasoning_content,e.reasoning_content];for(let i of r)if(typeof i=="string"&&i.length>0)return i;let n=[e.text,e.outputText,e.completion,e.resultText,e.delta];for(let i of n)if(typeof i=="string"&&i.length>0)return i;let o=[e.delta?.text,e.delta?.output_text,e.delta?.content,e.contentBlockDelta?.delta?.text,e.contentBlockDelta?.delta?.output_text,e.contentBlockDelta?.delta?.content,e.content_block_delta?.delta?.text,e.content_block_delta?.delta?.output_text,e.content_block_delta?.delta?.content,e.message?.content,e.messageStop?.message?.content,e.message_stop?.message?.content,e.content];for(let i of o){let a=this.extractTextFromCandidate(i);if(a)return a}return null}extractTextFromCandidate(e){if(!e)return null;if(typeof e=="string")return e.length>0?e:null;if(Array.isArray(e)){let r=e.map(n=>{if(typeof n=="string")return n;if(n&&typeof n=="object"){if(typeof n.text=="string")return n.text;if(typeof n.value=="string")return n.value;if(Array.isArray(n.content))return n.content.map(o=>typeof o?.text=="string"?o.text:"").join("")}return""}).join("");return r.length>0?r:null}if(typeof e=="object"){let r=e;if(typeof r.text=="string")return r.text.length>0?r.text:null;if(r.text&&typeof r.text=="object"){let n=this.extractTextFromCandidate(r.text);if(n)return n}if(typeof r.value=="string")return r.value.length>0?r.value:null;if(Array.isArray(r.content))return this.extractTextFromCandidate(r.content);if(r.delta){let n=this.extractTextFromCandidate(r.delta);if(n)return n}if(r.message&&typeof r.message=="object"){let n=this.extractTextFromCandidate(r.message);if(n)return n}}return null}extractUsage(e){if(!(!e||typeof e!="object")){if(e.usage&&typeof e.usage=="object")return e.usage;if(e.metrics&&typeof e.metrics=="object")return e.metrics;if(e["amazon-bedrock-invocationMetrics"]&&typeof e["amazon-bedrock-invocationMetrics"]=="object")return e["amazon-bedrock-invocationMetrics"];if(e.messageStop&&typeof e.messageStop=="object")return this.extractUsage(e.messageStop);if(e.message_stop&&typeof e.message_stop=="object")return this.extractUsage(e.message_stop)}}extractStopReason(e){if(!e||typeof e!="object")return;let r=e.stop_reason||e.stopReason||e.completionReason||e.completion_reason||e.reason||e.messageStop?.stopReason||e.message_stop?.stop_reason||(e.type==="message_stop"?e.reason:void 0);return typeof r=="string"?r:void 0}buildTerminalMetadataChunk(e,r){let n=r?this.normaliseUsageMetadata(r):void 0,o={provider:"amazon-bedrock"};e&&(o.stop_reason=e),r&&(o.usage=r);let i=new Ir({content:"",response_metadata:o,usage_metadata:n});return new yi({message:i,text:"",generationInfo:o})}normaliseUsageMetadata(e){let r=this.coerceNumber(e.inputTokens)??this.coerceNumber(e.input_tokens)??this.coerceNumber(e.inputTokenCount)??this.coerceNumber(e.promptTokens)??this.coerceNumber(e.prompt_tokens)??0,n=this.coerceNumber(e.outputTokens)??
`)),i!==void 0&&(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!==void 0&&(u.temperature=a),s!==void 0&&(u.top_p=s),u}normaliseMessageContent(e){let{content:r}=e;return typeof r=="string"?r:Array.isArray(r)?r.some(o=>typeof o=="object"&&o!==null&&(o.type==="image_url"||o.type==="image"))?r.map(o=>{if(typeof o=="string")return{type:"text",text:o};if(typeof o=="object"&&o!==null){if(o.type==="text"||o.type==="image_url"||o.type==="image")return o;if("text"in o&&typeof o.text=="string")return{type:"text",text:o.text};if("content"in o&&typeof o.content=="string")return{type:"text",text:o.content}}return null}).filter(o=>o!==null):r.map(o=>{if(typeof o=="string")return o;if(typeof o=="object"&&o!==null){if("text"in o&&typeof o.text=="string")return o.text;if("content"in o&&typeof o.content=="string")return o.content}return""}).join(""):typeof r=="object"&&r!==null&&"text"in r?r.text??"":""}extractText(e){return typeof e?.outputText=="string"?e.outputText:Array.isArray(e?.content)?e.content.map(r=>{if(!r)return"";if(typeof r=="string")return r;if(typeof r=="object"){if(typeof r.text=="string")return r.text;if(r.text&&typeof r.text=="object"&&"text"in r.text)return r.text.text??""}return""}).join(""):typeof e?.completion=="string"?e.completion:typeof e?.resultText=="string"?e.resultText:""}}});function CUr(t){let e,r,n,o,i,a,s;return u(),{feed:l,reset:u};function u(){e=!0,r="",n=0,o=-1,i=void 0,a=void 0,s=""}function l(d){r=r?r+d:d,e&&yZo(r)&&(r=r.slice(xUr.length)),e=!1;let f=r.length,p=0,m=!1;for(;p<f;){m&&(r[p]===`
`&&++p,m=!1);let h=-1,y=o,g;for(let b=n;h<0&&b<f;++b)g=r[b],g===":"&&y<0?y=b-p:g==="\r"?(m=!0,h=b-p):g===`
`&&(h=b-p);if(h<0){n=f-p,o=y;break}else n=0,o=-1;c(r,p,y,h),p+=h+1}p===f?r="":p>0&&(r=r.slice(p))}function c(d,f,p,m){if(m===0){s.length>0&&(t({type:"event",id:i,event:a||void 0,data:s.slice(0,-1)}),s="",i=void 0),a=void 0;return}let h=p<0,y=d.slice(f,f+(h?m:p)),g=0;h?g=m:d[f+p+1]===" "?g=p+2:g=p+1;let b=f+g,_=m-g,w=d.slice(b,b+_).toString();if(y==="data")s+=w?"".concat(w,`
`):`
`;else if(y==="event")a=w;else if(y==="id"&&!w.includes("\0"))i=w;else if(y==="retry"){let O=parseInt(w,10);Number.isNaN(O)||t({type:"reconnect-interval",value:O})}}}function yZo(t){return xUr.every((e,r)=>t.charCodeAt(r)===e)}var xUr,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=class t{constructor(){this.abortController=null;this.refreshPromise=null;this.refreshAttempts=0;this.authGeneration=0}static getInstance(){return t.instance||(t.instance=new t),t.instance}getAuthState(){let e=ae(),r=!!e.githubCopilotAccessToken,n=!!e.githubCopilotToken,o=e.githubCopilotTokenExpiresAt,a=!(typeof o=="number"&&o>0)||o<Date.now();return n&&!a||n&&r?{status:"authenticated"}:r?{status:"pending"}:{status:"idle"}}isAuthenticated(){return this.getAuthState().status==="authenticated"}async startDeviceCodeFlow(){let e=new URLSearchParams({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){let i=typeof n.error_description=="string"?n.error_description:typeof n.error=="string"?n.error:"";throw new Error(i?`Failed to get device code: ${i}`:`Failed to get device code: ${r.status}`)}if(typeof n.device_code!="string"||typeof n.user_code!="string"||typeof n.expires_in!="number")throw new Error("Invalid device code response from GitHub");let o=typeof n.verification_uri=="string"?n.verification_uri:typeof n.verification_uri_complete=="string"?n.verification_uri_complete:null;if(!o)throw new Error("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:typeof n.interval=="number"&&n.interval>0?n.interval:5}}async pollForAccessToken(e,r,n,o){let i=this.authGeneration;this.abortPolling();let a=new AbortController;this.abortController=a;let s=Date.now()+n*1e3,u=0;try{for(;Date.now()<s;){if(a.signal.aborted||this.authGeneration!==i)throw new Error("Authentication cancelled by user.");if(u++,o?.(u),await this.delay(r*1e3,a.signal),a.signal.aborted||this.authGeneration!==i)throw new Error("Authentication cancelled by user.");let l=new URLSearchParams({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)throw new Error("Authentication cancelled by user.");let d=this.getRequestUrlJson(c);if(c.status!==200){let f=typeof d.error_description=="string"?d.error_description:typeof d.error=="string"?d.error:`HTTP ${c.status}`;throw new Error(`Token request failed: ${f}`)}if(typeof d.access_token=="string"&&d.access_token){if(a.signal.aborted||this.authGeneration!==i)throw new Error("Authentication cancelled by user.");return t_({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")throw new Error("Device code expired. Please restart authentication.");if(d.error==="access_denied")throw new Error("Authorization denied by user.");if(typeof d.error=="string"&&d.error)throw new Error(typeof d.error_description=="string"&&d.error_description?d.error_description:d.error)}}throw new Error("Device code expired. Please restart authentication.")}finally{
without CORS Error: `+Sn(n)+`
with CORS Error: `+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: Failed to read file ${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
Question: {question}
Passage:`)}async getRelevantDocuments(r,n){return rh(async()=>{let o=mL(r,app.vault),i=o.map(h=>h.basename),a=[...new Set([...this.options.salientTerms,...i])],s=await this.getExplicitChunks(o),u=r;n?.runName!=="no_hyde"&&(u=await this.rewriteQuery(r));let l=await this.getOramaChunks(u,a,this.options.textWeight),c=this.filterAndFormatChunks(l,s),d=c;if(c.length===0)return ae().debug&&console.log("No chunks found for query:",r),d;let f=c.reduce((h,y)=>{let g=y.metadata.score;return typeof g=="number"&&!isNaN(g)?Math.max(h,g):h},0),p=c.every(h=>typeof h.metadata.score!="number"||isNaN(h.metadata.score)),m=this.options.useRerankerThreshold&&(f<this.options.useRerankerThreshold||p);return m&&(d=(await pc.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(`
Original Query: `,r),console.log("Rewritten Query: ",u)),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})}async rewriteQuery(r){try{return await pge(async()=>{let n=await this.queryRewritePrompt.format({question:r}),o=await rh(async()=>(await Nm.instance.getCurrentChainManager().chatModelManager.getChatModelWithTemperature(0)).invoke(n));if(o&&"content"in o){let i=Az(o.content);return JW(i)}return console.warn("Unexpected rewrittenQuery format. Falling back to original query."),r},KW)}catch(n){return console.error("Error in rewriteQuery:",n),r}}async getExplicitChunks(r){let n=[];for(let o of r){let i=await D1.getInstance().getDb(),a=await yR.getDocsByPath(i,o.path);if(a){let s=a.map(u=>new Rm({pageContent:u.document.content,metadata:{...u.document.metadata,score:u.score,path:u.document.path,mtime:u.document.mtime,ctime:u.document.ctime,title:u.document.title,id:u.document.id,embeddingModel:u.document.embeddingModel,tags:u.document.tags,extension:u.document.extension,created_at:u.document.created_at,nchars:u.document.nchars}}));n.push(...s)}}return n}async getOramaChunks(r,n,o){let i;try{i=await this.convertQueryToVector(r)}catch(l){throw console.error("Error in convertQueryToVector, please ensure your embedding model is working and has an adequate context length:",l,`
Query:`,r),l}let a=await D1.getInstance().getDb(),s={similarity:this.options.minSimilarityScore,limit:this.options.maxK,includeVectors:!0};if(n.length>0){let l;o||(o=.5),l=1-o;let c=!0;for(let d of n)if(!d.startsWith("#")){c=!1;break}c&&(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}}else s.mode="vector",s.vector={value:i,property:"embedding"};if(this.options.timeRange){let{startTime:l,endTime:c}=this.options.timeRange,d=this.generateDailyNoteDateRange(l,c);B("Daily note date range:",d[0],d[d.length-1]);let f=mL(d.join(", "),app.vault),m=(await this.getExplicitChunks(f)).map(_=>({..._,metadata:{..._.metadata,includeInContext:!0}}));B("Modified time range:",l,c),s.where={mtime:{between:[l,c]}};let y=(await x_(a,s)).hits.map(_=>new Rm({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];return Array.from(new Set(g.map(_=>_.metadata.id))).map(_=>g.find(w=>w.metadata.id===_)).filter(_=>_!==void 0)}B(`Orama search params:
`,s);let u=await x_(a,s);return!u||!u.hits?(console.warn("Search results or hits are undefined"),[]):u.hits.map(l=>!l||!l.document?(console.warn("Invalid hit or document in search results"),null):((typeof l.score!="number"||isNaN(l.score))&&console.warn("NaN/invalid score detected:",{score:l.score,path:l.document.path,title:l.document.title}),new Rm({pageContent:l.document.content||"",metadata:{...l.document.metadata||{},score:l.score,path:l.document.path||"",mtime:l.document.mtime,ctime:l.document.ctime,title:l.document.title||"",id:l.document.id,embeddingModel:l.document.embeddingModel,tags:l.document.tags||[],extension:l.document.extension,created_at:l.document.created_at,nchars:l.document.nchars}}))).filter(l=>l!==null)}async convertQueryToVector(r){let o=await(await gd.getInstance().getEmbeddingsAPI()).embedQuery(r);if(o.length===0)throw new Error("Query embedding returned an empty vector");return o}generateDailyNoteDateRange(r,n){let o=[],i=new Date(r),a=new Date(n),s=new Date(i);for(;s<=a;)o.push(`[[${s.toLocaleDateString("en-CA")}]]`),s.setDate(s.getDate()+1);return o}filterAndFormatChunks(r,n){let o=this.options.minSimilarityScore,i=r.filter(u=>{let l=u.metadata.score;return typeof l!="number"||isNaN(l)?!0:l>=o}),a=new Set(n.map(u=>u.pageContent)),s=[...n];for(let u of i){let l=u.pageContent;a.has(l)||(a.add(l),s.push(u))}return s.map(u=>({...u,metadata:{...u.metadata,includeInContext:!0}}))}}});var gft={};Rn(gft,{MergedSemanticRetriever:()=>Sue});var kq,Sue,D1e=v(()=>{j1e();tEe();w7();tG();kTe();kq=class kq extends vV{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;let o=this.returnAll?jm:Math.min(this.originalMaxK*2,jm),i={...n,maxK:o,returnAll:this.returnAll,returnAllTags:n.returnAllTags,tagTerms:n.tagTerms};this.lexicalRetriever=new GH(r,i);let a=this.returnAll?jm:Math.min(this.originalMaxK*2,jm);this.semanticRetriever=new wue({minSimilarityScore:n.minSimilarityScore??.1,maxK:a,salientTerms:n.salientTerms,timeRange:n.timeRange,textWeight:n.textWeight,returnAll:this.returnAll,useRerankerThreshold:n.useRerankerThreshold})}async getRelevantDocuments(r,n){let[o,i]=await Promise.all([this.lexicalRetriever.getRelevantDocuments(r,n),this.semanticRetriever.getRelevantDocuments(r,n)]),a=new Map;for(let l of o)this.insertResult(a,l,"lexical");for(let l of i)this.insertResult(a,l,"semantic");let s=Array.from(a.values()).sort((l,c)=>(c.metadata?.score??0)-(l.metadata?.score??0)),u=this.returnAll?jm:this.originalMaxK;return s.slice(0,u)}insertResult(r,n,o){let i=this.getDocumentKey(n),a=this.decorateDocument(n,o),s=r.get(i);if(!s){r.set(i,a);return}let u=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){let n=r.metadata??{};return n.chunkId||n.path||n.id||n.title||`${r.pageContent.slice(0,64)}::${r.pageContent.length}`}decorateDocument(r,n){let o={...r.metadata??{},source:n},i=this.extractBaseScore(o),a=n==="lexical"?kq.LEXICAL_WEIGHT:kq.SEMANTIC_WEIGHT,s=i*a;return n==="lexical"&&this.hasTagMatch(o)&&(s*=kq.TAG_MATCH_BOOST),o.score=s,o.rerank_score=s,new Rm({pageContent:r.pageContent,metadata:o})}extractBaseScore(r){let n=[r?.rerank_score,r?.score];for(let o of n)if(typeof o=="number"&&!Number.isNaN(o))return o;return 0}getDocumentScore(r){let n=r.metadata?.score;return typeof n=="number"&&!Number.isNaN(n)?n:0}hasTagMatch(r){let n=r?.explanation;if(!n)return!1;let o=n.lexicalMatches;return Array.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){return e?`
<guidance>
${DUr}
IMAGE INCLUSION:
When the retrieved documents contain relevant images (in formats like ![alt](image.png) 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 ![alt](image.png) 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>`}function LUr(t,e=!0){return e?`
${DUr}
Source Catalog (for reference only):
${t}`:""}function $1e(t,e,r=!0){if(!r||!e?.length||!t)return t||"";if(MZo(t))return t;let n=e.slice(0,PZo).map((o,i)=>{let a=(o.title||o.path||"Untitled").replace(/^\[\[|\]\]$/g,"");return`[^${i+1}]: [[${a}]]`}).join(`
`);return`${t}
#### Sources:
${n}`}function L1e(t){if(!t)return"";let e=t.replace(/\[\^\d+\]/g,"");return e=e.replace(/\[(\d+(?:\s*,\s*\d+)*)\](?!\()/g,""),e=e.replace(/^\s*\[\^\d+\]:.*$/gm,""),e}function MZo(t){let e=t||"",r=/(^|\n)\s*#{1,6}\s*Sources\b/i.test(e),n=/(^|\n)\s*Sources\s*(?:[:-]\s*)?(\n|$)/i.test(e),o=/<summary[^>]*>\s*Sources\s*<\/summary>/i.test(e),i=/(^|\n)\s*\[\^\d+\]:\s*/.test(e);return r||n||o||i}function FUr(t){let e=t||"";return/\[\^\d+\]/.test(e)}function kUr(t=!0){return t?`
${EZo}`:""}function IZo(t){let e=/([\s\S]*?)\n+(?:####\s*)?Sources\s*:?\s*\n+([\s\S]*)$/i,r=t.match(e);return r?{mainContent:r[1],sourcesBlock:(r[2]||"").trim()}:null}function RZo(t){return t.includes(`
`)||(t=t.replace(/\s*\[(\d+)\]\s*/g,`
[$1] `),t=t.replace(/\s+(\d+)\.\s/g,`
$1. `),t=t.trim()),t}function AZo(t){return t.split(`
`).map(e=>e.trim()).filter(e=>/^\[\^\d+\]:/.test(e))}function NZo(t,e){let r=new Map,n=new Set,o=[],i=/\[\^(\d+)\]/g,a;for(;(a=i.exec(t))!==null;){let s=parseInt(a[1],10);n.has(s)||(n.add(s),o.push(s))}if(o.length>0)o.forEach((s,u)=>r.set(s,u+1));else{let s=1;for(let u of e){let l=u.match(/^\[\^(\d+)\]:/);if(l){let c=parseInt(l[1],10);r.has(c)||r.set(c,s++)}}}return r}function jZo(t,e){let r=t,n;do n=!1,r=r.replace(/\[\^(\d+)\]/g,(o,i)=>{let a=parseInt(i,10),u=`[${e.get(a)??a}]`;return u!==o&&(n=!0),u}),r=r.replace(/\[\^(\d+(?:\s*,\s*\^?\d+)*)\]/g,(o,i)=>{let s=`[${i.split(",").map(u=>{let l=u.trim().replace(/^\^/,""),c=parseInt(l,10);return e.get(c)??c}).sort((u,l)=>u-l).map(u=>u.toString()).join(", ")}]`;return s!==o&&(n=!0),s});while(n);return r=r.replace(/\[(\d+)\]\./g,"[$1]"),r}function DZo(t,e){let r=[];return t.split(`
`).forEach(n=>{let o=n.match(/^\[\^(\d+)\]:\s*(.*)$/);if(!o)return;let i=parseInt(o[1],10),a=e.get(i)??i,s=o[2].match(/\[([^\]]+)\]\(([^)]+)\)/),u=o[2].match(/\[\[(.*?)\]\]/),l;if(s)l=`<a href="${s[2]}">${s[1]}</a>`;else if(u)l=`[[${u[1]}]]`;else{let c=o[2].match(/^(.*?)\]\s*\(([^)]+)\)\s*$/);if(c){let d=c[1].trim();l=`<a href="${c[2].trim()}">${d}</a>`}else l=o[2].replace(/\s*\([^)]*\)\s*$/,"")}r[a-1]=l}),r}function $Zo(t){let e=[],r=new Set,n=new Map;return t.forEach((o,i)=>{if(!o)return;let a=o.match(/\[\[(.*?)\]\]/),s=a?a[1].toLowerCase():o.toLowerCase();if(!r.has(s))r.add(s),e.push(o),n.set(i+1,e.length);else{let u=e.findIndex(l=>{let c=l.match(/\[\[(.*?)\]\]/);return(c?c[1].toLowerCase():l.toLowerCase())===s});u>=0&&n.set(i+1,u+1)}}),{uniqueItems:e,consolidationMap:n}}function LZo(t,e){return e.size===0?t:t.replace(/\[(\d+(?:\s*,\s*\d+)*)\]/g,(r,n)=>`[${n.split(/\s*,\s*/).map(a=>{let s=parseInt(a,10);return String(e.get(s)||s)}).join(", ")}]`)}function FZo(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function kZo(t){return t!=null}function qZo(t){let e=t.split(`
`),r=[];return e.forEach(n=>{let o=n.trim();if(!o)return;let i=o.replace(/^<li>/i,"").replace(/<\/li>$/i,"").replace(/^[-*]\s*/,"").trim();if(!i)return;let a=i.match(/\[([^\]]+)\]\(([^)]+)\)/),s=i.match(/\[\[(.*?)\]\]/),u;a?u=`<a href="${a[2]}">${a[1]}</a>`:s?u=`[[${s[1]}]]`:u=FZo(i),r.push({index:r.length+1,html:u})}),r}function jUr(t,e){let r=e.filter(o=>o.html.trim().length>0);if(r.length===0)return t;let n=r.map(({index:o,html:i})=>`<li class="copilot-sources__item"><span class="copilot-sources__index">[${o}]</span><span class="copilot-sources__text">${i}</span></li>`).join(`
`);return`${t}
<br/>
<details class="copilot-sources"><summary class="copilot-sources__summary">Sources</summary>
<ul class="copilot-sources__list">
${n}
</ul>
</details>`}function qUr(t,e=!0){if(!e)return t;let r=IZo(t);if(!r)return t;let{mainContent:n,sourcesBlock:o}=r;o=RZo(o);let i=AZo(o);if(i.length===0){let d=qZo(o);return jUr(n,d)}let a=NZo(n,i);n=jZo(n,a);let s=DZo(o,a),{uniqueItems:u,consolidationMap:l}=$Zo(s);l.size>0&&(n=LZo(n,l),s=u);let c=s.map((d,f)=>d?{index:f+1,html:d}:null).filter(kZo);return jUr(n,c)}function F1e(t){return t.map(e=>{let r=e.title||e.path||"Untitled",n=e.path||r;return`- [[${r}]] (${n})`})}var DUr,EZo,PZo,Cue=v(()=>{DUr=`CITATION RULES:
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)
10. End with '#### Sources' section containing: [^n]: [[Title]] (one per line, matching citation order)`,EZo=`WEB CITATION RULES:
1. START with [^1] and increment sequentially ([^1], [^2], [^3], etc.) with NO gaps
2. Cite ONLY when introducing new factual claims, statistics, or direct quotes from the search results
3. After every cited claim, place the corresponding footnote immediately after the sentence ("The study found X [^1]")
4. End with '#### Sources' and provide definitions EXACTLY in this format: [^n]: [Short Title](URL)
IMPORTANT: Each source definition must follow this exact pattern:
- Start with [^n]: (where n is the citation number)
- Follow with [Title](URL) where Title is SHORT (2-5 words) and wrapped in square brackets
- Example: [^1]: [Paul Graham Essay](https://paulgraham.com/wealth.html)
- DO NOT write long descriptions - keep titles concise`;PZo=20});var xue,UUr=v(()=>{Or();Xot();Mie();_t();w7();D1e();uit();ot();Zt();Pie();uG();Cue();F1();bV();qs();xue=class extends L1{async run(e,r,n,o,i){let a=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)}let l=new T_(n,void 0,u);try{let p=e.contextEnvelope;if(!p)throw new Error("[VaultQA] Context envelope is required but not available. Cannot proceed with VaultQA chain.");let h=p.layers.find(Y=>Y.id==="L5_USER")?.text||e.message,y=this.extractTagTerms(h);B("[VaultQA] Extracted tags before condensing:",y);let g=this.chainManager.memoryManager.getMemory(),b=await g.loadMemoryVariables({}),_=lge(b),w=h;_.length>0&&(B("[VaultQA] Condensing query with chat history for better retrieval"),w=await FTe(h,_),B("[VaultQA] Standalone question:",w));let O=ae(),T={minSimilarityScore:.01,maxK:O.maxSourceChunks,salientTerms:y.length>0?[...y]:[],timeRange:void 0,textWeight:void 0,returnAll:!1,useRerankerThreshold:void 0},M=await(O.enableSemanticSearchV3?new Sue(app,{...T,returnAll:y.length>0,returnAllTags:y.length>0,tagTerms:y}):new GH(app,{...T,returnAll:y.length>0,returnAllTags:y.length>0,tagTerms:y})).getRelevantDocuments(w);this.chainManager.storeRetrieverDocuments(M);let I=M.map(Y=>{let se=Y.metadata?.title||"Untitled",ie=Y.metadata?.path||se;return`<${hHe}>
<title>${se}</title>
<path>${ie}</path>
<content>
${L1e(Y.pageContent)}
</content>
</${hHe}>`}).join(`
`),j=[],A=this.chainManager.chatModelManager.getChatModel(),k=M.slice(0,Math.max(5,Math.min(20,M.length))).map(Y=>({title:Y.metadata?.title||Y.metadata?.path||"Untitled",path:Y.metadata?.path||Y.metadata?.title||""})),V=F1e(k).join(`
`),q=`
Answer the question based only on the following context:
`+I+LUr(V,O.enableInlineCitations);B("[VaultQA] Using envelope-based context construction with LayerToMessagesConverter");let J=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}),await wk(g,j);let ue=J.find(Y=>Y.role==="user");if(ue){let Y=q+`
`+ue.content;if(e.content&&Array.isArray(e.content)){let se=e.content.map(ie=>ie.type==="text"?{...ie,text:Y}:ie);j.push({role:"user",content:se})}else j.push({role:"user",content:Y})}let oe=A?.modelName;Sk({messages:j,modelName:oe,contextEnvelope:e.contextEnvelope}),B(`Final Request to AI:
`,j);let G=await rh(()=>this.chainManager.chatModelManager.getChatModel().stream(j,{signal:r.signal}));for await(let Y of G){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}):await this.handleError(p,l.processErrorChunk.bind(l))}let c=l.close(),d={wasTruncated:c.wasTruncated,tokenUsage:c.tokenUsage??void 0};if(r.signal.aborted&&r.signal.reason==="new-chat")return n(""),"";let f=this.addSourcestoResponse(c.content);return await this.handleResponse(f,e,r,o,n,void 0,void 0,d),f}addSourcestoResponse(e){let r=ae();if(!FUr(e))return e;let n=this.chainManager.getRetrievedDocuments(),o=RRt(n).map(i=>({title:i}));return $1e(e,o,r.enableInlineCitations)}extractTagTerms(e){return mG(e)}}});var S7,k1e=v(()=>{S7=["@vault","@websearch","@composer","@memory"]});function q1e(){return e_(qq,{store:pw})}function zUr(){return dL(yft,{store:pw})}function C7(){return pw.get(qq)}function XH(){return pw.get(yft)}function U1e(t){pw.set(qq,t)}function ZH(t){let e=pw.get(qq),r=e.findIndex(n=>n.title===t.title);if(r!==-1){let n=[...e];n[r]=t,pw.set(qq,n)}else pw.set(qq,[...e,t])}function x7(t){let e=pw.get(qq);pw.set(qq,e.filter(r=>r.title!==t))}function Uq(t){pw.set(yft,t)}function Oue(t){pw.set(BUr,t)}function Tue(){return pw.get(BUr)}function Bq(t){bft.add(t)}function zq(t){bft.delete(t)}function ED(t){return bft.has(t)}function B1e(){return ae().defaultSystemPromptTitle}function VUr(){let t=C7(),e=XH();if(e){let n=t.find(o=>o.title===e);if(n)return n.content}let r=B1e();if(r){let n=t.find(o=>o.title===r);if(n)return n.content}return""}function HUr(){let t=B1e();Uq(t)}function _ft(){Oue(!1),Uq("")}var pw,qq,yft,BUr,bft,YH=v(()=>{eC();eC();ot();pw=cL(),qq=Cc([]),yft=Cc(""),BUr=Cc(!1);bft=new Set});function z1e(){return VUr()||ae()?.userSystemPrompt||""}function PD(){let t=z1e();if(Tue())return t;let r=kRt;return t?`${r}
<user_custom_instructions>
${t}
</user_custom_instructions>`:r}async function MD(t){let e=PD();if(!t)return B("No UserMemoryManager provided to getSystemPromptWithMemory"),e;let r=await t.getUserMemoryPrompt();return r?`${r}
${e}`:e}var Vq=v(()=>{ot();Or();_t();YH()});function lx(){}function JUr(t,e,r,n,o){for(var i=[],a;e;)i.push(e),a=e.previousComponent,delete e.previousComponent,e=a;i.reverse();for(var s=0,u=i.length,l=0,c=0;s<u;s++){var d=i[s];if(d.removed)d.value=t.join(n.slice(c,c+d.count)),c+=d.count;else{if(!d.added&&o){var f=r.slice(l,l+d.count);f=f.map(function(p,m){var h=n[c+m];return h.length>p.length?h:p}),d.value=t.join(f)}else d.value=t.join(r.slice(l,l+d.count));l+=d.count,d.added||(c+=d.count)}}return i}function WUr(t,e){var r;for(r=0;r<t.length&&r<e.length;r++)if(t[r]!=e[r])return t.slice(0,r);return t.slice(0,r)}function KUr(t,e){var r;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)])return t.slice(-r);return t.slice(-r)}function vft(t,e,r){if(t.slice(0,e.length)!=e)throw Error("string ".concat(JSON.stringify(t)," doesn't start with prefix ").concat(JSON.stringify(e),"; this is a bug"));return r+t.slice(e.length)}function wft(t,e,r){if(!e)return t+r;if(t.slice(-e.length)!=e)throw Error("string ".concat(JSON.stringify(t)," doesn't end with suffix ").concat(JSON.stringify(e),"; this is a bug"));return t.slice(0,-e.length)+r}function Eue(t,e){return vft(t,e,"")}function V1e(t,e){return wft(t,e,"")}function GUr(t,e){return e.slice(0,UZo(t,e))}function UZo(t,e){var r=0;t.length>e.length&&(r=t.length-e.length);var n=e.length;t.length<e.length&&(n=t.length);var o=Array(n),i=0;o[0]=0;for(var a=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(var s=r;s<t.length;s++){for(;i>0&&t[s]!=e[i];)i=o[i];t[s]==e[i]&&i++}return i}function XUr(t,e,r,n){if(e&&r){var o=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){var u=WUr(o,a);t.value=wft(t.value,a,u),e.value=Eue(e.value,u),r.value=Eue(r.value,u)}if(n){var l=KUr(i,s);n.value=vft(n.value,s,l),e.value=V1e(e.value,l),r.value=V1e(r.value,l)}}else if(r)t&&(r.value=r.value.replace(/^\s*/,"")),n&&(n.value=n.value.replace(/^\s*/,""));else if(t&&n){var c=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);var m=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))}else if(n){var h=n.value.match(/^\s*/)[0],y=e.value.match(/\s*$/)[0],g=GUr(y,h);e.value=V1e(e.value,g)}else if(t){var b=t.value.match(/\s*$/)[0],_=e.value.match(/^\s*/)[0],w=GUr(b,_);e.value=Eue(e.value,w)}}function VZo(t,e){if(typeof t=="function")e.callback=t;else if(t)for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);return e}function ZUr(t,e,r){var n=VZo(r,{ignoreWhitespace:!0});return K1e.diff(t,e,n)}function Sft(t){"@babel/helpers - typeof";return Sft=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Sft(t)}function Cft(t,e,r,n,o){e=e||[],r=r||[],n&&(t=n(o,t));var i;for(i=0;i<e.length;i+=1)if(e[i]===t)return r[i];var a;if(Object.prototype.toString.call(t)==="[object Array]"){for(e.push(t),a=new Array(t.length),r.push(a),i=0;i<t.length;i+=1)a[i]=Cft(t[i],e,r,n,o);return e.pop(),r.pop(),a}if(t&&t.toJSON&&(t=t.toJSON()),Sft(t)==="object"&&t!==null){e.push(t),a={},r.push(a);var s=[],u;for(u in t)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()}else a=t;return a}function YUr(t,e,r){return J1e.diff(t,e,r)}var Iis,H1e,BZo,W1e,zZo,K1e,HZo,JZo,Pue,J1e,xft=v(()=>{lx.prototype={diff:function(e,r){var n,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=o.callback;typeof o=="function"&&(i=o,o={});var a=this;function s(w){return w=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));var u=r.length,l=e.length,c=1,d=u+l;o.maxEditLength!=null&&(d=Math.min(d,o.maxEditLength));var f=(n=o.
`));var r=[],n=t.split(/(\n|\r\n)/);n[n.length-1]||n.pop();for(var o=0;o<n.length;o++){var i=n[o];o%2&&!e.newlineIsToken?r[r.length-1]+=i:r.push(i)}return r};K1e.equals=function(t,e,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
`))&&(t=t.trim()),(!r.newlineIsToken||!e.includes(`
`))&&(e=e.trim())):r.ignoreNewlineAtEof&&!r.newlineIsToken&&(t.endsWith(`
`)&&(t=t.slice(0,-1)),e.endsWith(`
`)&&(e=e.slice(0,-1))),lx.prototype.equals.call(this,t,e,r)};HZo=new lx;HZo.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};JZo=new lx;JZo.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};Pue=new lx;Pue.useLongestToken=!0;Pue.tokenize=K1e.tokenize;Pue.castInput=function(t,e){var r=e.undefinedReplacement,n=e.stringifyReplacer,o=n===void 0?function(i,a){return typeof a>"u"?r:a}:n;return typeof t=="string"?t:JSON.stringify(Cft(t,null,null,o),o," ")};Pue.equals=function(t,e,r){return lx.prototype.equals.call(Pue,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"),r)};J1e=new lx;J1e.tokenize=function(t){return t.slice()};J1e.join=J1e.removeEmpty=function(t){return t}});var Mue,cx,Iue=v(()=>{Mue=L(X());kn();cx=Mue.forwardRef(({checked:t=!1,onCheckedChange:e,disabled:r=!1,className:n,...o},i)=>{let a=()=>{r||e?.(!t)},s=u=>{r||(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),e?.(!t))};return Mue.createElement("div",{role:"switch","aria-checked":t,"aria-disabled":r,"data-state":t?"checked":"unchecked","data-disabled":r?"":void 0,ref:i,tabIndex:r?-1:0,className:Te("tw-relative tw-inline-flex tw-h-5.5 tw-w-10 tw-shrink-0 tw-cursor-pointer tw-items-center tw-rounded-full tw-transition-colors","focus-visible:tw-outline-none focus-visible:tw-ring-2 focus-visible:tw-ring-ring focus-visible:tw-ring-offset-2",t?"tw-bg-interactive-accent":"tw-bg-[--background-modifier-border-hover]",r&&"tw-cursor-not-allowed tw-opacity-50",n),onClick:a,onKeyDown:s,...o},Mue.createElement("div",{className:Te("tw-pointer-events-none tw-block tw-size-4 tw-rounded-full tw-bg-toggle-thumb tw-shadow-lg tw-ring-0 tw-transition-transform",t?"tw-translate-x-5.5":"tw-translate-x-0.5")}))});cx.displayName="SettingSwitch"});function QUr(t){let e=[],r=[];return t.forEach(n=>{n.added||n.removed?r.push(n):(r.length>0&&(e.push(r),r=[]),e.push([n]))}),r.length>0&&e.push(r),e}var eBr=v(()=>{});function WZo(t,e){let r=o=>o.split(/(\s+)/).filter(Boolean);return YUr(r(t),r(e)).map(o=>({value:o.value.join(""),added:o.added,removed:o.removed}))}function Rue(t){let e=t.split(`
`);return e.length>0&&e[e.length-1]===""&&e.pop(),e}function rBr(t){let e=[],r=0;for(;r<t.length;){let n=t[r];if(!n.added&&!n.removed)Rue(n.value).forEach(o=>{e.push({original:o,modified:o,isUnchanged:!0})}),r++;else if(n.removed){let o=t[r+1];if(o?.added){let i=Rue(n.value),a=Rue(o.value),s=Math.max(i.length,a.length);for(let u=0;u<s;u++)e.push({original:i[u]??null,modified:a[u]??null,isUnchanged:!1});r+=2}else Rue(n.value).forEach(i=>{e.push({original:i,modified:null,isUnchanged:!1})}),r++}else n.added&&Rue(n.value).forEach(o=>{e.push({original:null,modified:o,isUnchanged:!1})}),r++}return e}var ID,qt,tBr,Oft,nBr,Aue,Nue,G1e,oBr,iBr,KZo,Tft=v(()=>{kn();_t();ot();xft();Jr();ID=require("obsidian"),qt=L(X()),tBr=L(dd());to();Iue();Oft=L(X());eBr();Zt();nBr=(0,qt.memo)(({original:t,modified:e,side:r})=>{let n=WZo(t,e);return qt.default.createElement("span",null,n.map((o,i)=>{if(r==="original"){if(o.removed)return qt.default.createElement("span",{key:i,className:"tw-bg-error tw-text-error"},o.value);if(o.added)return null}else{if(o.added)return qt.default.createElement("span",{key:i,className:"tw-bg-success tw-text-success"},o.value);if(o.removed)return null}return qt.default.createElement("span",{key:i},o.value)}))});nBr.displayName="WordDiffSpan";Aue=(0,qt.memo)(({row:t,side:e})=>{let r=e==="original"?t.original:t.modified,n=e==="original"?t.modified:t.original;return r===null?qt.default.createElement("span",{className:"tw-text-muted"},"\xA0"):t.isUnchanged?qt.default.createElement("span",{className:"tw-text-normal"},r||"\xA0"):n!==null?qt.default.createElement(nBr,{original:t.original,modified:t.modified,side:e}):qt.default.createElement("span",{className:e==="original"?"tw-bg-error tw-text-error":"tw-bg-success tw-text-success"},r||"\xA0")});Aue.displayName="DiffCell";Nue="obsidian-copilot-apply-view",G1e=class extends ID.ItemView{constructor(r){super(r);this.root=null;this.state=null;this.result=null}getViewType(){return Nue}getDisplayText(){return"Preview Changes"}async setState(r){this.state=r,this.render()}async onOpen(){this.render()}async onClose(){this.root&&(this.root.unmount(),this.root=null),this.state?.resultCallback?.(this.result?this.result:"aborted")}render(){if(!this.state)return;let r=this.containerEl.children[1];r.empty();let n=r.createDiv();this.root||(this.root=(0,tBr.createRoot)(n)),this.root.render(qt.default.createElement(KZo,{app:this.app,state:this.state,close:o=>{this.result=o,this.leaf.detach()}}))}},oBr=(0,qt.memo)(({block:t})=>{let e=(0,qt.useMemo)(()=>rBr(t),[t]);return qt.default.createElement("div",{className:"tw-grid tw-grid-cols-2 tw-gap-2"},qt.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-2"},e.map((r,n)=>qt.default.createElement("div",{key:n,className:"tw-whitespace-pre-wrap tw-font-mono tw-text-sm"},qt.default.createElement(Aue,{row:r,side:"original"})))),qt.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-2"},e.map((r,n)=>qt.default.createElement("div",{key:n,className:"tw-whitespace-pre-wrap tw-font-mono tw-text-sm"},qt.default.createElement(Aue,{row:r,side:"modified"})))))});oBr.displayName="SideBySideBlock";iBr=(0,qt.memo)(({block:t})=>{let e=t.some(n=>n.added||n.removed),r=(0,qt.useMemo)(()=>rBr(t),[t]);return e?qt.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},qt.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-2"},qt.default.createElement("div",{className:"tw-mb-1 tw-text-xs tw-font-medium tw-text-muted"},"Original"),qt.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-font-mono tw-text-sm"},r.map((n,o)=>n.original!==null?qt.default.createElement("div",{key:o},qt.default.createElement(Aue,{row:n,side:"original"})):null))),qt.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-2"},qt.default.createElement("div",{className:"tw-mb-1 tw-text-xs tw-font-medium tw-text-muted"},"Mo
`).replace(/\r/g,`
`)}function ZZo(t,e,r){let n=(t.match(/\r\n/g)||[]).length,o=(t.match(/(?<!\r)\n/g)||[]).length,i=n>o,a=jue(t),s=jue(e),u=jue(r),l=a.replaceAll(s,u);return i?l.replace(/\n/g,`\r
`):l}function YZo(t){let e=[],r=/-{3,}\s*SEARCH\s*(?:\r?\n)?/,n=/(?:\r?\n)?={3,}\s*(?:\r?\n)?/,o=/(?:\r?\n)?\+{3,}\s*REPLACE/,i=new RegExp(r.source+"([\\s\\S]*?)"+n.source+"([\\s\\S]*?)"+o.source,"g"),a;for(;(a=i.exec(t))!==null;){let s=a[1].trim(),u=a[2].trim();e.push({searchText:s,replaceText:u})}return e}var O7,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 end with explicit file extension, such as .md or .canvas .
Prefer to create new files in existing folders or root folder unless the user's request specifies otherwise.
The path must be relative to the root of the vault.`),content:Ct.union([Ct.string(),Ct.object({}).passthrough()]).describe(`(Required) The content to write to the file. Can be either a string or an object.
ALWAYS provide the COMPLETE intended content of the file, without any truncation or omissions.
You MUST include ALL parts of the file, even if they haven't been modified.
# For string content
* Use when writing text files like .md, .txt, etc.
# For object content
* Use when writing structured data files like .json, .canvas, etc.
* The object will be automatically converted to JSON string format
# Canvas JSON Format (JSON Canvas spec 1.0)
Required node fields: id, type, x, y, width, height
Node types: "text" (needs text), "file" (needs file), "link" (needs url), "group" (optional label)
Optional node fields: color (hex #FF0000 or preset "1"-"6"), subpath (file nodes, starts with #)
Required edge fields: id, fromNode, toNode
Optional edge fields: fromSide/toSide ("top"/"right"/"bottom"/"left"), fromEnd/toEnd ("none"/"arrow"), color, label
All IDs must be unique. Edge nodes must reference existing node IDs.
Example:
{
"nodes": [
{"id": "1", "type": "text", "text": "Hello", "x": 0, "y": 0, "width": 200, "height": 50},
{"id": "2", "type": "file", "file": "note.md", "subpath": "#heading", "x": 250, "y": 0, "width": 200, "height": 100, "color": "2"},
{"id": "3", "type": "group", "label": "Group", "x": 0, "y": 100, "width": 300, "height": 150}
],
"edges": [
{"id": "e1-2", "fromNode": "1", "toNode": "2", "fromSide": "right", "toSide": "left", "color": "3", "label": "links to"}
]
}`),confirmation:Ct.preprocess(t=>{if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t},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.
# Steps to find the the target path
1. Extract the target file information from user message and find out the file path from the context.
2. If target file is not specified, use the active note as the target file.
3. If still failed to find the target file or the file path, ask the user to specify the target file.
`,schema:GZo,handler:async({path:t,content:e,confirmation:r=!0})=>{let n=typeof e=="string"?e:JSON.stringify(e,null,2);if(ae().autoAcceptEdits||r===!1)try{let s=await sBr(t);return await app.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){return JSON.stringify({result:"failed",message:`Error writing to file without preview: ${s?.message||s}`})}let a=await uBr(t,n);return JSON.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:
------- SEARCH
[exact content to find, including all whitespace and indentation]
=======
[new content to replace with]
+++++++ REPLACE
WHEN TO USE THIS TOOL vs writeToFile:
- Use replaceInFile for: small edits, fixing typos, updating specific sections, targeted changes
- Use writeToFile for: creating new files, major rewrites, when you can't identify specific text to replace
CRITICAL RULES:
1. SEARCH content must match EXACTLY - every character, space, and line break
2. Use the exact markers: "------- SEARCH", "=======", "+++++++ REPLACE"
3. For multiple changes, include multiple SEARCH/REPLACE blocks in order
4. Keep blocks concise - include only the lines being changed plus minimal context
COMMON MISTAKES TO AVOID:
- Wrong: Using different markers like "---- SEARCH" or "SEARCH -------"
- Wrong: Including too many unchanged lines
- Wrong: Not matching whitespace/indentation exactly`)});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})=>{let r=app.vault.getAbstractFileByPath(t);if(!r||!(r instanceof O7.TFile))return`File not found at path: ${t}. Please check the file path and try again.`;try{let n=await app.vault.read(r),o=n;if(n.length<3e3)return"File is too small to use this tool. Please use writeToFile instead.";let a=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}`;let s=0;for(let c of a){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();else return`Search text not found in file ${t} : "${d}".`;let h=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{return await app.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){return JSON.stringify({result:"failed",blocksApplied:s,message:`Error applying changes without preview: ${c?.message||c}`})}let l=await uBr(t,o);return JSON.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})});var Pft,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{static async callTool(e,r){try{if(!e)throw new Error("Tool is undefined");let n=await e.call(r);return n??(console.warn(`Tool ${e.name} returned null/undefined result`),null)}catch(n){return console.error("Error calling tool:",n),n instanceof Error?new Pft.Notice(n.message):new Pft.Notice("An error occurred while executing the tool. Check console for details."),null}}}});function Q1e(t){let e=t.trim();if(!e)return"note";let r=e.match(/^\[\[([\s\S]+?)\]\]$/),n=r?r[1]:e,[o="",i=""]=n.split("|"),a=i.trim();if(a.length>0)return a;let s=o.trim(),[u]=s.split("#"),l=(u||s).trim()||e,c=l.split("/").filter(Boolean),d=c.length>0?c[c.length-1]:l;return d.replace(/\.[^/.]+$/,"")||d||"note"}function QZo(t){let e=t.trim();return e.length<=cBr?e:`${e.slice(0,cBr)}\u2026`}function eYo(t){if(!t||typeof t!="object")return null;let e=typeof t.status=="string"?t.status:null,r=typeof t.message=="string"&&t.message.trim().length>0?QZo(t.message):null,n=typeof t.notePath=="string"?t.notePath:"",i=(typeof t.noteTitle=="string"&&t.noteTitle.trim().length>0?t.noteTitle.trim():Q1e(n))||Q1e(n);if(e==="invalid_path")return r??`\u26A0\uFE0F Invalid note path "${i}"`;if(e==="not_found")return r??`\u26A0\uFE0F Note "${i}" not found`;if(e==="not_unique"){let c=Array.isArray(t.candidates)?t.candidates.length:0;return r||(c>0?`\u26A0\uFE0F Multiple matches for "${i}" (${c} candidates)`:`\u26A0\uFE0F Multiple matches for "${i}"`)}if(e==="empty")return r??`\u26A0\uFE0F "${i}" contains no readable content`;if(e==="out_of_range"){if(r)return r;let c=typeof t.totalChunks=="number"&&Number.isFinite(t.totalChunks)?t.totalChunks:null,d=typeof t.chunkIndex=="number"&&Number.isFinite(t.chunkIndex)?t.chunkIndex:null;if(d!==null&&c!==null){let f=Math.max(c-1,0);return`\u26A0\uFE0F Chunk ${d} exceeds available range (max index ${f})`}return"\u26A0\uFE0F Requested chunk is out of range"}let a=typeof t.chunkIndex=="number"&&Number.isFinite(t.chunkIndex)?t.chunkIndex:0,s=typeof t.totalChunks=="number"&&Number.isFinite(t.totalChunks)?t.totalChunks:null,u=!!t.hasMore,l=[`\u2705 Read "${i||"note"}"`];return s&&s>0?l.push(`chunk ${a+1} of ${s}`):l.push(`chunk ${a+1}`),u&&l.push("more available"),l.join(" \xB7 ")}var cBr,fx,Due=v(()=>{cBr=180;fx=class{static format(e,r){try{let n=r;if(typeof n=="string"&&n.startsWith("ENC:"))try{n=decodeURIComponent(n.slice(4))}catch{}let o;try{o=JSON.parse(n)}catch{o=n}switch(e){case"localSearch":return this.formatLocalSearch(o);case"webSearch":return this.formatWebSearch(o);case"youtubeTranscription":return this.formatYoutubeTranscription(o
No matching notes found.`;let r=e.length,n=e.slice(0,10),o=n.some(s=>typeof s?.rerank_score=="number"||typeof s?.score=="number"||s?.source),i=n.map((s,u)=>o?this.formatSearchItem(s,u):this.formatBasicSearchItem(s,u)).join(`
`),a=r>10?`
... and ${r-10} more results`:"";return`\u{1F4DA} Found ${r} relevant notes
Top results:
${i}${a}`}static formatLocalSearch(e){if(typeof e=="string"){let n=e.match(/<localSearch[^>]*>([\s\S]*)<\/localSearch>/);if(n){let o=n[1].trim(),i=o.match(/<document>/g);if((i?i.length:0)===0)return`\u{1F4DA} Found 0 relevant notes
No matching notes found.`;let s=[],u=/<document>([\s\S]*?)<\/document>/g,l;for(;(l=u.exec(o))!==null;){let c=l[1],d=c.match(/<title>([\s\S]*?)<\/title>/),f=c.match(/<path>([\s\S]*?)<\/path>/),p=c.match(/<modified>([\s\S]*?)<\/modified>/),m=(d?.[1]||"Untitled").trim(),h=(f?.[1]||"").trim(),y=(p?.[1]||"").trim();s.push({title:m,path:h,mtime:y||null})}return this.formatLocalSearchDocuments(s)}}let r=this.parseSearchResults(e);return Array.isArray(r)?r.length===0?typeof e=="string"&&!e.includes("<localSearch")&&!e.includes('"type":"local_search"')?e:`\u{1F4DA} Found 0 relevant notes
No matching notes found.`:this.formatLocalSearchDocuments(r):typeof e=="string"?e:JSON.stringify(e,null,2)}static parseSearchResults(e){if(typeof e=="object"&&e!==null)return e.type==="local_search"&&Array.isArray(e.documents)?e.documents:[];if(typeof e=="string"){try{let r=JSON.parse(e);if(r&&r.type==="local_search"&&Array.isArray(r.documents))return r.documents}catch{}return[]}return[]}static formatSearchItem(e,r){let n=e.path?.split("/").pop()?.replace(/\.md$/,"")||e.title||"Untitled",o=e.rerank_score||e.score||0,i=typeof o=="number"?o.toFixed(4):o,a=e.source==="time-filtered"?"Recency":"Relevance",s=[`${r+1}. ${n}`];if(e.source==="time-filtered"){if(e.mtime)try{let l=new Date(e.mtime),c=isNaN(l.getTime())?String(e.mtime):l.toISOString();s.push(` \u{1F552} Modified: ${c}${e.includeInContext?" \u2713":""}`)}catch{s.push(` \u{1F552} Modified: ${String(e.mtime)}${e.includeInContext?" \u2713":""}`)}}else e.source==="title-match"?s.push(` \u{1F516} Title match${e.includeInContext?" \u2713":""}`):s.push(` \u{1F4CA} ${a}: ${i}${e.includeInContext?" \u2713":""}`);let u=this.extractContentSnippet(e.content);return u&&s.push(` \u{1F4AC} "${u}${e.content?.length>150?"...":""}"`),e.path&&!e.path.endsWith(`/${n}.md`)&&s.push(` \u{1F4C1} ${e.path}`),s.join(`
`)}static formatBasicSearchItem(e,r){let n=e.title||e.path||`Result ${r+1}`,o=[`${r+1}. ${n}`],i=e.mtime||e.modified||e.modified_at||e.updated_at;return i&&o.push(` \u{1F552} Modified: ${String(i)}`),e.path&&e.path!==n&&o.push(` \u{1F4C1} ${e.path}`),o.join(`
`)}static extractContentSnippet(e,r=150){return e?(e.match(/NOTE BLOCK CONTENT:\s*([\s\S]*)/)?.[1]||e).substring(0,r).replace(/\s+/g," ").trim():""}static formatWebSearch(e){if(Array.isArray(e)&&e.length>0&&e[0].type==="web_search"){let r=["\u{1F310} Web Search Results"],n=e[0];return n.content&&(r.push(""),r.push(n.content)),n.citations&&n.citations.length>0&&(r.push(""),r.push("Sources:"),n.citations.forEach((o,i)=>{r.push(`[${i+1}] ${o}`)})),n.instruction&&(r.push(""),r.push(`Note: ${n.instruction}`)),r.join(`
`)}if(typeof e=="string"){let r=e.split(`
`),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(`
`)}return e}static formatYoutubeTranscription(e){let r;if(typeof e=="string")try{r=JSON.parse(e)}catch{return e}else if(typeof e=="object")r=e;else return String(e);if(r.success===!1)return`\u{1F4FA} YouTube Transcription Failed
${r.message}`;if(r.results&&Array.isArray(r.results)){let n=[`\u{1F4FA} YouTube Transcripts (${r.total_urls} video${r.total_urls>1?"s":""})`];n.push("");for(let o of r.results){if(o.success){n.push(`\u{1F4F9} Video: ${o.url}`),n.push("");let i=o.transcript.split(`
`),a=0;for(let s of i)if(s.trim()&&(s.match(/^\[(\d+:\d+)\]/)?(a>0&&n.push(""),n.push(`\u23F0 ${s}`)):n.push(` ${s.trim()}`),a++,a>30)){n.push(""),n.push("... (transcript truncated for display)");break}o.elapsed_time_ms&&(n.push(""),n.push(`Processing time: ${(o.elapsed_time_ms/1e3).toFixed(1)}s`))}else n.push(`\u274C Failed to transcribe: ${o.url}`),n.push(` ${o.message}`);n.push(""),n.push("---"),n.push("")}return n.join(`
`).trimEnd()}if(r.transcript){let n=["\u{1F4FA} YouTube Transcript"];n.push("");let o=r.transcript.split(`
`),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(`Processing time: ${(r.elapsed_time_ms/1e3).toFixed(1)}s`)),n.join(`
`)}return typeof e=="object"?JSON.stringify(e,null,2):String(e)}static formatWriteToFile(e){let r=typeof e=="object"?e.result:e,n=String(r).toLowerCase();return n.includes("accepted")?"\u2705 File change: accepted":n.includes("rejected")?"\u274C File change: rejected":typeof e=="object"&&e.message?e.message:String(r)}static formatReplaceInFile(e){let r=0,n="";if(typeof e=="object")r=e.blocksApplied||0,n=e.result||"";else if(typeof e=="string"){let i=e.match(/Applied (\d+) SEARCH\/REPLACE block/);i&&(r=parseInt(i[1])),n=e}let o=String(n).toLowerCase();if(o.includes("accepted")){let i=r===1?"replacement":"replacements";return r>0?`\u2705 ${r} ${i} accepted`:"\u2705 File replacements: accepted"}else if(o.includes("rejected"))return r===0?"\u274C No replacements made":"\u274C File replacements: rejected";return typeof e=="object"&&e.message?e.message:String(n)}static formatReadNote(e){let r=e;if(typeof e=="string")try{r=JSON.parse(e)}catch{r=null}let n=eYo(r);return n||(typeof e=="string"?e:JSON.stringify(e,null,2))}}});function tYo(t){return"children"in t&&"path"in t}function rYo(t){return"path"in t&&!("children"in t)}function nYo(t){let e=t.split(".");return e.length>1&&e.pop()?.toLowerCase()||""}function Ift(t,e=!0){let r=[],n={},o={},{inclusions:i,exclusions:a}=Xc();for(let u of t.children)if(rYo(u)){if(bl(u,i,a)){e&&r.push(u.name);let l=nYo(u.name)||"unknown";l&&(n[l]=(n[l]||0)+1)}}else if(tYo(u)){let l=Ift(u,e);if(Object.keys(l).length>0&&(o[u.name]=l[u.name],l[u.name].extensionCounts))for(let[c,d]of Object.entries(l[u.name].extensionCounts))n[c]=(n[c]||0)+d}let s={};return Object.keys(n).length>0&&(s.extensionCounts=n),e&&r.length>0&&(s.files=r),Object.keys(o).length>0&&(s.subFolders=o),Object.keys(s).length===0?{}:t.name?{[t.name]:s}:{vault:s}}var dBr,fBr=v(()=>{vb();sA();dx();dBr=t=>Yl({name:"getFileTree",description:"Get the file tree as a nested structure of folders and files",schema:Ct.void(),handler:async()=>{let e=Ift(t,!0),r=`A JSON represents the file tree as a nested structure:
* The root object has a key "vault" which contains a FileTreeNode object.
* Each FileTreeNode has these properties:
* files: An array of filenames in the current directory (if any files exist)
* subFolders: An object mapping folder names to their FileTreeNode objects (if any subfolders exist)
* extensionCounts: An object with counts of file extensions in this folder and all subfolders
`,n=JSON.stringify(e);if(n.length>5e5){let o=Ift(t,!1);return r+JSON.stringify(o)}return r+n},isBackground:!0})});var T7,Hq,eje=v(()=>{T7=require("obsidian");_t();ot();Zt();Qa();Hq=class{constructor(e){this.recentConversationsContent="";this.savedMemoriesContent="";this.isUpdatingMemory=!1;this.app=e}async loadMemory(){try{let e=this.app.vault.getAbstractFileByPath(this.getRecentConversationFilePath());e instanceof T7.TFile?this.recentConversationsContent=await this.app.vault.read(e):(this.recentConversationsContent="",B("[UserMemoryManager] Recent Conversations file not found, skipping memory load"));let r=this.app.vault.getAbstractFileByPath(this.getSavedMemoriesFilePath());r instanceof T7.TFile?this.savedMemoriesContent=await this.app.vault.read(r):(this.savedMemoriesContent="",B("[UserMemoryManager] Saved Memories file not found, skipping saved memory load"))}catch(e){ne("[UserMemoryManager] Error reading memory files:",e),this.recentConversationsContent="",this.savedMemoriesContent=""}}addRecentConversation(e,r){if(!ae().enableRecentConversations){Be("[UserMemoryManager] Recent history referencing is disabled, skipping analysis");return}if(e.length===0){Be("[UserMemoryManager] No messages to analyze for user memory");return}this.updateMemory(e,r).catch(o=>{ne("[UserMemoryManager] Background user memory operation failed:",o)})}async updateSavedMemory(e,r){if(!ae().enableSavedMemory)return{error:"Saved memory is disabled, skipping save"};if(!e||e.trim()==="")return{error:"No content provided for saved memory"};if(!r)return{error:"No chat model available, skipping save"};try{return await this.ensureMemoryFolderExists(),await this.updateSavedMemoryFile(this.getSavedMemoriesFilePath(),e,r)}catch(o){return{error:"Error saving memory: "+o.message}}}async getUserMemoryPrompt(){await this.loadMemory();try{let e=ae(),r="";return e.enableRecentConversations&&this.recentConversationsContent&&(r+=`<recent_conversations>
${this.recentConversationsContent}
</recent_conversations>
The current time is ${this.getTimestamp()}.
<recent_conversations> are the recent conversations between you and the user.
You can use it to provide more context for your responses.
Only use the recent conversations if they are relevant to the current conversation.`),e.enableSavedMemory&&this.savedMemoriesContent&&(r+=`<saved_memories>
${this.savedMemoriesContent}
</saved_memories>
<saved_memories> are important memories that the user explicitly asked you to remember.
Use these memories to provide more personalized and contextually relevant responses.`),r.length>0?r:null}catch(e){return ne("[UserMemoryManager] Error reading user memory content:",e),null}}getTimestamp(){let e=new Date,r=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0"),i=String(e.getHours()).padStart(2,"0"),a=String(e.getMinutes()).padStart(2,"0");return`${r}-${n}-${o} ${i}:${a}`}async createConversationSection(e,r){let{title:n,summary:o}=await this.extractTitleAndSummary(e,r),i=this.getTimestamp(),a=`## ${n}
`;return a+=`**Time:** ${i}
`,a+=`**Summary:** ${o}
`,a}async updateMemory(e,r){if(this.isUpdatingMemory){B("[UserMemoryManager] Memory update already in progress, skipping.");return}this.isUpdatingMemory=!0;try{if(await this.ensureMemoryFolderExists(),!r){ne("[UserMemoryManager] No chat model available, skipping memory update");return}if(e.length===0){B("[UserMemoryManager] No messages available, skipping memory update");return}let n=await this.createConversationSection(e,r);await this.addToRecentConversationsFile(this.getRecentConversationFilePath(),n)}catch(n){ne("[UserMemoryManager] Error analyzing chat messages for user memory:",n)}finally{this.isUpdatingMemory=!1}}async ensureMemoryFolderExists(){let r=ae().memoryFolderName;await xc(r)}getRecentConversationFilePath(){return`${ae().memoryFolderName}/Recent Conversations.md`}getSavedMemoriesFilePath(){return`${ae().memoryFolderName}/Saved Memories.md`}async updateSavedMemoryFile(e,r,n){let o=this.app.vault.getAbstractFileByPath(e),i=o instanceof T7.TFile?await this.app.vault.read(o):"";if(!n)return{error:"No chat model available, skipping memory update"};let a=`You maintain a user's long-term personal memory list as concise bullet points.
You task is to update the user's memory list with the new statement.
Rules:
- Keep only stable, evergreen facts or preferences that will help future conversations.
- Remove duplicates and near-duplicates by merging them into one concise statement.
- If the new statement conflicts with older ones, keep the most recent truth and remove obsolete/conflicting entries.
- Prefer short, specific, and unambiguous phrasing.
- Preserve the language used in the input memories.
- Output only the memory content with each as a bullet point.
# OUTPUT FORMAT
Return the updated memory list with each as a bullet point.
- memory item 1
- memory item 2
- memory item 3
...
`,s=`<current_memories>
${i.trim()}
</current_memories>
<new_statement>
${r.trim()}
</new_statement>
`,u=[new Qm(a),new Hs(s)],l=null;try{l=(await n.invoke(u)).text??""}catch(c){return{error:"LLM call failed while updating saved memories: "+c.message}}return l==null||l.trim()===""?{error:"Empty content returned from LLM"}:(o instanceof T7.TFile?await this.app.vault.modify(o,l):await this.app.vault.create(e,l),{content:l})}async addToRecentConversationsFile(e,r){let n=this.app.vault.getAbstractFileByPath(e);if(n instanceof T7.TFile){let o=await this.app.vault.read(n),i;if(o.trim()==="")i=`${r.trim()}
`;else{let a=this.parseExistingConversations(o);a.push(r);let u=ae().maxRecentConversations;a.length>u&&a.splice(0,a.length-u),i=`${a.map(c=>c.trim()).join(`
`)}
`}await this.app.vault.modify(n,i)}else{let o=`${r.trim()}
`;await this.app.vault.create(e,o)}}parseExistingConversations(e){let r=e.split(`
`),n=[],o=[];for(let i of r)i.trim().startsWith("## ")?(o.length>0&&n.push(o.join(`
`).trim()),o=[i]):o.length>0&&o.push(i);return o.length>0&&n.push(o.join(`
`).trim()),n}extractJsonFromResponse(e){let r=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);if(r)return r[1].trim();let n=e.match(/\{[\s\S]*\}/);return n?n[0]:e}async extractTitleAndSummary(e,r){let n=e.map(s=>`${s.sender}: ${s.message}`).join(`
`),o=`Your task is to analyze a conversation and generate both a title and a summary.
# OUTPUT FORMAT
You must return your response in the following JSON format:
{
"title": "Brief 2-8 word title capturing the main user intent",
"summary": "2-3 sentence summary at most including key details (e.g. user facts mentioned entities), and key conclusions if there are any."
}
# RULES
* Use the same language as the conversation`,i=`<conversation_text>
${n}
</conversation_text>
Generate a title and summary for this conversation:`,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:`Memory updated successfully into ${e.getSavedMemoriesFilePath()}: ${n.content}`}}catch(e){return ne("[updateMemoryTool] Error updating memory:",e),{success:!1,message:`Failed to save memory: ${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: failed to read ${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})}return i}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(typeof t=="string"){let e=t.trim();if(e.length===0)return;let r=Number(e);return Number.isFinite(r)?r:t}return t},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})=>{let r=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."};let n=await sYo(r);if(n.type==="not_found")return Be(`readNote: note not found or not a file (${r})`),{notePath:r,status:"not_found",message:`Note "${r}" was not found or is not a readable file.`};if(n.type==="not_unique")return Be(`readNote: ambiguous note path "${r}" matched multiple files`,n.matches.map(f=>f.path)),{notePath:r,status:"not_unique",message:`Multiple notes match "${r}". Provide a more specific path.`,candidates:n.matches.map(f=>({path:f.path,title:f.basename}))};let o=n.file,i=o.path,a=await uYo(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};let l=s[e];B(`readNote: returning chunk ${l.chunkIndex} of ${u} for ${i}`);let c=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:void 0}}})});async function jft(t,e,r){try{if(!t||!t.name)return{toolName:t?.name||"unknown",result:"Error: Invalid tool call - missing tool name",success:!1};let o=e.find(u=>u.name===t.name);if(!o){let u=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};let i={...t.args};o.requiresUserMessageContent&&r&&(i._userMessageContent=r);let a=6e4;typeof o.timeoutMs=="number"&&(a=o.timeoutMs);let s;return!a||a===1/0?s=await RD.callTool(o,i):s=await Promise.race([RD.callTool(o,i),new Promise((u,l)=>setTimeout(()=>l(new Error(`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:typeof s=="string"?s:JSON.stringify(s),success:!0}}catch(o){return ne(`Error executing tool ${t.name}:`,o),{toolName:t.name,result:`Error: ${Sn(o)}`,success:!1}}}function QH(t){return t==="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}function E7(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({success:!0,message:`Semantic search index has been refreshed with ${r} documents.`,documentCount:r})}catch(e){return JSON.stringify({success:!1,message:`Failed to index with semantic search: ${e.message}`})}else return`The tiered lexical retriever builds indexes on demand and doesn't require manual indexing.
`+JSON.stringify({success:!0,message:"Tiered lexical retriever uses on-demand indexing. No manual indexing required."})},isBackground:!0}),gYo=Ct.object({query:Ct.string().min(1).describe("The search query"),chatHistory:Ct.array(Ct.object({role:Ct.enum(["user","assistant"]),content:Ct.string()})).describe("Previous conversation turns")}),oje=Yl({name:"webSearch",description:"Search the web for information",schema:gYo,isPlusOnly:!0,handler:async({query:t,chatHistory:e})=>{try{let r=await FTe(t,e),n=await pc.getInstance().webSearch(r),o=n.response.citations||[],a=[{type:"web_search",content:n.response.choices[0].message.content,citations:o,instruction:kUr()}];return JSON.stringify(a)}catch(r){return console.error(`Error processing web search query ${t}:`,r),""}}})});function _Yo(){return typeof app>"u"||!app?.metadataCache?null:app.metadataCache}function yBr(t){let e={};if(!t)return e;for(let[r,n]of Object.entries(t)){let o=r?.trim();if(!o)continue;let i=o.replace(/^#+/,"").trim().toLowerCase();if(!i)continue;let a=`#${i}`;if(a==="#")continue;let s=Number.isFinite(n)?Math.max(0,Math.floor(n)):0;e[a]=(e[a]||0)+s}return e}function vYo(t,e,r){let n=t,o=yBr(n.getFrontmatterTags?.()),i=e?yBr(n.getTags?.()):{},a=new Set([...Object.keys(o),...e?Object.keys(i):[]]),s=[],u=0;for(let c of a){let d=o[c]??0,f=e?Math.max(0,i[c]??0):0,p=0,m=d;e&&(f>=d?(p=f-d,m=f):f>0&&(p=f,m=d+p)),m!==0&&(u+=m,s.push({tag:c,occurrences:m,frontmatterOccurrences:d,inlineOccurrences:p}))}s.sort((c,d)=>d.occurrences===c.occurrences?c.tag.localeCompare(d.tag):d.occurrences-c.occurrences);let l=s.slice(0,r);return{totalUniqueTags:s.length,returnedTagCount:l.length,totalOccurrences:u,includedSources:e?["frontmatter","inline"]:["frontmatter"],truncated:l.length<s.length,tags:l}}function wYo(t){let e=t,r=JSON.stringify(e);if(r.length<=kft)return e;let n=e.tags.length;for(;r.length>kft&&n>gBr;)n=Math.max(gBr,Math.floor(n/2)),e={...e,tags:t.tags.slice(0,n),returnedTagCount:n,truncated:!0},r=JSON.stringify(e);return r.length>kft?{totalUniqueTags:t.totalUniqueTags,returnedTagCount:0,totalOccurrences:t.totalOccurrences,includedSources:t.includedSources,truncated:!0,tags:[],note:"Tag list exceeded the size limit. Request a narrower scope or specify a smaller maxEntries value."}:e}function bBr(t){return`A JSON object lists the vault tags and their occurrence counts:
* totalUniqueTags: number of unique tags indexed across the vault
* returnedTagCount: number of tag entries included in this response
* totalOccurrences: total tag occurrences across included sources
* includedSources: sources represented in the counts (frontmatter, inline)
* truncated: whether the list was shortened due to limits
* tags: array of tag objects { tag, occurrences, frontmatterOccurrences, inlineOccurrences }
${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=
tags: ${JSON.stringify(Array.from(this._tags).sort())},
knownValues: ${JSON.stringify(this.knownValues)},
impliedValues: ${JSON.stringify(this.impliedValues)}},
reference: ${JSON.stringify(this.reference)}]`}dayjs(){return(0,Fue.default)(this.date())}date(){let e=this.dateWithoutTimezoneAdjustment(),r=this.reference.getSystemTimezoneAdjustmentMinute(e,this.get("timezoneOffset"));return new Date(e.getTime()+r*6e4)}addTag(e){return this._tags.add(e),this}addTags(e){for(let r of e)this._tags.add(r);return this}tags(){return new Set(this._tags)}dateWithoutTimezoneAdjustment(){let e=new Date(this.get("year"),this.get("month")-1,this.get("day"),this.get("hour"),this.get("minute"),this.get("second"),this.get("millisecond"));return e.setFullYear(this.get("year")),e}static createRelativeFromReference(e,r){let n=(0,Fue.default)(e.instant);for(let i in r)n=n.add(r[i],i);let o=new t(e);return r.hour||r.minute||r.second?(ije(o,n),px(o,n),e.timezoneOffset!==null&&o.assign("timezoneOffset",-e.instant.getTimezoneOffset())):(P7(o,n),e.timezoneOffset!==null&&o.imply("timezoneOffset",-e.instant.getTimezoneOffset()),r.d?(o.assign("day",n.date()),o.assign("month",n.month()+1),o.assign("year",n.year())):r.week?(o.assign("day",n.date()),o.assign("month",n.month()+1),o.assign("year",n.year()),o.imply("weekday",n.day())):(o.imply("day",n.date()),r.month?(o.assign("month",n.month()+1),o.assign("year",n.year())):(o.imply("month",n.month()+1),r.year?o.assign("year",n.year()):o.imply("year",n.year())))),o}},AD=class t{constructor(e,r,n,o,i){this.reference=e,this.refDate=e.instant,this.index=r,this.text=n,this.start=o||new Za(e),this.end=i}clone(){let e=new t(this.reference,this.index,this.text);return e.start=this.start?this.start.clone():null,e.end=this.end?this.end.clone():null,e}date(){return this.start.date()}tags(){let e=new Set(this.start.tags());if(this.end)for(let r of this.end.tags())e.add(r);return e}toString(){let e=Array.from(this.tags()).sort();return`[ParsingResult {index: ${this.index}, text: '${this.text}', tags: ${JSON.stringify(e)} ...}]`}}});function Jft(t,e,r="\\s{0,5},?\\s{0,5}"){let n=e.replace(/\((?!\?)/g,"(?:");return`${t}${n}(?:${r}${n}){0,10}`}function CYo(t){let e;return t instanceof Array?e=[...t]:t instanceof Map?e=Array.from(t.keys()):e=Object.keys(t),e}function jg(t){return`(?:${CYo(t).sort((r,n)=>n.length-r.length).join("|").replace(/\./g,"\\.")})`}var Zq=v(()=>{});function sje(t){return t<100&&(t>50?t=t+1900:t=t+2e3),t}function Yq(t,e,r){let n=(0,OBr.default)(t),o=n;o=o.month(r-1),o=o.date(e),o=o.year(n.year());let i=o.add(1,"y"),a=o.add(-1,"y");return Math.abs(i.diff(n))<Math.abs(o.diff(n))?o=i:Math.abs(a.diff(n))<Math.abs(o.diff(n))&&(o=a),o.year()}var OBr,I7=v(()=>{OBr=L(Wq(),1)});function xYo(t){let e=t.toLowerCase();return Wft[e]!==void 0?Wft[e]:e==="a"||e==="an"||e=="the"?1:e.match(/few/)?3:e.match(/half/)?.5:e.match(/couple/)?2:e.match(/several/)?7:parseFloat(e)}function A7(t){let e=t.toLowerCase();return Kft[e]!==void 0?Kft[e]:(e=e.replace(/(?:st|nd|rd|th)$/i,""),parseInt(e))}function eU(t){if(/BE/i.test(t))return t=t.replace(/BE/i,""),parseInt(t)-543;if(/BCE?/i.test(t))return t=t.replace(/BCE?/i,""),-parseInt(t);if(/(AD|CE)/i.test(t))return t=t.replace(/(AD|CE)/i,""),parseInt(t);let e=parseInt(t);return sje(e)}function d0(t){let e={},r=t,n=TBr.exec(r);for(;n;)TYo(e,n),r=r.substring(n[0].length).trim(),n=TBr.exec(r);return Object.keys(e).length==0?null:e}function TYo(t,e){if(e[0].match(/^[a-zA-Z]+$/))return;let r=xYo(e[1]),n=kue[e[2].toLowerCase()];t[n]=r}var Gft,Xft,c0,Wft,Kft,EBr,kue,PBr,R7,Qq,MBr,TBr,OYo,IBr,ND,tU,qm=v(()=>{Zq();I7();Gft={sunday:0,sun:0,"sun.":0,monday:1,mon:1,"mon.":1,tuesday:2,tue:2,"tue.":2,wednesday:3,wed:3,"wed.":3,thursday:4,thurs:4,"thurs.":4,thur:4,"thur.":4,thu:4,"thu.":4,friday:5,fri:5,"fri.":5,saturday:6,sat:6,"sat.":6},Xft={january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12},c0={...Xft,jan:1,"jan.":1,feb:2,"feb.":2,mar:3,"mar.":3,apr:4,"apr.":4,jun:6,"jun.":6,jul:7,"jul.":7,aug:8,"aug.":8,sep:9,"sep.":9,sept:9,"sept.":9,oct:10,"oct.":10,nov:11,"nov.":11,dec:12,"dec.":12},Wft={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:
EXAMPLES OF CORRECT USAGE:
- "what time is it" \u2192 No parameter (uses local time)
- "what time is it in Tokyo" \u2192 timezoneOffset: "+9"
- "what time is it in Beijing" \u2192 timezoneOffset: "+8"
- "what time is it in New York" \u2192 timezoneOffset: "-5" (or "-4" during DST)
- "what time is it in Mumbai" \u2192 timezoneOffset: "+5:30"
SUPPORTED FORMATS:
- Simple: "+8", "-5", "+5:30"
- With prefix: "UTC+8", "GMT-5", "UTC+5:30"
COMMON TIMEZONE OFFSETS:
- Tokyo: UTC+9
- Beijing/Singapore: UTC+8
- Mumbai: UTC+5:30
- Dubai: UTC+4
- London: UTC+0 (UTC+1 during BST)
- New York: UTC-5 (UTC-4 during DST)
- 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.
COMMON EXPRESSIONS:
- Relative past: "yesterday", "last week", "last month", "last year"
- Relative ranges: "this week", "this month", "this year"
- Specific dates: "July 1", "July 1 2023", "2023-07-01"
- Date ranges: "from July 1 to July 15", "between May and June"
- Time periods: "last 7 days", "past 30 days", "previous 3 months"
IMPORTANT: This tool is typically used as the first step before localSearch when searching notes by time.
EXAMPLE WORKFLOW:
1. User: "what did I do last week"
2. First call getTimeRangeMs with timeExpression: "last week"
3. Then use the returned time range with localSearch`)}),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:
- 12-hour: "6pm", "3:30 PM", "11:45 am"
- 24-hour: "18:00", "15:30", "23:45"
- Relative: "noon", "midnight"`),fromOffset:Ct.string().describe(`Source UTC offset. Must be numeric, not timezone name.
Examples: "-8" for PT, "+0" for London, "+8" for Beijing`),toOffset:Ct.string().describe(`Target UTC offset. Must be numeric, not timezone name.
Examples: "+9" for Tokyo, "-5" for NY, "+5:30" for Mumbai
EXAMPLE USAGE:
- "what time is 6pm PT in Tokyo" \u2192 time: "6pm", fromOffset: "-8", toOffset: "+9"
- "convert 3:30 PM EST to London time" \u2192 time: "3:30 PM", fromOffset: "-5", toOffset: "+0"
- "what is 9am Beijing time in New York" \u2192 time: "9am", fromOffset: "+8", toOffset: "-5"`)}),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 to browse the vault's file structure including paths of notes and folders
- Always call this tool to explore the exact path of notes or folders when you are not given the exact path.
- DO NOT use this tool to look up note contents or metadata - use localSearch or readNote instead.
- No parameters needed
Example usage:
<use_tool>
<name>getFileTree</name>
</use_tool>
Example queries that should use getFileTree:
- "Create a new note in the projects folder" -> call getFileTree to get the exact folder path of projects folder
- "Create a new note using the quick note template" -> call getFileTree to look up the exact folder path of the quick note template
- "How many files are in the projects folder" -> call getFileTree to list all files in the projects folder
`}})}function gti(){bd.getInstance().register({tool:_Br(),metadata:{id:"getTagList",displayName:"Tag List",description:"List vault tags with occurrence statistics",category:"file",isAlwaysEnabled:!0,requiresVault:!0,customPromptInstructions:`For getTagList:
- Use to inspect existing tags before suggesting new ones or reorganizing notes.
- Omit parameters to include both frontmatter and inline tags.
- Set includeInline to false when you only need frontmatter-defined tags.
- Use maxEntries to limit output for very large vaults.
Example usage (default):
<use_tool>
<name>getTagList</name>
</use_tool>
Example usage (frontmatter only):
<use_tool>
<name>getTagList</name>
<includeInline>false</includeInline>
</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 this tool to update the memory when the user explicitly asks to update the memory
- DO NOT use for general information - only for personal facts, preferences, or specific things the user wants stored
Example usage:
<use_tool>
<name>updateMemory</name>
<statement>I'm studying Japanese and I'm preparing for JLPT N3</statement>
</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):
- You MUST always provide both "query" (string) and "salientTerms" (array of strings)
- salientTerms MUST be extracted from the user's original query - never invent new terms
- They are keywords used for BM25 full-text search to find notes containing those exact words
- Treat every token that begins with "#" as a high-priority salient term. Keep the leading "#" and the full tag hierarchy (e.g., "#project/phase1").
- Include tagged terms alongside other meaningful words; never strip hashes or rewrite tags into plain words.
- Extract meaningful content words from the query (nouns, verbs, names, etc.)
- Exclude common words like "what", "I", "do", "the", "a", etc.
- Exclude time expressions like "last month", "yesterday", "last week"
- Preserve the original language - do NOT translate terms to English
Example usage:
<use_tool>
<name>localSearch</name>
<query>piano learning practice</query>
<salientTerms>["piano", "learning", "practice"]</salientTerms>
</use_tool>
For localSearch with tags in the query (e.g., "#projectx status update"):
<use_tool>
<name>localSearch</name>
<query>#projectx status update</query>
<salientTerms>["#projectx", "status", "update"]</salientTerms>
</use_tool>
For localSearch with time range (e.g., "what did I do last week"):
Step 1 - Get time range:
<use_tool>
<name>getTimeRangeMs</name>
<timeExpression>last week</timeExpression>
</use_tool>
Step 2 - Search with time range (after receiving time range result):
<use_tool>
<name>localSearch</name>
<query>what did I do</query>
<salientTerms>[]</salientTerms>
<timeRange>{"startTime": {...}, "endTime": {...}}</timeRange>
</use_tool>
For localSearch with meaningful terms (e.g., "python debugging notes from yesterday"):
Step 1 - Get time range:
<use_tool>
<name>getTimeRangeMs</name>
<timeExpression>yesterday</timeExpression>
</use_tool>
Step 2 - Search with time range:
<use_tool>
<name>localSearch</name>
<query>python debugging notes</query>
<salientTerms>["python", "debugging", "notes"]</salientTerms>
<timeRange>{"startTime": {...}, "endTime": {...}}</timeRange>
</use_tool>
For localSearch with non-English query (PRESERVE ORIGINAL LANGUAGE):
<use_tool>
<name>localSearch</name>
<query>\u94A2\u7434\u5B66\u4E60</query>
<salientTerms>["\u94A2\u7434", "\u5B66\u4E60"]</salientTerms>
</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:
- ONLY use when the user's query contains explicit web-search intent like:
* "web search", "internet search", "online search"
* "Google", "search online", "look up online", "search the web"
- Always provide an empty chatHistory array
Example - "search the web for python tutorials":
<use_tool>
<name>webSearch</name>
<query>python tutorials</query>
<chatHistory>[]</chatHistory>
</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):
- If the user mentions a specific city, country, or timezone name (e.g., "Tokyo", "Japan", "JST"), you MUST convert it to the correct UTC offset and pass it via the timezoneOffset parameter (e.g., "+9").
- Only omit timezoneOffset when the user asks for the current local time without naming any location or timezone.
- If you cannot confidently determine the offset from the user request, ask the user to clarify before calling the tool.
Example 1 - "what time is it" (local time):
<use_tool>
<name>getCurrentTime</name>
</use_tool>
Example 2 - "what time is it in Tokyo" (UTC+9):
<use_tool>
<name>getCurrentTime</name>
<timezoneOffset>+9</timezoneOffset>
</use_tool>
Example 3 - "what time is it in New York" (UTC-5 or UTC-4 depending on DST):
<use_tool>
<name>getCurrentTime</name>
<timezoneOffset>-5</timezoneOffset>
</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 this tool to convert time expressions like "last week", "yesterday", "last month" to proper time ranges
- This is typically the first step before using localSearch with a time range
Example:
<use_tool>
<name>getTimeRangeMs</name>
<timeExpression>last week</timeExpression>
</use_tool>`}},{tool:m2r,metadata:{id:"convertTimeBetweenTimezones",displayName:"Convert Timezones",description:"Convert time between different timezones",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For timezone conversions:
Example - "what time is 6pm PT in Tokyo" (PT is UTC-8 or UTC-7, Tokyo is UTC+9):
<use_tool>
<name>convertTimeBetweenTimezones</name>
<time>6pm</time>
<fromOffset>-8</fromOffset>
<toOffset>+9</toOffset>
</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:
- Decide based on the user's request: only call this tool when the question requires reading note content.
- If the user asks about a note title that is already mentioned in the current or previous turns of the conversation, or linked in <active_note> or <note_context> blocks, call readNote directly\u2014do not use localSearch to look it up. Even if the note title mention is partial but similar to what you have seen in the context, try to infer the correct note path from context. Skip the tool when a note is irrelevant to the user query.
- If the user asks about notes linked from that note, read the original note first, then follow the "linkedNotes" paths returned in the tool result to inspect those linked notes.
- Always start with chunk 0 (omit <chunkIndex> or set it to 0). Only request the next chunk if the previous chunk did not answer the question.
- Pass vault-relative paths without a leading slash. If a call fails, adjust the path (for example, add ".md" or use an alternative candidate) and retry only if necessary.
- Every tool result may include a "linkedNotes" array. If the user needs information from those linked notes, call readNote again with one of the provided candidate paths, starting again at chunk 0. Do not expand links you don't need.
- Stop calling readNote as soon as you have the required information.
- Always call getFileTree to get the exact note path if it is not provided in the context before calling readNote.
Example (first chunk):
<use_tool>
<name>readNote</name>
<notePath>Projects/launch-plan.md</notePath>
</use_tool>
Example (next chunk):
<use_tool>
<name>readNote</name>
<notePath>Projects/launch-plan.md</notePath>
<chunkIndex>1</chunkIndex>
</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:
- NEVER display the file content directly in your response
- Always pass the complete file content to the tool
- Include the full path to the file
- You MUST explicitly call writeToFile for any intent of updating or creating files
- Do not call writeToFile tool again if the result is not accepted
- Do not call writeToFile tool if no change needs to be made
- Always create new notes in root folder or folders the user explicitly specifies
- When creating a new note in a folder, you MUST use getFileTree to get the exact folder path first
Example usage:
<use_tool>
<name>writeToFile</name>
<path>path/to/note.md</path>
<content>FULL CONTENT OF THE NOTE</content>
</use_tool>
Example usage with user explicitly asks to skip preview or confirmation:
<use_tool>
<name>writeToFile</name>
<path>path/to/note.md</path>
<content>FULL CONTENT OF THE NOTE</content>
<confirmation>false</confirmation>
</use_tool>
`}},{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:`For replaceInFile:
- Remember: Small edits \u2192 replaceInFile, Major rewrites \u2192 writeToFile
- SEARCH text must match EXACTLY including all whitespace
Example usage:
<use_tool>
<name>replaceInFile</name>
<path>notes/meeting.md</path>
<diff>
------- SEARCH
## Attendees
- John Smith
- Jane Doe
=======
## Attendees
- John Smith
- Jane Doe
- Bob Johnson
+++++++ REPLACE
</diff>
</use_tool>`}},{tool:y2r,metadata:{id:"youtubeTranscription",displayName:"YouTube Transcription",description:"Get transcripts from YouTube videos",category:"media",customPromptInstructions:`For youtubeTranscription:
- Use when user provides YouTube URLs
- No parameters needed - the tool will process URLs from the conversation
Example usage:
<use_tool>
<name>youtubeTranscription</name>
</use_tool>`}}]});var $je,_2r=v(()=>{Due();$je=class{constructor(e,r){this.toolManager=e;this.writeToFileTool=r;this.buffer=""}findCompleteBlock(e){let r=/<writeToFile>[\s\S]*?<\/writeToFile>/,n=e.match(r);return!n||n.index===void 0?null:{block:n[0],endIdx:n.index+n[0].length}}async*processChunk(e){let r="";if(Array.isArray(e.content))for(let o of e.content)o.type==="text"&&o.text!=null&&(r+=o.text);else e.content!=null&&(r=e.content);r&&(this.buffer+=r),yield e;let n=this.findCompleteBlock(this.buffer);for(;n;){let{block:o,endIdx:i}=n,a=o.match(/<path>([\s\S]*?)<\/path>/),s=o.match(/<content>([\s\S]*?)<\/content>/),u=a?a[1].trim():void 0,l=s?s[1].trim():void 0;try{let c=await this.toolManager.callTool(this.writeToFileTool,{path:u,content:l}),d=fx.format("writeToFile",c);yield{...e,content:`
${d}
`}}catch(c){yield{...e,content:`
Error: ${c?.message||c}
`}}this.buffer=this.buffer.substring(i),n=this.findCompleteBlock(this.buffer)}}}});function Ypt(t){if(!Array.isArray(t))return"";let e=t.filter(n=>n.includeInContext!==!1);return e.length===0?"No relevant documents found.":e.map((n,o)=>{let i=n.title||"Untitled",a=n.path||"",s=n.__sourceId||n.source_id||o+1,u=null;if(n.mtime){let l=new Date(n.mtime);isNaN(l.getTime())||(u=l.toISOString())}return`<document>
<id>${s}</id>
<title>${i}</title>${a&&a!==i?`
<path>${a}</path>`:""}${u?`
<modified>${u}</modified>`:""}
<content>
${n.content||""}
</content>
</document>`}).filter(n=>n.length>0).join(`
`)}function v2r(t){try{let e=JSON.parse(t);return Array.isArray(e)?Ypt(e):"Invalid search results format."}catch(e){return Be("Failed to format localSearch result string:",e),"Error processing search results."}}function w2r(t){return Array.isArray(t)?t.map(e=>({title:e.title||e.path||"Untitled",path:e.path||e.title||"",score:e.rerank_score||e.score||0,explanation:e.explanation||null})):[]}function bti(t){if(typeof t=="number"){let e=new Date(t);return isNaN(e.getTime())?"":e.toISOString()}if(typeof t=="string"){let e=new Date(t);return isNaN(e.getTime())?"":e.toISOString()}return""}function _ti(t){if(!t)return"";let e=[];try{if(Array.isArray(t.lexicalMatches)&&t.lexicalMatches.length>0){let r=new Set,n=new Set;for(let a of t.lexicalMatches)a?.field&&r.add(String(a.field)),a?.query&&n.add(String(a.query));let o=Array.from(r).join("/"),i=Array.from(n).slice(0,3).join(", ");e.push(`Lexical(${o}): ${i}${n.size>3?", ...":""}`)}if(typeof t.semanticScore=="number"&&t.semanticScore>0&&e.push(`Semantic: ${(t.semanticScore*100).toFixed(1)}%`),t.folderBoost&&typeof t.folderBoost.boostFactor=="number"){let r=t.folderBoost,n=r.folder||"root";e.push(`Folder +${r.boostFactor.toFixed(2)} (${n})`)}if(t.graphConnections&&typeof t.graphConnections=="object"){let r=t.graphConnections,n=[];r.backlinks>0&&n.push(`${r.backlinks} backlinks`),r.coCitations>0&&n.push(`${r.coCitations} co-cites`),r.sharedTags>0&&n.push(`${r.sharedTags} tags`),typeof r.score=="number"?e.push(`Graph ${r.score.toFixed(1)}${n.length?` (${n.join(", ")})`:""}`):n.length&&e.push(`Graph (${n.join(", ")})`)}if(t.graphBoost&&typeof t.graphBoost.boostFactor=="number"&&!t.graphConnections){let r=t.graphBoost;e.push(`Graph +${r.boostFactor.toFixed(2)} (${r.connections} connections)`)}typeof t.baseScore=="number"&&typeof t.finalScore=="number"&&t.baseScore!==t.finalScore&&e.push(`Score: ${t.baseScore.toFixed(4)}\u2192${t.finalScore.toFixed(4)}`)}catch{}return e.join(" | ")}function S2r(t){if(!Array.isArray(t)||t.length===0){B("Search Results: (none)");return}let e=0,r=t.map((u,l)=>{let c=bti(u.mtime),d=typeof u.rerank_score=="number"?u.rerank_score:u.score||0,f=(Number.isFinite(d)?d:0).toFixed(4),p=u.chunkId||u.path||"",m=_ti(u.explanation),h=u.includeInContext!==!1;return h&&e++,{idx:String(l+1),in:h?"Y":"",path:p,mtime:c,score:f,explanation:m}}),n=r.length;B(`Search Results (debug table): ${n} rows; in-context ${e}/${n}`),_Rt(r,["idx","in","path","mtime","score","explanation"]);let o=u=>String(u||"").replace(/\|/g,"\\|"),i="| # | IN | PATH | MTIME | SCORE | EXPLANATION |",a="| ---: | :-: | --- | --- | ---: | --- |",s=r.map(u=>`| ${u.idx} | ${u.in} | ${o(u.path)} | ${u.mtime||""} | ${u.score} | ${o(u.explanation)} |`);ige(["",`Results: ${n} rows; in-context ${e}/${n}`,"",i,a,...s,""])}var C2r=v(()=>{_t()});function x2r(t,e){return[t,e].map(n=>n?.trim()).filter(n=>!!n).join(`
`)}function O2r(t,e){let r=t?`
${t}
`:"";return`<localSearch${e?` timeRange="${e}"`:""}>${r}</localSearch>`}function Qpt(t,e){let r=t.trim();return r?`${r}
${e}`:e}function T2r(t,e){let r=e.trim();return!r||t.includes(r)?t:Qpt(t,`[User query]:
${r}`)}var emt=v(()=>{});function E2r(t){let e=[],r=0;for(;r<t.length;){let n=t.indexOf("![",r);if(n===-1)break;let o=Sti(t,n+2);if(o===null){r=n+2;continue}let i=o+1;for(;i<t.length&&Lje(t[i]);)i++;if(t[i]!=="("){r=i;continue}let a=Cti(t,i);if(a===null){r=i+1;continue}let s=vti(t.slice(i+1,a));s&&e.push(s),r=a+1}return e}function vti(t){let e=t.trim();if(e.length===0)return null;if(e.startsWith("<")){let n=xti(e,0);if(n===null)return null;let o=e.slice(1,n).trim();return o.length>0?o:null}let r=wti(e).trim();return r.length>0?r:null}function wti(t){let e=t.trimEnd();if(e.length===0)return"";let r=e[e.length-1];if(r==='"'||r==="'"){let o=Oti(e,r,e.length-1);if(o!==null){let i=e.slice(0,o);if(i.length>0&&Lje(i[i.length-1]))return i.trimEnd()}}if(r===")"){let n=Tti(e);if(n!==null){let o=e.slice(0,n);if(o.length>0&&Lje(o[o.length-1]))return o.trimEnd()}}return e}function Sti(t,e){let r=e,n=0;for(;r<t.length;){let o=t[r];if(o==="\\"){r+=2;continue}if(o==="["){n++,r++;continue}if(o==="]"){if(n===0)return r;n--,r++;continue}r++}return null}function Cti(t,e){let r=e+1,n=1,o=!0,i=!1;for(;r<t.length;){let a=t[r];if(i){if(a==="\\"){r+=2;continue}if(a===">"){i=!1,o=!1,r++;continue}r++;continue}if(o){if(Lje(a)){r++;continue}if(a==="<"){i=!0,r++;continue}o=!1}if(a==="\\"){r+=2;continue}if(a==="("){n++,r++;continue}if(a===")"){if(n--,n===0)return r;r++;continue}r++}return null}function xti(t,e){for(let r=e+1;r<t.length;r++){let n=t[r];if(n==="\\"){r++;continue}if(n===">")return r}return null}function Oti(t,e,r){for(let n=r-1;n>=0;n--)if(t[n]===e&&!P2r(t,n))return n;return null}function Tti(t){if(t.length===0||t[t.length-1]!==")")return null;let e=0;for(let r=t.length-1;r>=0;r--){let n=t[r];if(!((n===")"||n==="(")&&P2r(t,r))){if(n===")"){e++;continue}if(n==="("&&(e--,e===0))return r}}return null}function P2r(t,e){let r=0;for(let n=e-1;n>=0&&t[n]==="\\";n--)r++;return r%2===1}function Lje(t){return t===" "||t===" "||t===`
`||t==="\r"}var M2r=v(()=>{});function cJ(t){return t.map(e=>e.content).filter(e=>e&&e.trim().length>0).join(`
`)}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}: call the tool named ${n.id}`);return r.length===0?null:["When the user explicitly includes a Copilot command alias (e.g., @vault) in their message, treat it as a direct request to call the mapped tool before proceeding.","Honor these aliases exactly (case-insensitive):",...r,"If the referenced tool is unavailable, explain that the command cannot be fulfilled instead of ignoring it."].join(`
`)}enhanceSystemPrompt(e,r,n,o){let i=this.buildSystemPromptSections(e,r,n,o);return cJ(i)}buildSystemPromptSections(e,r,n,o){let i=o||[],a=this.buildToolSpecificInstructions(i).trim(),u=[{id:"base-system-prompt",label:"System prompt with memory",source:"src/system-prompts/systemPromptBuilder.ts#getSystemPromptWithMemory",content:e.trimEnd()},{id:"autonomous-agent-intro",label:"Autonomous agent introduction",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildSystemPromptSections",content:`# Autonomous Agent Mode
You are now in autonomous agent mode. You can use tools to gather information and complete tasks step by step.
When you need to use a tool, format it EXACTLY like this:
<use_tool>
<name>tool_name_here</name>
<parameter_name>value</parameter_name>
<another_parameter>["array", "values"]</another_parameter>
</use_tool>
IMPORTANT: Use the EXACT parameter names as shown in the tool descriptions below. Do NOT use generic names like "param1" or "param".
`}],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:`Available tools:
${l}`}),u.push({id:"tool-usage-guidelines",label:"Tool usage guidelines",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildSystemPromptSections",content:`# Tool Usage Guidelines
## Time-based Queries
When users ask about temporal periods (e.g., "what did I do last month", "show me notes from last week"), you MUST:
1. First call getTimeRangeMs to convert the time expression to a proper time range
2. Then use localSearch with the timeRange parameter from step 1
3. For salientTerms, ONLY use words that exist in the user's original query (excluding time expressions)
Example for "what did I do last month":
1. Call getTimeRangeMs with timeExpression: "last month"
2. Use localSearch with query matching the user's question
3. salientTerms: [] - empty because "what", "I", "do" are not meaningful search terms
Example for "meetings about project X last week":
1. Call getTimeRangeMs with timeExpression: "last week"
2. Use localSearch with query "meetings about project X"
3. salientTerms: ["meetings", "project", "X"] - these words exist in the original query
## File-related Queries
### Handle ambiguity in folder/note paths
When user mentions a folder name (e.g., "meetings folder") or a note name (e.g., "meeting note template") without providing an exact path,
you MUST first call getFileTree to find the folder or notes best matching the user's query.
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'll receive the results and can decide whether to use more tools or provide your final response.
Always explain your reasoning before using tools. Be conversational and clear about what you're doing.
When you've gathered enough information, provide your final response without any tool calls.
IMPORTANT: Do not include any code blocks (\`\`\`) or tool_code blocks in your responses. Only use the <use_tool> format for tool calls.
NOTE: Use individual XML parameter tags. For arrays, use JSON format like ["item1", "item2"].`}),u}enhanceUserMessage(e,r){return e}needsSpecialHandling(){return!1}},tmt=class extends lJ{isGPT5Model(){return this.modelName.includes("gpt-5")||this.modelName.includes("gpt5")}buildSystemPromptSections(e,r,n,o){let i=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.");let l=u.join(`
`);return i.push({id:"gpt-specific-guidelines",label:"GPT-specific guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#GPTModelAdapter.buildSystemPromptSections",content:l}),i}enhanceUserMessage(e,r){return r?this.getBaseEnhancement(e,r):e}getBaseEnhancement(e,r){if(!r)return e;let n=e.toLowerCase(),o=n.includes("find")||n.includes("search")||n.includes("my notes"),i=n.includes("edit")||n.includes("modify")||n.includes("update")||n.includes("change")||n.includes("fix")||n.includes("add")||n.includes("typo");return o?`${e}
REMINDER: Use the <use_tool> XML format to call the localSearch tool.`:i?`${e}
\u{1F6A8} GPT REMINDER: Use replaceInFile for small edits (with SEARCH/REPLACE blocks in diff parameter). The diff parameter MUST contain triple backticks around the SEARCH/REPLACE blocks. Check the examples in your system prompt.`:e}needsSpecialHandling(){return!0}},rmt=class extends lJ{isThinkingModel(){return this.modelName.includes("claude-3-7-sonnet")||this.modelName.includes("claude-sonnet-4")||this.modelName.includes("claude-3.7-sonnet")||this.modelName.includes("claude-4-sonnet")}isClaudeSonnet4(){return this.modelName.includes("claude-sonnet-4")||this.modelName.includes("claude-4-sonnet")||this.modelName.includes("claude-sonnet-4-20250514")}buildSystemPromptSections(e,r,n,o){let i=super.buildSystemPromptSections(e,r,n,o);if(!this.isThinkingModel())return i;let a=[`IMPORTANT FOR CLAUDE THINKING MODELS:
- You are a thinking model with internal reasoning capability
- Your thinking process will be automatically wrapped in <think> tags - do not manually add thinking tags
- 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`];return this.isClaudeSonnet4()&&a.push(`\u{1F6A8} CRITICAL INSTRUCTIONS FOR CLAUDE SONNET 4 - AUTONOMOUS AGENT MODE \u{1F6A8}
\u26A0\uFE0F WARNING: You have a specific tendency to write complete responses immediately after tool calls. This BREAKS the autonomous agent pattern!
\u{1F504} CORRECT AUTONOMOUS AGENT ITERATION PATTERN:
1. User asks question
2. Brief sentence about what you'll do (1 sentence max)
3. Use tools to gather information: <use_tool>...</use_tool>
4. \u270B STOP after tool calls - Do not write anything else
5. Wait for tool results (system provides them)
6. Evaluate results and either: Use more tools OR provide final answer
\u2705 IDEAL RESPONSE FLOW:
- Brief action statement (1 sentence)
- Tool calls
- STOP (wait for results)
- Brief transition statement (1 sentence)
- More tool calls OR final answer
\u{1F3AF} CORRECT FIRST RESPONSE PATTERN (when tools needed):
I'll search your vault for piano practice information.
<use_tool>
<name>localSearch</name>
<query>piano practice</query>
<salientTerms>["piano", "practice"]</salientTerms>
</use_tool>
\u{1F310} MULTILINGUAL EXAMPLE (PRESERVE ORIGINAL LANGUAGE):
<use_tool>
<name>localSearch</name>
<query>\u30D4\u30A2\u30CE\u306E\u7DF4\u7FD2\u65B9\u6CD5</query>
<salientTerms>["\u30D4\u30A2\u30CE", "\u7DF4\u7FD2", "\u65B9\u6CD5"]</salientTerms>
</use_tool>
<use_tool>
<name>webSearch</name>
<query>piano techniques</query>
<chatHistory>[]</chatHistory>
</use_tool>
[RESPONSE ENDS HERE - NO MORE TEXT]
\u{1F3AF} CORRECT FOLLOW-UP RESPONSE PATTERN:
Let me gather more specific information about practice schedules.
<use_tool>
<name>localSearch</name>
<query>practice schedule</query>
<salientTerms>["practice", "schedule"]</salientTerms>
</use_tool>
[RESPONSE ENDS HERE - NO MORE TEXT]
\u274C WRONG PATTERN (DO NOT DO THIS):
<use_tool>...</use_tool>
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(`
`)}),i}needsSpecialHandling(){return this.isThinkingModel()}detectPrematureResponse(e){let r=e.indexOf("<use_tool>");if(r===-1)return{hasPremature:!1,type:null};let o=e.substring(0,r).trim().replace(/<think>[\s\S]*?<\/think>/g,"").trim();if(o.split(/[.!?]+/).filter(u=>u.trim().length>0).length>2||o.length>200)return{hasPremature:!0,type:"before"};let s=e.lastIndexOf("</use_tool>");return s!==-1&&e.substring(s+11).trim().replace(/<think>[\s\S]*?<\/think>/g,"").trim().length>100?{hasPremature:!0,type:"after"}:{hasPremature:!1,type:null}}sanitizeResponse(e,r){if(!this.isClaudeSonnet4()||r!==1)return e;let n=this.detectPrematureResponse(e);if(!n.hasPremature)return e;if(n.type==="after"){let o=e.lastIndexOf("</use_tool>");if(o!==-1){let i=e.substring(0,o+11),a=e.substring(o+11),s=/<think>[\s\S]*?<\/think>/g,u=a.match(s)||[];return i+(u.length>0?`
`+u.join(`
`):"")}}return e}shouldTruncateStreaming(e){if(!this.isClaudeSonnet4())return!1;let r=e.lastIndexOf("</use_tool>");return r===-1?!1:e.substring(r+11).trim().replace(/<think>[\s\S]*?<\/think>/g,"").trim().length>omt}},nmt=class extends lJ{buildSystemPromptSections(e,r,n,o){let i=super.buildSystemPromptSections(e,r,n,o),u=[`\u{1F6A8} CRITICAL INSTRUCTIONS FOR GEMINI - AUTONOMOUS AGENT MODE \u{1F6A8}
You MUST use tools to complete tasks. DO NOT ask the user questions about how to proceed.
${(n||[]).includes("localSearch")?`
When the user mentions "my notes" or "my vault", use the localSearch tool.
\u274C WRONG:
"Let's start by searching your notes. What kind of information should I look for?"
\u2705 CORRECT:
<use_tool>
<name>localSearch</name>
<query>piano</query>
<salientTerms>["piano"]</salientTerms>
</use_tool>`:""}`.trim()];return u.push(`GEMINI SPECIFIC RULES:
1. When user mentions "my notes" about X \u2192 use localSearch with query "X"
2. DO NOT ask clarifying questions about search terms
3. DO NOT wait for permission to use tools
4. Use tools based on the user's request
\u{1F6A8} CRITICAL: SEQUENTIAL vs PARALLEL TOOL CALLS \u{1F6A8}
When one tool's OUTPUT is needed as INPUT to another tool, you MUST make them in SEPARATE responses:
1. Call the FIRST tool
2. STOP and wait for the result
3. In the NEXT response, use the result from step 1 in the SECOND tool call
\u274C WRONG (DO NOT DO THIS):
User: "Recap my last week"
Your response:
<use_tool>
<name>getTimeRangeMs</name>
<timeExpression>last week</timeExpression>
</use_tool>
<use_tool>
<name>localSearch</name>
<timeRange>{"startTime":1234567890,"endTime":9876543210}</timeRange>
</use_tool>
This is WRONG because you're hallucinating the timeRange values! You don't know what getTimeRangeMs will return yet!
\u2705 CORRECT (DO THIS):
User: "Recap my last week"
Your FIRST response:
<use_tool>
<name>getTimeRangeMs</name>
<timeExpression>last week</timeExpression>
</use_tool>
[STOP HERE - WAIT FOR RESULT]
System provides: {"startTime":1753660800000,"endTime":1754265600000}
Your SECOND response:
<use_tool>
<name>localSearch</name>
<query>recap my last week</query>
<salientTerms>[]</salientTerms>
<timeRange>{"startTime":1753660800000,"endTime":1754265600000}</timeRange>
</use_tool>
RULE: NEVER make up or guess parameter values. If you need a tool's output, call that tool FIRST, then WAIT for the result.
PATTERN FOR MULTI-STEP REQUESTS:
User: "based on my project roadmap notes and create summary"
Your response:
<use_tool>
<name>localSearch</name>
<query>project roadmap</query>
<salientTerms>["project", "roadmap"]</salientTerms>
</use_tool>
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(`
`)}),i}enhanceUserMessage(e,r){return r?`${e}
REMINDER: Use the tools immediately. Do not ask questions. For "my notes", use localSearch.`:e}needsSpecialHandling(){return!0}},hU=class{static createAdapter(e){let r=(e.modelName||e.model||"").toLowerCase();if(B(`Creating model adapter for: ${r}`),r.includes("gpt")){let n=new tmt(r);return n.isGPT5Model()?B("Using GPTModelAdapter with GPT-5 specific enhancements"):B("Using GPTModelAdapter"),n}return r.includes("claude")?(B("Using ClaudeModelAdapter"),new rmt(r)):r.includes("gemini")||r.includes("google/gemini")?(B("Using GeminiModelAdapter"),new nmt(r)):r.includes("copilot-plus")?(B("Using BaseModelAdapter for Copilot Plus"),new lJ(r)):(B("Using BaseModelAdapter (default)"),new lJ(r))}}});function Yc(t){return typeof t!="string"?"":t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function I2r(t){return typeof t!="string"?"":t.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&")}function rX(t){let e=[];try{let r=/<use_tool>([\s\S]*?)(<\/use_tool>|$)/g,n;for(;(n=r.exec(t))!==null;){let o=n[1],i=o.match(/<name>([\s\S]*?)<\/name>/),a=n[2]==="</use_tool>";if(i){let s=i[1].trim();if(!s||s.length===0){Be("Skipping tool call with empty name");continue}let u={},l=o.replace(/<name>[\s\S]*?<\/name>/,""),c=/<([^>]+)>([\s\S]*?)<\/\1>/g,d;for(;(d=c.exec(l))!==null;){let f=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){return ne("Error parsing XML tool calls:",r),[]}return e}function imt(t,e){if(!t)return e==="chatHistory"||e==="salientTerms"?[]:"";if(!/<[^>]+>/.test(t)){if(t.startsWith("[")&&t.endsWith("]")||t.startsWith("{")&&t.endsWith("}"))try{return JSON.parse(t)}catch{return t}return t}let n=t.match(/<item>([\s\S]*?)<\/item>/g);if(n)return n.map(s=>{let u=s.replace(/<\/?item>/g,"").trim();return imt(u)});let o=/<([^>]+)>([\s\S]*?)<\/\1>/g,i=[],a;for(;(a=o.exec(t))!==null;){let s=a[1].trim(),u=a[2].trim();i.push([s,imt(u)])}return i.length>0?Object.fromEntries(i):t}function R2r(t){t=t.replace(/<use_tool>[\s\S]*?<\/use_tool>/g,"");let e=t.match(/<use_tool>([\s\S]*)/),n=(e?e[1]:t).match(/<name>([\s\S]*?)<\/name>/);return n&&n[1].trim()||null}function Zle(t){let e=t;return e=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,`
`).trim(),e}var Yle=v(()=>{_t()});var uA,kje=v(()=>{k1e();Or();Mie();Fot();_t();Nv();ot();Vq();Eft();Y1e();Due();yV();Dje();Fft();Rft();Zt();Zt();Pie();_2r();uG();Cue();C2r();emt();M2r();bV();Lue();F1();Xle();Yle();dx();k1();qs();uA=class t extends L1{constructor(){super(...arguments);this.lastCitationSources=null}getAvailableToolsForPlanning(){let r=bd.getInstance();return r.getAllTools().length===0&&tX(this.chainManager.app?.vault),r.getAllTools().map(o=>o.tool).filter(o=>o.name==="getCurrentTime"||o.name==="convertTimeBetweenTimezones"||o.name==="getTimeInfoByEpoch"||o.name==="getTimeRangeMs"||o.name==="getFileTree")}static generateToolDescriptions(r){return r.map(n=>{let o="",i=X1e(n.schema);return Object.keys(i).length>0&&(o=Object.entries(i).map(([a,s])=>`<${a}>${s}</${a}>`).join(`
`)),`<${n.name}>
<description>${n.description}</description>
<parameters>
${o}
</parameters>
</${n.name}>`}).join(`
`)}async planToolCalls(r,n){let o=this.getAvailableToolsForPlanning(),i=hU.createAdapter(n),a=t.generateToolDescriptions(o),s=bd.getInstance(),u=o.map(g=>s.getToolMetadata(g.name)).filter(g=>g!==void 0),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+=`
IMPORTANT: Respond ONLY with XML blocks. Do not include any natural language explanations, apologies, or commentary.
Your response must contain:
1. Tool calls (if needed): <use_tool>...</use_tool>
2. Salient terms (always): <salient_terms><term>keyword</term></salient_terms>
Format for salient terms:
<salient_terms>
<term>first keyword</term>
<term>second keyword</term>
</salient_terms>
Guidelines for salient terms:
- Extract meaningful nouns, topics, and specific concepts
- Exclude common words like "what", "how", "my", "the", "a", "an"
- Exclude time expressions (those are handled separately)
- If the message has no meaningful search terms, output empty <salient_terms></salient_terms>
- Use the EXACT words from the user's message (preserve language/spelling)
OUTPUT ONLY XML - NO OTHER TEXT.`;let d=[{role:Iz(n),content:c},{role:"user",content:r}];B("[CopilotPlus] Requesting tool planning from model...");let f=await rh(()=>n.invoke(d)),p=typeof f.content=="string"?f.content:String(f.content);B("[CopilotPlus] Model planning response:",p.substring(0,500));let m=rX(p),h=this.extractSalientTerms(p),y=[];for(let g of m){let b=o.find(_=>_.name===g.name);b&&y.push({tool:b,args:g.args})}return{toolCalls:y,salientTerms:h}}extractSalientTerms(r){let n=r.match(/<salient_terms>([\s\S]*?)<\/salient_terms>/);if(!n)return[];let i=n[1].matchAll(/<term>(.*?)<\/term>/g),a=[];for(let s of i){let u=s[1].trim();u&&a.push(u)}return a}async processAtCommands(r,n,o){let i=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")){let c=await Nm.instance.getCurrentChainManager().memoryManager.getMemory().loadMemoryVariables({}),d=lge(c);s.push({tool:oje,args:{query:a,chatHistory:d}})}return i.includes("@memory")&&(s.some(l=>l.tool.name==="updateMemory")||s.push({tool:tje,args:{statement:a}})),s}removeAtCommands(r){return r.split(" ").filter(n=>!S7.includes(n.toLowerCase())).join(" ").trim()}async processImageUrls(r){let n=[],o=await gV.processUrlBatch(r,n,this.chainManager.app.vault);return gV.showFailedImagesNotice(n),o}async processChatInputImages(r){let n=[],o=await gV.processChatImageBatch(r,n,this.chainManager.app.vault);return gV.showFailedImagesNotice(n),o}async extractImagesFromContextBlock(r,n){let i=new RegExp(`<${n.tagName}>([\\s\\S]*?)<\\/${n.tagName}>`).exec(r);if(!i)return[];let a=i[1],u=/<content>([\s\S]*?)<\/content>/.exec(a),l=u?I2r(u[1]):"";if(!l)return[];let d=new RegExp(`<${n.identifierTag}>(.*?)<\\/${n.identifierTag}>`).exec(a),f=d?d[1]:void 0;B(`[CopilotPlus] Extracting images from ${n.displayName}:`,f||`no ${n.identifierTag}`);let p=n.useForResolution?f:void 0;return this.extractEmbeddedImages(l,p)}async extractEmbeddedImages(r,n){let o=/!\[\[(.*?\.(png|jpg|jpeg|gif|webp|bmp|svg))\]\]/g,i=[],a=[...r.matchAll(o)];for(let u of a){let l=u[1];if(n){let c=app.metadataCache.getFirstLinkpathDest(l,n);c?i.push(c.path):(Be(`Could not resolve embedded image: ${l} from source: ${n}`),i.push(l))}else i.push(l)}let s=E2r(r);for(let u of s){if(!u)continue;if(u.match(/^https?:\/\//)){i.push(u);continue}let l=u.replace(/^\.\//,"").replace(/^\//,"");if(n){let c=app.metadataCache.getFirstLinkpathDest(l,n);c?i.push(c.path):i.push(l)}else i.push(l)}return i}async buildMessageContent(r,n){let o=[],i=[],a=ae(),s=[];if(a.passMarkdownImages){let d=n.contextEnvelope;if(!d)throw new Error("[CopilotPlus] Context envelope is required but not available. Cannot extract images.");let f=d.layers.find(p=>p.id==="L3_TURN");if(f){let p=[{tagName:"active_note",identifierTag:"path",displayName:"active note",useForResolution:!0},{tagName:"active_web_tab",identifierTag:"url",displayName:"active web tab",useForResolution:!1}];for(let m of p){let h=await this.extractImagesFromContextBlock(f.text,m);h.length>0&&s.push({urls:h,type:"embedded"})}}}for(let d of s){let f=await this.processImageUrls(d.urls);i.push(...f.successfulImages),o.push(...f.failureDescriptions)}let u=n.content;if(u&&u.length>0){let d=await this.processChatInputImages(u);i.push(...d.successfulImages),o.push(...d.failureDescriptions)}let l=r;o.length>0&&(l=`${r}
Note:
${o.join(`
`)}
`);let c=[{type:"text",text:l}];return i.length>0&&c.push(...i),c}hasCapability(r,n){let o=r.modelName||r.model||"";return this.chainManager.chatModelManager.findModelByName(o)?.capabilities?.includes(n)??!1}isMultimodalModel(r){return this.hasCapability(r,"vision")}appendComposerInstructionsIfNeeded(r,n){if(!n.message||!n.message.includes("@composer"))return r;let o=`<OUTPUT_FORMAT>
${qRt}
</OUTPUT_FORMAT>`;return`${r}
${o}`}async streamMultimodalResponse(r,n,o,i,a,s,u){let l=this.chainManager.memoryManager.getMemory(),c=this.chainManager.chatModelManager.getChatModel(),d=this.isMultimodalModel(c),f=[],p=n.contextEnvelope;if(!p)throw new Error("[CopilotPlus] Context envelope is required but not available. Cannot proceed with CopilotPlus chain.");B("[CopilotPlus] Using envelope-based context construction");let m=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}),await wk(l,f);let y=m.find(w=>w.role==="user");if(y){let w,O=o.length>0,T=M=>{let I="[User query]:";if(M.includes(I))return M;let j=M.trimEnd(),A=[];j.length>0&&A.push(j);let k=s.trim()||n.message?.trim()||n.originalMessage?.trim()||"";return k.length>0?A.push(`${I}
${k}`):A.push(I),A.join(`
`)};if(O){let M=this.formatAllToolOutputs(o),I=T(y.content);w=Qpt(M,I)}else w=T(y.content);if(r.includes("<OUTPUT_FORMAT>")&&!w.includes("<OUTPUT_FORMAT>")){let M=r.match(/<OUTPUT_FORMAT>[\s\S]*?<\/OUTPUT_FORMAT>/);M&&(w+=`
`+M[0])}let P=d?await this.buildMessageContent(w,n):w;f.push({role:"user",content:P})}B("Final request to AI",{messages:f.length});let g=c?.modelName;Sk({messages:f,modelName:g,contextEnvelope:n.contextEnvelope});let b=new $je(RD,Z1e),_=await rh(()=>this.chainManager.chatModelManager.getChatModel().stream(f,{signal:i.signal}));for await(let w of _){if(i.signal.aborted){B("CopilotPlus multimodal stream iteration aborted",{reason:i.signal.reason});break}for await(let O of b.processChunk(w))a.processChunk(O)}}async run(r,n,o,i,a){let{updateLoadingMessage:s}=a,u=this.chainManager.chatModelManager.getChatModel(),c=!this.hasCapability(u,"reasoning"),d=new T_(o,void 0,c),f=[];if(!await $S({isCopilotPlus:!0})){await this.handleError(new Error("Invalid license key"),d.processErrorChunk.bind(d));let _=d.close().content;return this.handleResponse(_,r,n,i,o,void 0)}try{B("==== Step 1: Planning tools ====");let _,w=r.contextEnvelope;if(!w)throw new Error("[CopilotPlus] Context envelope is required but not available. Cannot proceed with CopilotPlus chain.");let T=w.layers.find(k=>k.id==="L5_USER")?.text||r.originalMessage||r.message;try{let k=this.chainManager.chatModelManager.getChatModel(),V=await this.planToolCalls(T,k),q,J=V.toolCalls.find(ue=>ue.tool.name==="getTimeRangeMs");J&&(q=await RD.callTool(J.tool,J.args),B("[CopilotPlus] Executed getTimeRangeMs, result:",q));let K=V.toolCalls.filter(ue=>ue.tool.name==="getFileTree"&&t6()?(B("Skipping getFileTree in project mode"),!1):ue.tool.name==="getTimeRangeMs"&&q?(B("Skipping getTimeRangeMs - already executed during planning"),!1):!0);_=await this.processAtCommands(T,K,{salientTerms:V.salientTerms,timeRange:q})}catch(k){return this.handleResponse(ORt(k),r,n,i,o)}let P=this.removeAtCommands(r.message),{toolOutputs:M,sources:I}=await this.executeToolCalls(_,s);f=I;let j=M.filter(k=>k.output!=null),A=this.appendComposerInstructionsIfNeeded(P,r);B("Invoking LLM with envelope-based context construction"),await this.streamMultimodalResponse(A,r,j,n,d,P,s)}catch(_){s?.(Sv.DEFAULT),_.name==="AbortError"||n.signal.aborted?B("CopilotPlus stream aborted by user",{reason:n.signal.reason}):await this.handleError(_,d.processErrorChunk.bind(d))}if(n.signal.aborted&&n.signal.reason==="new-chat")return o(""),"";let m=d.close(),h=m.content,y={wasTruncated:m.wasTruncated,tokenUsage:m.tokenUsage??void 0},g=ae(),b=this.lastCitationSources&&this.lastCitationSources.length>0?this.lastCitationSources:(f||[]).map(_=>({title:_.title,path:_.path}));return h=$1e(h,b,g.enableInlineCitations),await this.handleResponse(h,r,n,i,o,f,void 0,y),h}async executeToolCalls(r,n){let o=[],i=[],a=r.some(s=>s.tool.name==="localSearch");for(let s of r){if(s.tool.name==="getFileTree"&&a){B("Skipping getFileTree since localSearch is already active");continue}B(`Step 2: Calling tool: ${s.tool.name}`),s.tool.name==="localSearch"?n?.(Sv.READING_FILES):s.tool.name==="webSearch"?n?.(Sv.SEARCHING_WEB):s.tool.name==="getFileTree"&&n?.(Sv.READING_FILE_TREE);let u=await RD.callTool(s.tool,s.args);if(s.tool.name==="localSearch"){let c={result:typeof u=="string"?u:JSON.stringify(u),success:u!=null},d=this.getTimeExpression(r),f=this.processLocalSearchResult(c,d);i.push(...f.sources),o.push({tool:s.tool.name,output:f.formattedForLLM})}else o.push({tool:s.tool.name,output:u})}return{toolOutputs:o,sources:Jq(i)}}getTimeExpression(r){let n=r.find(o=>o.tool.name==="getTimeRangeMs");return n?n.args.timeExpression:""}prepareLocalSearchResult(r,n){let o=r.filter(y=>y.includeInContext),i=o.reduce((y,g)=>y+(g.content?.length||0),0),a=o;if(i>_He){let y=_He/i;B("Truncating document contents to fit context length. Truncation ratio:",y),a=o.map(g=>({...g,content:g.content?.slice(0,Math.floor((g.content?.length||0)*y))||""}))}let s=a.map((y,g)=>({...y,__sourceId:g+1,content:L1e(y.content||"")})),u=Ypt(s),l=s.slice(0,Math.min(20,s.length)).map(y=>({title:y.title||y.path||"Untitled",path:y.path||y.title||""})),c=F1e(l);this.lastCitationSources=s.slice(0,Math.min(20,s.length)).map(y=>({title:y.title||y.path||"Untitled",path:y.path||void 0}));let d=ae(),f=
${f}`:m;return O2r(h,n)}processLocalSearchResult(r,n){let o=[],i,a;if(!r.success)return i=`<localSearch>
Search failed.
</localSearch>`,a=`Search failed: ${r.result}`,{formattedForLLM:i,formattedForDisplay:a,sources:o};try{let s=JSON.parse(r.result),u=s&&typeof s=="object"&&s.type==="local_search"&&Array.isArray(s.documents)?s.documents:null;if(!Array.isArray(u))return i=`<localSearch>
Invalid search results format.
</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}">
${u}
</localSearch>`:`<localSearch>
${u}
</localSearch>`,a=fx.format("localSearch",i)}return{formattedForLLM:i,formattedForDisplay:a,sources:o}}async getSystemPrompt(){return MD(this.chainManager.userMemoryManager)}formatAllToolOutputs(r){return r.length===0?"":`# Additional context:
`+r.map(o=>{let i=o.output;return typeof i!="string"&&(i=JSON.stringify(i)),`<${o.tool}>
${i}
</${o.tool}>`}).join(`
`)}}});var Qle,A2r=v(()=>{kje();Qle=class extends uA{}});function Eti(t){let{systemSections:e,rawHistory:r,adapterName:n,originalUserMessage:o,enhancedUserMessage:i}=t,a=[...e];if(r&&r.length>0){let u=Kot(r);if(u.length>0){let c=Kgr(u).map((d,f)=>`${f+1}. ${d.role.toUpperCase()}
${d.content}`);a.push({id:"chat-history",label:"Restored chat history from memory",source:"src/LLMProviders/chainRunner/utils/chatHistoryUtils.ts#processRawChatHistory",content:c.join(`
`)})}}a.push({id:"user-original-message",label:"Original user message",source:"Chat input",content:o});let s=i===o?" (unchanged)":"";return a.push({id:"user-enhanced-message",label:`User message after ${n}.enhanceUserMessage${s}`,source:`src/LLMProviders/chainRunner/utils/modelAdapter.ts#${n}.enhanceUserMessage`,content:i}),a}function Pti(t){return t.map(e=>`${`[Section: ${e.label} | Source: ${e.source}]`}
${e.content}`).join(`
`)}function N2r(t){let e=Eti(t),r=Pti(e),n=cJ(t.systemSections);return{sections:e,annotatedPrompt:r,systemPrompt:n}}var j2r=v(()=>{Xle();uG()});async function Mti(t){let{chainManager:e,adapter:r,basePrompt:n,toolDescriptions:o,toolNames:i,toolMetadata:a,userMessage:s}=t,u=r.buildSystemPromptSections(n,o,i,a),c=await e.memoryManager.getMemory().loadMemoryVariables({}),d=Array.isArray(c.history)?c.history:[],f=s.originalMessage||s.message,p=Fje(s.message),m=r.enhanceUserMessage(s.message,p);return N2r({systemSections:u,rawHistory:d,adapterName:r.constructor?.name||"ModelAdapter",originalUserMessage:f,enhancedUserMessage:m})}async function Iti(t){return MD(t.userMemoryManager)}async function D2r(t){let{chainManager:e,adapter:r,availableTools:n,toolDescriptions:o,userMessage:i}=t,a=bd.getInstance(),s=n.map(c=>c.name),u=n.map(c=>a.getToolMetadata(c.name)).filter(c=>c!==void 0),l=await Iti(e);return Mti({chainManager:e,adapter:r,basePrompt:l,toolDescriptions:o,toolNames:s,toolMetadata:u,userMessage:i})}var $2r=v(()=>{Vq();yV();Xle();j2r()});var ece,L2r=v(()=>{Or();_t();Nv();ot();Vq();Dje();dx();yV();Due();Zt();LTe();Qa();kje();uG();Xle();bV();Tie();Lue();emt();Mie();$2r();F1();Yle();ece=class t extends uA{constructor(){super(...arguments);this.llmFormattedMessages=[];this.lastDisplayedContent=""}getAvailableTools(){let r=ae(),n=bd.getInstance();n.getAllTools().length===0&&tX(this.chainManager.app?.vault);let o=new Set(r.autonomousAgentEnabledToolIds||[]);return n.getEnabledTools(o,!!this.chainManager.app?.vault)}static generateToolDescriptions(r){return r.map(o=>{let i="",a=X1e(o.schema);return Object.keys(a).length>0&&(i=Object.entries(a).map(([s,u])=>`<${s}>${u}</${s}>`).join(`
`)),`<${o.name}>
<description>${o.description}</description>
<parameters>
${i}
</parameters>
</${o.name}>`}).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=`
Fallback to regular Plus mode also failed: `+Sn(_);return await this.handleError(new Error(w+O),m.processErrorChunk.bind(m)),s=m.close().content,this.handleResponse(s,r,n,i,o,void 0,s)}}}return await this.finalizeAgentRun({...g,userMessage:r,abortController:n,addMessage:i,updateCurrentAiMessage:o,modelNameForLog:h,responseMetadata:u,fullAIResponse:s})}async prepareAgentConversation(r,n,o){let i=[],a=[],s=[],u=this.getAvailableTools(),l={availableTools:u,getTemporaryToolCallId:this.getTemporaryToolCallId.bind(this),processLocalSearchResult:this.processLocalSearchResult.bind(this),applyCiCOrderingToLocalSearchResult:this.applyCiCOrderingToLocalSearchResult.bind(this)},c=r.contextEnvelope,d=vR.convert(c,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),f=this.chainManager.memoryManager.getMemory(),p=d.find(I=>I.role==="system"),m=hU.createAdapter(n),h=t.generateToolDescriptions(u),y=bd.getInstance(),g=u.map(I=>y.getToolMetadata(I.name)).filter(I=>I!==void 0),_=m.buildSystemPromptSections("",h,u.map(I=>I.name),g).filter(I=>I.id!=="base-system-prompt"),w=cJ(_);if(p||w){let I=[p?.content||"",w||""].filter(Boolean).join(`
`);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(`=== Autonomous Agent Iteration ${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(`
`))}let Y=await jft(K,m,a);if(Y.success||(Y.displayResult=dG(Y.result,"Tool execution failed")),K.name==="localSearch"){if(Y.success){let se=s.processLocalSearchResult(Y);f.push(...se.sources),Y.result=s.applyCiCOrderingToLocalSearchResult(se.formattedForLLM,a||""),Y.displayResult=se.formattedForDisplay}}else K.name==="readNote"&&Y.success&&(Y.displayResult=fx.format("readNote",Y.result));if(j.push(Y),G&&!oe){let se=_.findIndex(ie=>ie.includes(G));se!==-1&&(_[se]=Jot(_[se],G,Y.displayResult??Y.result)),c([...d,..._].join(`
`))}$ft(K.name,Y)}_.length>0&&d.push(_.join(`
`));let k=M;if(p.push(k),j.length>0){let J=Got(j,!0);J&&p.push(J)}let V=jTe(M);n.push({role:"assistant",content:V});let q=Got(j,!1);n.push({role:"user",content:q}),B("Tool results added to conversation")}if(y>=h&&!g){Be(`Autonomous agent reached maximum iterations (${h}) without completing the task`);let _=`
I've reached the maximum number of iterations (${h}) for this task. I attempted to gather information using various tools but couldn't complete the analysis within the iteration limit. You may want to try a more specific question or break down your request into smaller parts.`;g=d.join(`
`)+_,n.push({role:"assistant",content:g})}return{fullAIResponse:g,responseMetadata:b,iterationHistory:d,collectedSources:f,llmMessages:p}}updateStreamingDisplay(r,n,o,i,a){let s=Zle(r),u=[...n];s.trim()&&u.push(s);let l=rX(r),c=new Set(a.availableTools.filter(h=>h.isBackground).map(h=>h.name));if(o.length>0&&c.size>0){let h=Array.from(c).map(y=>`temporary-tool-call-id-${y}-`);for(let y=o.length-1;y>=0;y-=1){let g=o[y];h.some(b=>g.includes(b))&&o.splice(y,1)}}let d=[];l.forEach(h=>{c.has(h.name)||d.push(h.name)});let f=R2r(r);if(f){let h=r.lastIndexOf(f);r.length-h>omt&&(c.has(f)||d.push(f))}Array.from(new Set(d)).forEach((h,y)=>{let g=a.getTemporaryToolCallId(h,y);if(o.findIndex(w=>w.includes(g))!==-1)return;let _=DTe(g,h,QH(h),E7(h),"",!0,"","");o.push(_)}),o.length>0&&u.push(o.join(`
`));let m=u.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(`
`)),n.length>0&&Sk({messages:[...n],modelName:c,contextEnvelope:a.contextEnvelope}),await Promise.resolve().then(()=>(Tie(),Wot));let h=this.llmFormattedMessages.join(`
`);return await this.handleResponse(p,a,s,u,l,m.length>0?m:void 0,h,d),this.lastDisplayedContent="",p}async streamResponse(r,n,o,i){let a=this.chainManager.chatModelManager.getChatModel(),u=!this.hasCapability(a,"reasoning"),l=new T_(o,i,u),c=2,d=0;for(;d<=c;)try{let p=r.map(y=>y.role==="user"?new Hs(y.content):new eo(y.content)),m=await rh(()=>this.chainManager.chatModelManager.getChatModel().stream(p,{signal:n.signal}));for await(let y of m){if(n.signal.aborted)break;l.processChunk(y)}let h=l.close();return{content:h.content,wasTruncated:h.wasTruncated,tokenUsage:h.tokenUsage}}catch(p){if(p.name==="AbortError"||n.signal.aborted){let h=l.close();return{content:h.content,wasTruncated:h.wasTruncated,tokenUsage:h.tokenUsage}}if((p?.message?.includes("overloaded")||p?.message?.includes("Overloaded")||p?.error?.type==="overloaded_error")&&d<c){d++,B(`Retrying autonomous agent request (attempt ${d}/${c+1}) due to overloaded error`),await new Promise(h=>setTimeout(h,1e3*d));continue}throw p}let f=l.close();return{content:f.content,wasTruncated:f.wasTruncated,tokenUsage:f.tokenUsage}}}});var F2r=v(()=>{Pie();Ygr();UUr();kje();A2r();L2r();bV();Yle();Lue()});var Rti,k2r,Ati,q2r,Nti,U2r,jti,B2r,qje=v(()=>{wv();Rti=`Progressively summarize the lines of conversation provided, adding onto the previous summary returning a new summary.
EXAMPLE
Current summary:
The human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good.
New lines of conversation:
Human: Why do you think artificial intelligence is a force for good?
AI: Because artificial intelligence will help humans reach their full potential.
New summary:
The human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good because it will help humans reach their full potential.
END OF EXAMPLE
Current summary:
{summary}
New lines of conversation:
{new_lines}
New summary:`,k2r=new lu({inputVariables:["summary","new_lines"],template:Rti}),Ati=`You are an assistant to a human, powered by a large language model trained by OpenAI.
You are designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, you are able to generate human-like text based on the input you receive, allowing you to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.
You are constantly learning and improving, and your capabilities are constantly evolving. You are able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. You have access to some personalized information provided by the human in the Context section below. Additionally, you are able to generate your own text based on the input you receive, allowing you to engage in discussions and provide explanations and descriptions on a wide range of topics.
Overall, you are a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether the human needs help with a specific question or just wants to have a conversation about a particular topic, you are here to assist.
Context:
{entities}
Current conversation:
{history}
Last line:
Human: {input}
You:`,q2r=new lu({inputVariables:["entities","history","input"],template:Ati}),Nti=`You are an AI assistant reading the transcript of a conversation between an AI and a human. Extract all of the proper nouns from the last line of conversation. As a guideline, a proper noun is generally capitalized. You should definitely extract all names and places.
The conversation history is provided just in case of a coreference (e.g. "What do you know about him" where "him" is defined in a previous line) -- ignore items mentioned there that are not in the last line.
Return the output as a single comma-separated list, or NONE if there is nothing of note to return (e.g. the user is just issuing a greeting or having a simple conversation).
EXAMPLE
Conversation history:
Person #1: my name is Jacob. how's it going today?
AI: "It's going great! How about you?"
Person #1: good! busy working on Langchain. lots to do.
AI: "That sounds like a lot of work! What kind of things are you doing to make Langchain better?"
Last line:
Person #1: i'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff.
Output: Jacob,Langchain
END OF EXAMPLE
EXAMPLE
Conversation history:
Person #1: how's it going today?
AI: "It's going great! How about you?"
Person #1: good! busy working on Langchain. lots to do.
AI: "That sounds like a lot of work! What kind of things are you doing to make Langchain better?"
Last line:
Person #1: i'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff. I'm working with Person #2.
Output: Langchain, Person #2
END OF EXAMPLE
Conversation history (for reference only):
{history}
Last line of conversation (for extraction):
Human: {input}
Output:`,U2r=new lu({inputVariables:["history","input"],template:Nti}),jti=`You are an AI assistant helping a human keep track of facts about relevant people, places, and concepts in their life. Update and add to the summary of the provided entity in the "Entity" section based on the last line of your conversation with the human. If you are writing the summary for the first time, return a single sentence.
The update should only include facts that are relayed in the last line of conversation about the provided entity, and should only contain facts about the provided entity.
If there is no new information about the provided entity or the information is not worth noting (not an important or relevant fact to remember long-term), output the exact string "UNCHANGED" below.
Full conversation history (for context):
{history}
Entity to summarize:
{entity}
Existing summary of {entity}:
{summary}
Last line of conversation:
Human: {input}
Updated summary (or the exact string "UNCHANGED" if there is no new information about {entity} above):`,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(`One input key expected, but got ${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(`input values have ${n.length} keys, you must specify an input key or pass only 1 key as input`)}return r},rce=(t,e)=>{let r=V2r(t,e);if(!r&&r!==""){let n=Object.keys(t);throw new Error(`output values have ${n.length} keys, you must specify an output key or pass only 1 key as output`)}return r}});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(`The following keys: ${ice(i)} are overlapping between memory and input keys of the chain variables. This can lead to unexpected behaviour. Please use input and memory keys that don'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(
`);return{...o,[this.documentVariableName]:a}}async _call(r,n){return await this.llmChain.call(this._prepInputs(r),n?.getChild("combine_documents"))}_chainType(){return"stuff_documents_chain"}static async deserialize(r){if(!r.llm_chain)throw new Error("Missing llm_chain");return new G2r({llmChain:await Rh.deserialize(r.llm_chain)})}serialize(){return{_type:this._chainType(),llm_chain:this.llmChain.serialize()}}},X2r=class Z2r extends Ny{constructor(r){super(r);x(this,"llmChain");x(this,"inputKey","input_documents");x(this,"documentVariableName","context");x(this,"returnIntermediateSteps",!1);x(this,"maxTokens",3e3);x(this,"maxIterations",10);x(this,"ensureMapStep",!1);x(this,"combineDocumentChain");this.llmChain=r.llmChain,this.combineDocumentChain=r.combineDocumentChain,this.documentVariableName=r.documentVariableName??this.documentVariableName,this.ensureMapStep=r.ensureMapStep??this.ensureMapStep,this.inputKey=r.inputKey??this.inputKey,this.maxTokens=r.maxTokens??this.maxTokens,this.maxIterations=r.maxIterations??this.maxIterations,this.returnIntermediateSteps=r.returnIntermediateSteps??!1}static lc_name(){return"MapReduceDocumentsChain"}get inputKeys(){return[this.inputKey,...this.combineDocumentChain.inputKeys]}get outputKeys(){return this.combineDocumentChain.outputKeys}async _call(r,n){if(!(this.inputKey in r))throw new Error(`Document key ${this.inputKey} not found.`);let{[this.inputKey]:o,...i}=r,a=o,s=[];for(let c=0;c<this.maxIterations;c+=1){let d=a.map(h=>({[this.documentVariableName]:h.pageContent,...i}));if(c!==0||!this.ensureMapStep){let h=await this.combineDocumentChain.llmChain.prompt.format(this.combineDocumentChain._prepInputs({[this.combineDocumentChain.inputKey]:a,...i}));if(await this.combineDocumentChain.llmChain._getNumTokens(h)<this.maxTokens)break}let p=await this.llmChain.apply(d,n?Array.from({length:d.length},(h,y)=>n.getChild(`map_${y+1}`)):void 0),{outputKey:m}=this.llmChain;this.returnIntermediateSteps&&(s=s.concat(p.map(h=>h[m]))),a=p.map(h=>({pageContent:h[m],metadata:{}}))}let u={[this.combineDocumentChain.inputKey]:a,...i},l=await this.combineDocumentChain.call(u,n?.getChild("combine_documents"));return this.returnIntermediateSteps?{...l,intermediateSteps:s}:l}_chainType(){return"map_reduce_documents_chain"}static async deserialize(r){if(!r.llm_chain)throw new Error("Missing llm_chain");if(!r.combine_document_chain)throw new Error("Missing combine_document_chain");return new Z2r({llmChain:await Rh.deserialize(r.llm_chain),combineDocumentChain:await Bje.deserialize(r.combine_document_chain)})}serialize(){return{_type:this._chainType(),llm_chain:this.llmChain.serialize(),combine_document_chain:this.combineDocumentChain.serialize()}}},Y2r=class Q2r extends Ny{constructor(r){super(r);x(this,"llmChain");x(this,"inputKey","input_documents");x(this,"outputKey","output_text");x(this,"documentVariableName","context");x(this,"initialResponseName","existing_answer");x(this,"refineLLMChain");x(this,"documentPrompt",this.defaultDocumentPrompt);this.llmChain=r.llmChain,this.refineLLMChain=r.refineLLMChain,this.documentVariableName=r.documentVariableName??this.documentVariableName,this.inputKey=r.inputKey??this.inputKey,this.outputKey=r.outputKey??this.outputKey,this.documentPrompt=r.documentPrompt??this.documentPrompt,this.initialResponseName=r.initialResponseName??this.initialResponseName}static lc_name(){return"RefineDocumentsChain"}get defaultDocumentPrompt(){return new lu({inputVariables:["page_content"],template:"{page_content}"})}get inputKeys(){return[...new Set([this.inputKey,...this.llmChain.inputKeys,...this.refineLLMChain.inputKeys])].filter(r=>r!==this.documentVariableName&&r!==this.initialResponseName)}get outputKeys(){return[this.outputKey]}async _constructInitialInputs(r,n){let o={page_content:r.pageContent,...r.metadata},i={};return this.documentPrompt.inputVariables.forEach(u=>{i[u]=o[u]}),{...{[this.documentVariableName]:await this.documentPrompt.format({...i})},...n}}async _constructRefineInputs(r,n){let o={page_content:r.pageContent,...r.metadata},i={};this.documentPrompt.inputVa
{context}
Question: {question}
Helpful Answer:`,inputVariables:["context","question"]}),zti=`Use the following pieces of context to answer the users question.
If you don't know the answer, just say that you don't know, don't try to make up an answer.
----------------
{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(`Question key ${this.inputKey} not found.`);let o=r[this.inputKey],i=await this.vectorstore.similaritySearch(o,this.k,r.filter,n?.getChild("vectorstore")),a={question:o,input_documents:i},s=await this.combineDocumentsChain.call(a,n?.getChild("combine_documents"));return this.returnSourceDocuments?{...s,sourceDocuments:i}:s}_chainType(){return"vector_db_qa"}static async deserialize(r,n){if(!("vectorstore"in n))throw new Error("Need to pass in a vectorstore to deserialize VectorDBQAChain");let{vectorstore:o}=n;if(!r.combine_documents_chain)throw new Error("VectorDBQAChain must have combine_documents_chain in serialized data");return new 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=`You are given the below API Documentation:
{api_docs}
Using this documentation, generate the full API url to call for answering the user question.
You should build the API url in order to get a response that is as short as possible, while still getting the necessary information to answer the question. Pay attention to deliberately exclude any unnecessary pieces of data in the API call.
Question:{question}
API url:`,_Vr=new lu({inputVariables:["api_docs","question"],template:bVr}),Wti=`${bVr} {api_url}
Here is the response from the API:
{api_response}
Summarize this response to answer the original question.
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(`Missing output keys: ${e.join(", ")} from chain ${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()} expects multiple inputs, cannot use '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(
`);await this.vectorStoreRetriever.addDocuments([new Rm({pageContent:o,metadata:n})])}}});var $Vr,LVr=v(()=>{L$();$Vr=class extends Kh{}});var FVr,kVr=v(()=>{LVr();FVr=class extends $Vr{constructor(){super();x(this,"lc_namespace",["langchain","stores","entity","in_memory"]);x(this,"store");this.store=Object.create(null)}async get(e,r){return e in this.store?this.store[e]:r}async set(e,r){this.store[e]=r}async delete(e){delete this.store[e]}async exists(e){return e in this.store}async clear(){this.store=Object.create(null)}}});var qVr,UVr=v(()=>{pJ();qje();gU();kVr();Qa();nce();qVr=class extends Rb{constructor(e){super({chatHistory:e.chatHistory,returnMessages:e.returnMessages??!1,inputKey:e.inputKey,outputKey:e.outputKey});x(this,"entityExtractionChain");x(this,"entitySummarizationChain");x(this,"entityStore");x(this,"entityCache",[]);x(this,"k",3);x(this,"chatHistoryKey","history");x(this,"llm");x(this,"entitiesKey","entities");x(this,"humanPrefix");x(this,"aiPrefix");this.llm=e.llm,this.humanPrefix=e.humanPrefix,this.aiPrefix=e.aiPrefix,this.chatHistoryKey=e.chatHistoryKey??this.chatHistoryKey,this.entitiesKey=e.entitiesKey??this.entitiesKey,this.entityExtractionChain=new Rh({llm:this.llm,prompt:e.entityExtractionPrompt??U2r}),this.entitySummarizationChain=new Rh({llm:this.llm,prompt:e.entitySummarizationPrompt??B2r}),this.entityStore=e.entityStore??new FVr,this.entityCache=e.entityCache??this.entityCache,this.k=e.k??this.k}get memoryKeys(){return[this.chatHistoryKey]}get memoryVariables(){return[this.entitiesKey,this.chatHistoryKey]}async loadMemoryVariables(e){let r=this.inputKey??Uje(e,this.memoryVariables),n=await this.chatHistory.getMessages(),o=ol(n.slice(-this.k*2),this.humanPrefix,this.aiPrefix),i=await this.entityExtractionChain.predict({history:o,input:e[r]}),a=i.trim()==="NONE"?[]:i.split(",").map(l=>l.trim()),s={};for(let l of a)s[l]=await this.entityStore.get(l,"No current information known.");this.entityCache=[...a];let u=this.returnMessages?n.slice(-this.k*2):o;return{[this.chatHistoryKey]:u,[this.entitiesKey]:s}}async saveContext(e,r){await super.saveContext(e,r);let n=this.inputKey??Uje(e,this.memoryVariables),o=await this.chatHistory.getMessages(),i=ol(o.slice(-this.k*2),this.humanPrefix,this.aiPrefix),a=e[n];for(let s of this.entityCache){let u=await this.entityStore.get(s,"No current information known."),l=await this.entitySummarizationChain.predict({summary:u,entity:s,history:i,input:a});l.trim()!=="UNCHANGED"&&await this.entityStore.set(s,l.trim())}}async clear(){await super.clear(),await this.entityStore.clear()}}});var BVr,zVr=v(()=>{gU();BVr=class extends Rb{constructor(e){super({chatHistory:e?.chatHistory,returnMessages:e?.returnMessages??!1,inputKey:e?.inputKey,outputKey:e?.outputKey});x(this,"humanPrefix","Human");x(this,"aiPrefix","AI");x(this,"memoryKey","history");x(this,"memories",[]);this.memories=e?.memories??this.memories,this.humanPrefix=e?.humanPrefix??this.humanPrefix,this.aiPrefix=e?.aiPrefix??this.aiPrefix,this.memoryKey=e?.memoryKey??this.memoryKey,this.checkRepeatedMemoryVariable(),this.checkInputKey()}checkRepeatedMemoryVariable(){let e=[];for(let r of this.memories){let n=e.filter(o=>r.memoryKeys.includes(o));if(n.length>0)throw new Error(`The same variables ${[...n]} are found in multiple memory objects, which is not allowed by CombinedMemory.`);e.push(...r.memoryKeys)}}checkInputKey(){for(let e of this.memories)e.chatHistory!==void 0&&e.inputKey===void 0&&console.warn(`When using CombinedMemory, input keys should be set so the input is known. Was not set on ${e}.`)}async loadMemoryVariables(e){let r={};for(let n of this.memories){let o=await n.loadMemoryVariables(e);r={...r,...o}}return r}async saveContext(e,r){for(let n of this.memories)await n.saveContext(e,r)}async clear(){for(let e of this.memories)typeof e.clear=="function"&&await e.clear()}get memoryKeys(){let e=[];for(let r of this.memories)e.push(...r.memoryKeys);return e}}});var VVr,HVr=v(()=>{gU();Qa();VVr=class extends Rb{constructor(e){super(e);x(this,"humanPrefix","Human");x(this,"aiPrefix","AI");x(this,"memor
Answer the question with as detailed as possible based only on the following context:
{context}
Question: {question}
`;this.qaPrompt=ld.fromMessages([Gw.fromTemplate(e)])}escapeTemplateString(e){return e.replace(/\{/g,"{{").replace(/\}/g,"}}")}getChatPrompt(){return this.chatPrompt}async getQAPrompt({question:e,context:r,systemMessage:n}){return await this.qaPrompt.format({question:e,context:r,system_message:n})}}});var KVr,cce,GVr=v(()=>{qs();Bc();Or();F2r();_t();ot();Vq();Zt();Xw();wv();KVr=require("obsidian");v7();JVr();WVr();eje();cce=class{constructor(e){this.retrievedDocuments=[];this.pendingModelError=null;this.app=e,this.memoryManager=uce.getInstance(),this.chatModelManager=l0.getInstance(),this.promptManager=lce.getInstance(),this.userMemoryManager=new Hq(e),this.initialize(),al(async()=>{await this.createChainWithNewModel()})}getRetrievedDocuments(){return this.retrievedDocuments}async initialize(){await this.createChainWithNewModel()}getChain(){return this.chain}getRetrievalChain(){return this.retrievalChain}validateChainType(e){if(e==null)throw new Error("No chain type set")}validateChatModel(){if(this.pendingModelError)throw this.pendingModelError;if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){let e="Chat model is not initialized properly, check your API key in Copilot setting and make sure you have API access.";throw new kW(e)}}validateChainInitialization(){(!this.chain||!TRt(this.chain))&&(B("Reinitializing chat chain after detecting missing or unsupported instance."),this.createChainWithNewModel({},!1))}storeRetrieverDocuments(e){this.retrievedDocuments=e}async createChainWithNewModel(e={},r=!0){let n,o=gN(),i=Uu();if(!(o==="project"&&!i))try{if(n=o==="project"?i?.projectModelKey:i_(),!n)throw new kW("No model key found. Please select a model in settings.");if(r){let a=_O(n,ae().activeModels);if(a||(console.error("Resetting default model. No model configuration found for: ",n),a=hO[0],n=a.name+"|"+a.provider),o==="project"&&!a.projectEnabled){let u=ae().activeModels.find(l=>l.enabled&&l.projectEnabled);if(u)a=u,n=u.name+"|"+u.provider,new KVr.Notice(`Model ${a.name} is not available in project mode. Switching to ${u.name}.`);else throw new Error("No project-enabled models available. Please enable a model for project mode in settings.")}let s={...a,...i?.modelConfigs};await this.chatModelManager.setChatModel(s),this.pendingModelError=null}this.setChain(o,e),B(`Setting model to ${n}`)}catch(a){this.pendingModelError=a instanceof Error?a:new Error(String(a)),ne(`createChainWithNewModel failed: ${a}`),B(`modelKey: ${n||i_()}`)}}async setChain(e,r={}){if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){console.error("setChain failed: No chat model set.");return}this.validateChainType(e);let n=this.chatModelManager.getChatModel(),o=this.memoryManager.getMemory(),i=this.promptManager.getChatPrompt();switch(e){case"llm_chain":{this.chain=Ree.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),Lz("llm_chain");break}case"vault_qa":{await this.initializeQAChain(r);let a=ae(),s=a.enableSemanticSearchV3?new(await Promise.resolve().then(()=>(j1e(),hft))).HybridRetriever({minSimilarityScore:.01,maxK:a.maxSourceChunks,salientTerms:[]}):new(await Promise.resolve().then(()=>(w7(),N1e))).TieredLexicalRetriever(app,{minSimilarityScore:.01,maxK:a.maxSourceChunks,salientTerms:[],timeRange:void 0,textWeight:void 0,returnAll:!1,useRerankerThreshold:void 0});this.retrievalChain=Ree.createConversationalRetrievalChain({llm:n,retriever:s,systemMessage:PD()},this.storeRetrieverDocuments.bind(this),ae().debug),Lz("vault_qa"),ae().debug&&(console.log("New Vault QA chain with hybrid retriever created for entire vault"),console.log("Set chain:","vault_qa"));break}case"copilot_plus":{await this.initializeQAChain(r),this.chain=Ree.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),Lz("copilot_plus");break}case"project":{await this.initializeQAChain(r),this.chain=Ree.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),Lz("project");break}default:this.validateChainType(e);break}}
`,e.message),this.validateChatModel(),this.validateChainInitialization();let s=this.chatModelManager.getChatModel();if(a||Mee(s)){let l=ld.fromMessages([new pO("history"),Qb.fromTemplate("{input}")]);Mee(s)&&(l=ld.fromMessages([[Ws,PD()||""],l])),this.createChainWithNewModel({prompt:l},!1)}return await this.getChainRunner().run(e,r,n,o,i)}async updateMemoryWithLoadedMessages(e){await this.memoryManager.clearChatMemory();for(let r=0;r<e.length;r+=2){let n=e[r],o=e[r+1];n&&o&&n.sender===Ws&&await this.memoryManager.getMemory().saveContext({input:n.message},{output:o.message})}}}});var Gje,XVr=v(()=>{qs();_t();ot();Zt();xie();Gje=class t{constructor(e){this.app=e}static getInstance(e){return t.instance||(t.instance=new t(e)),t.instance}clearAllLoadStates(){vAt({success:[],failed:[],processingFiles:[],total:[]})}async executeWithProcessTracking(e,r,n){this.setFileOrUrlStartProcess(e);try{let o=await n();return this.setFileOrUrlProcessSuccessful(e),o}catch(o){let i=$1(o)?"Rate limit exceeded. (Rate limit: 50 files or 100MB per 3 hours, whichever is reached first)":Sn(o);throw this.setFileOrUrlProcessFailed(e,r,i),o}}setFileOrUrlStartProcess(e){ui.set(qee,r=>{let n={...r};return n.failed.find(o=>o.path===e)&&(n.failed=n.failed.filter(o=>o.path!==e)),n.success.includes(e)&&(n.success=n.success.filter(o=>o!==e)),n.processingFiles.includes(e)||(n.processingFiles=[...n.processingFiles,e]),n.total.includes(e)||(n.total=[...n.total,e]),n})}setFileOrUrlProcessSuccessful(e){CO("processingFiles",r=>r.filter(n=>n!==e)),CO("success",r=>r.includes(e)?r:[...r,e])}setFileOrUrlProcessFailed(e,r,n){CO("processingFiles",o=>o.filter(i=>i!==e)),CO("failed",o=>{if(!o.find(a=>a.path===e)){let a={path:e,type:r,error:n,timestamp:Date.now()};return[...o,a]}return o})}preComputeAllItems(e,r){B(`[preComputeAllItems] Starting pre-computation for project: ${e.name}`);let n=[];n.push(...r.map(a=>a.path));let o=e.contextSource?.webUrls?.trim()||"";if(o){let a=o.split(`
`).filter(s=>s.trim());n.push(...a)}let i=e.contextSource?.youtubeUrls?.trim()||"";if(i){let a=i.split(`
`).filter(s=>s.trim());n.push(...a)}if(n.length>0){let a=[...new Set([...n])];CO("total",s=>a),B(`[preComputeAllItems] Project ${e.name}: Added ${n.length} items to tracking (${a.length} total unique items)`)}}markAllCachedItemsAsSuccess(e,r,n){B(`[markAllCachedItemsAsSuccess] Starting for project: ${e.name||"default"}`);let o=e.contextSource?.webUrls?.trim()||"";if(o){let s=o.split(`
`).filter(u=>u.trim()).filter(u=>r.webContexts[u]);s.forEach(u=>{this.markCachedItemAsSuccess(u)}),s.length>0&&B(`[markAllCachedItemsAsSuccess] Project ${e.name}: Marked ${s.length} cached Web URLs as successful`)}let i=e.contextSource?.youtubeUrls?.trim()||"";if(i){let s=i.split(`
`).filter(u=>u.trim()).filter(u=>r.youtubeContexts[u]);s.forEach(u=>{this.markCachedItemAsSuccess(u)}),s.length>0&&B(`[markAllCachedItemsAsSuccess] Project ${e.name}: Marked ${s.length} cached YouTube URLs as successful`)}if(r.fileContexts){let a=new Set(n.filter(u=>u.extension==="md").map(u=>u.path)),s=Object.keys(r.fileContexts).filter(u=>a.has(u));s.forEach(u=>{this.markCachedItemAsSuccess(u)}),s.length>0&&B(`[markAllCachedItemsAsSuccess] Project ${e.name}: Marked ${s.length} cached files that match current project patterns as successful.`)}}markCachedItemAsSuccess(e){CO("total",r=>r.includes(e)?r:[...r,e]),CO("success",r=>r.includes(e)?r:[...r,e])}makeItemFailed(e,r,n){CO("total",o=>o.includes(e)?o:[...o,e]),CO("failed",o=>{if(!o.find(a=>a.path===e)){let a={path:e,type:r,error:n,timestamp:Date.now()};return[...o,a]}return o})}}});var mJ,Nm,k1=v(()=>{qs();iG();Bc();Or();_t();kot();vb();ot();NTe();Zt();xie();lN();mJ=require("obsidian");mR();GVr();XVr();Nm=class t{constructor(e,r){this.projectUsageTimestampsManager=new $W;this.app=e,this.plugin=r,this.currentProjectId=null,this.chainMangerInstance=new cce(e),this.projectContextCache=Yv.getInstance(),this.fileParserManager=new vk(pc.getInstance(),this.app.vault,!0,null),this.loadTracker=Gje.getInstance(this.app),hAt(async()=>{await this.getCurrentChainManager().createChainWithNewModel()}),gAt(async()=>{if(t6())return;let n=ae(),o=n.enableSemanticSearchV3&&n.indexVaultToVectorStore==="ON MODE SWITCH"&&(gN()==="vault_qa"||gN()==="copilot_plus");await this.getCurrentChainManager().createChainWithNewModel({refreshIndex:o})}),e6(async n=>{await this.switchProject(n)}),this.setupProjectListChangeMonitor()}setupProjectListChangeMonitor(){al(async(e,r)=>{if(!e||!r)return;let n=e.projectList||[],o=r.projectList||[];for(let i of o){let a=n.find(s=>s.id===i.id);a&&this.hasMeaningfulProjectConfigChange(a,i)&&(await this.compareAndUpdateCache(a,i),this.currentProjectId===i.id&&await Promise.all([this.loadProjectContext(i,!0),this.getCurrentChainManager().createChainWithNewModel()]))}})}hasMeaningfulProjectConfigChange(e,r){let n={...e,UsageTimestamps:0},o={...r,UsageTimestamps:0};return JSON.stringify(n)!==JSON.stringify(o)}static getInstance(e,r){return t.instance||(t.instance=new t(e,r)),t.instance}getCurrentChainManager(){return this.chainMangerInstance}getCurrentProjectId(){return this.currentProjectId}touchProjectUsageTimestamps(e){this.projectUsageTimestampsManager.touch(e.id);let r=ae().projectList||[],n=r.find(i=>i.id===e.id);if(!n)return;let o=this.projectUsageTimestampsManager.shouldPersist(e.id,n.UsageTimestamps);o!==null&&(Ue("projectList",r.map(i=>i.id===e.id?{...i,UsageTimestamps:o}:i)),this.projectUsageTimestampsManager.markPersisted(e.id,o))}getProjectUsageTimestampsManager(){return this.projectUsageTimestampsManager}async switchProject(e){try{if(this.loadTracker.clearAllLoadStates(),SO(!0),B("Project loading started..."),!e){await this.saveCurrentProjectMessage(),this.currentProjectId=null,await this.loadNextProjectMessage(),this.refreshChatView();return}let r=e.id;if(this.currentProjectId===r)return;await this.saveCurrentProjectMessage(),this.currentProjectId=r,await this.loadNextProjectMessage(),await this.getCurrentChainManager().createChainWithNewModel(),this.fileParserManager=new vk(pc.getInstance(),this.app.vault,!0,e),await this.loadProjectContext(e),this.refreshChatView(),this.touchProjectUsageTimestamps(e),B(`Switched to project: ${e.name}`)}catch(r){throw ne(`Failed to switch project: ${r}`),r}finally{SO(!1)}}async saveCurrentProjectMessage(){await this.plugin.autosaveCurrentChat()}async loadNextProjectMessage(){await this.plugin.chatUIState.handleProjectSwitch()}async loadProjectContext(e,r=!1){r&&(this.loadTracker.clearAllLoadStates(),SO(!0));try{if(!e.contextSource)return Be(`[loadProjectContext] Project ${e.name}: No contextSource. Aborting.`),null;B(`[loadProjectContext] Starting for project: ${e.name}`);let n=await this.projectContextCache.getOrInitializeCache(e),o=this.getProjectAllFiles(e);this.loadTracker.preComputeAllItems(e,o),this.loadTracker.m
`).filter(m=>m.trim()),p=l.split(`
`).filter(m=>m.trim());await this.projectContextCache.removeWebUrls(r,f.filter(m=>!p.includes(m)))}let c=e.contextSource?.youtubeUrls||"",d=r.contextSource?.youtubeUrls||"";if(c!==d){let f=c.split(`
`).filter(m=>m.trim()),p=d.split(`
`).filter(m=>m.trim());await this.projectContextCache.removeYoutubeUrls(r,f.filter(m=>!p.includes(m)))}}catch(n){ne(`Error comparing project configurations: ${n}`)}}refreshChatView(){let e=this.app.workspace.getLeavesOfType(ac)[0]?.view;e&&e.updateView()}async getProjectContext(e){let r=ae().projectList.find(o=>o.id===e);if(!r)return Be(`[getProjectContext] Project not found for ID: ${e}`),null;B(`[getProjectContext] Getting context for project: ${r.name} (ID: ${e})`);let n=this.projectContextCache.getSync(r);if(!n||n.markdownNeedsReload){n?B(`[getProjectContext] Project ${r.name}: Markdown needs reload. Triggering full load.`):B(`[getProjectContext] Project ${r.name}: Memory cache miss. Triggering full load.`);let o=await this.loadProjectContext(r,!0);if(!o)return ne(`[getProjectContext] Project ${r.name}: loadProjectContext returned null.`),null;n=o}else B(`[getProjectContext] Project ${r.name}: Memory cache hit and markdown OK. Using existing context.`);return this.formatProjectContextWithFiles(n,r)}async formatProjectContextWithFiles(e,r){let n=[];if(e.markdownContext&&n.push(`## Markdown Files
${e.markdownContext}`),Object.keys(e.webContexts).length>0&&n.push(`## Web Content
${Object.values(e.webContexts).join(`
`)}`),Object.keys(e.youtubeContexts).length>0&&n.push(`## YouTube Content
${Object.values(e.youtubeContexts).join(`
`)}`),Object.keys(e.fileContexts).length>0){let o=Object.entries(e.fileContexts).filter(([i])=>i.split(".").pop()?.toLowerCase()!=="md");if(o.length>0){let i=o.map(async([s,u])=>{let l=s.split("/"),c=l[l.length-1],d=c.split(".").pop()||"",f=await this.projectContextCache.getOrReuseFileContext(r,s)||"[Content not available]";return`[[${c}]]
path: ${s}
type: ${d}
modified: ${new Date(u.timestamp).toISOString()}
${f}`}),a=await Promise.all(i);a.length>0&&n.push(`## Other Files
${a.join(`
`)}`)}}return`
# Project Context
The following information is the relevant context for this project. Use this information to inform your responses when appropriate:
<ProjectContext>
${n.join(`
`)}
</ProjectContext>
`}formatProjectContext(e){let r=[];if(e.markdownContext&&r.push(`## Markdown Files
${e.markdownContext}`),Object.keys(e.webContexts).length>0&&r.push(`## Web Content
${Object.values(e.webContexts).join(`
`)}`),Object.keys(e.youtubeContexts).length>0&&r.push(`## YouTube Content
${Object.values(e.youtubeContexts).join(`
`)}`),Object.keys(e.fileContexts).length>0){let n="";for(let[o,i]of Object.entries(e.fileContexts)){let a=o.split("/"),s=a[a.length-1],u=s.split(".").pop()||"";n+=`[[${s}]]
path: ${o}
type: ${u}
modified: ${new Date(i.timestamp).toISOString()}
`}n&&r.push(`## Other Files
${n}`)}return`
# Project Context
The following information is the relevant context for this project. Use this information to inform your responses when appropriate:
<ProjectContext>
${r.join(`
`)}
</ProjectContext>
`}async processMarkdownFiles(e,r,n){if(B(`[processMarkdownFiles] Starting for project: ${e.name}`),r.markdownNeedsReload||!r.markdownContext||!r.markdownContext.trim()){B(`[processMarkdownFiles] Project ${e.name}: Processing markdown content.`);let o=await this.processMarkdownFileContext(n);this.projectContextCache.updateProjectMarkdownFilesFromPatterns(e,r,n),r.markdownContext=o,r.markdownNeedsReload=!1,B(`[processMarkdownFiles] Project ${e.name}: Markdown content updated.`)}else B(`[processMarkdownFiles] Project ${e.name}: Markdown content already up-to-date.`);return B(`[processMarkdownFiles] Completed for project: ${e.name}. Total fileContexts: ${Object.keys(r.fileContexts||{}).length}`),r}async processMarkdownFileContext(e){let r=e.filter(o=>o.extension==="md");B(`Found ${r.length} markdown files to process for project context`);let n=await Promise.all(r.map(async o=>{let i="",a="";try{let[s,u]=await this.loadTracker.executeWithProcessTracking(o.path,"md",async()=>Promise.all([this.app.vault.adapter.stat(o.path),this.app.vault.read(o)]));a=`[[${o.basename}]]
path: ${o.path}
type: ${o.extension}
created: ${s?new Date(s.ctime).toISOString():"unknown"}
modified: ${s?new Date(s.mtime).toISOString():"unknown"}`,i=u,B(`Completed processing markdown file: ${o.path}`)}catch(s){ne(`Error processing file ${o.path}: ${s}`),i=`[Error: ${Sn(s)}]`}return`${a}
${i}`}));return B("All markdown files processed for project context"),n.join(`
`)}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?`
YouTube transcript from ${e}:
${r.response.transcript}`:""}catch(r){return ne(`Failed to process YouTube URL ${e}: ${r}`),new mJ.Notice(`Failed to process YouTube URL ${e}: ${Sn(r)}`),""}}async processNonMarkdownFiles(e,r){let n=r.filter(i=>i.extension!=="md");if(B(`[loadProjectContext] Project ${e.name}: Checking for non-markdown processing: ${n.length} files .`),n.length<=0)return;this.fileParserManager=new vk(pc.getInstance(),this.app.vault,!0,e);let o=0;for(let i of n){let a=i.path;if(this.fileParserManager.supportsExtension(i.extension))try{await this.loadTracker.executeWithProcessTracking(a,"nonMd",async()=>{await this.projectContextCache.getOrReuseFileContext(e,a)||(B(`[loadProjectContext] Project ${e.name}: Parsing/caching new/updated file: ${a}`),await this.fileParserManager.parseFile(i,this.app.vault)),o++})}catch(s){if(ne(`[loadProjectContext] Project ${e.name}: Error parsing file ${a}:`,s),$1(s))throw s}}o>0&&B(`[loadProjectContext] Project ${e.name}: Processed and cached ${o} non-markdown files.`)}async retryFailedItem(e){try{if(!this.currentProjectId){Be("[retryFailedItem] No current project, aborting retry");return}let r=ae().projectList.find(n=>n.id===this.currentProjectId);if(!r){ne(`[retryFailedItem] Current project not found: ${this.currentProjectId}`);return}switch(B(`[retryFailedItem] Starting retry for ${e.type} item: ${e.path}`),e.type){case"web":await this.retryWebUrl(r,e.path);break;case"youtube":await this.retryYoutubeUrl(r,e.path);break;case"md":await this.retryMarkdownFile(r,e.path);break;case"nonMd":await this.retryNonMarkdownFile(r,e.path);break;default:Be(`[retryFailedItem] Unknown item type: ${e.type}`);return}B(`[retryFailedItem] Successfully retried ${e.type} item: ${e.path}`),new mJ.Notice(`Retry successful: ${e.path}`)}catch(r){ne(`[retryFailedItem] Failed to retry ${e.type} item ${e.path}:`,r),new mJ.Notice(`Retry failed: ${Sn(r)}`)}}async retryWebUrl(e,r){let n=await this.processWebUrlContext(r);if(!n){Be(`[retryWebUrl] Project ${e.name}: Fetched empty content for Web URL: ${r}`);return}B(`[retryWebUrl] Project ${e.name}: Successfully fetched content for URL: ${r.substring(0,50)}...`),await this.projectContextCache.updateWebUrl(e,r,n)}async retryYoutubeUrl(e,r){let n=await this.processYoutubeUrlContext(r);if(!n){Be(`[retryYoutubeUrl] Project ${e.name}: Fetched empty transcript for YouTube URL: ${r}`);return}B(`[retryYoutubeUrl] Project ${e.name}: Successfully fetched transcript for YouTube URL: ${r.substring(0,50)}...`),await this.projectContextCache.updateYoutubeUrl(e,r,n)}async retryMarkdownFile(e,r){let n=this.app.vault.getAbstractFileByPath(r);if(!(n instanceof mJ.TFile)||n.extension!=="md")throw new Error(`File not found or not a markdown file: ${r}`);try{await this.loadTracker.executeWithProcessTracking(n.path,"md",async()=>{}),B(`[retryMarkdownFile] Successfully reprocessed markdown file: ${r}`),await this.projectContextCache.invalidateMarkdownContext(e)}catch(o){throw ne(`[retryMarkdownFile] Error processing file ${r}: ${o}`),o}}async retryNonMarkdownFile(e,r){let n=this.app.vault.getAbstractFileByPath(r);if(!(n instanceof mJ.TFile)||n.extension==="md")throw new Error(`File not found or is a markdown file: ${r}`);if(!this.fileParserManager.supportsExtension(n.extension))throw new Error(`Unsupported file extension: ${n.extension}`);try{await this.loadTracker.executeWithProcessTracking(r,"nonMd",async()=>this.fileParserManager.parseFile(n,this.app.vault)),B(`[retryNonMarkdownFile] Successfully reprocessed non-markdown file: ${r}`)}catch(o){throw ne(`[retryNonMarkdownFile] Error processing file ${r}: ${o}`),o}}getProjectAllFiles(e){let{inclusions:r,exclusions:n}=Xc({inclusions:e.contextSource.inclusions,exclusions:e.contextSource.exclusions,isProject:!0});return this.app.vault.getFiles().filter(o=>bl(o,r,n,!0))}onunload(){this.projectContextCache.cleanup()}}});function bce(t){if(!t)return!1;let e=t.view;return!e||typeof e!="object"?!1:typeof e.getViewType=="function"&&t.view.getViewType()===vJ}function yX(t){let e=t.view?.webview;if(!e||typeof e!="object"||typeof e.executeJavaScript!="function")throw new Mm
`;)e--;return t.substring(0,e)}function jHr(t){return NHr(AHr(t))}function jmt(t){return Dmt(t,Mri)}function $Hr(t){return Dmt(t,DHr)}function Iri(t){return FHr(t,DHr)}function Rri(t){return Dmt(t,LHr)}function Ari(t){return FHr(t,LHr)}function Dmt(t,e){return e.indexOf(t.nodeName)>=0}function FHr(t,e){return t.getElementsByTagName&&e.some(function(r){return t.getElementsByTagName(r).length})}function gDe(t){return t?t.replace(/(\n+\s*)+/g,`
`):""}function kHr(t){this.options=t,this._keep=[],this._remove=[],this.blankRule={replacement:t.blankReplacement},this.keepReplacement=t.keepReplacement,this.defaultRule={replacement:t.defaultReplacement},this.array=[];for(var e in t.rules)this.array.push(t.rules[e])}function Imt(t,e,r){for(var n=0;n<t.length;n++){var o=t[n];if(Nri(o,e,r))return o}}function Nri(t,e,r){var n=t.filter;if(typeof n=="string"){if(n===e.nodeName.toLowerCase())return!0}else if(Array.isArray(n)){if(n.indexOf(e.nodeName.toLowerCase())>-1)return!0}else if(typeof n=="function"){if(n.call(t,e,r))return!0}else throw new TypeError("`filter` needs to be a string, array, or function")}function jri(t){var e=t.element,r=t.isBlock,n=t.isVoid,o=t.isPre||function(d){return d.nodeName==="PRE"};if(!(!e.firstChild||o(e))){for(var i=null,a=!1,s=null,u=IHr(s,e,o);u!==e;){if(u.nodeType===3||u.nodeType===4){var l=u.data.replace(/[ \r\n\t]+/g," ");if((!i||/ $/.test(i.data))&&!a&&l[0]===" "&&(l=l.substr(1)),!l){u=Rmt(u);continue}u.data=l,i=u}else if(u.nodeType===1)r(u)||u.nodeName==="BR"?(i&&(i.data=i.data.replace(/ $/,"")),i=null,a=!1):n(u)||o(u)?(i=null,a=!0):i&&(a=!1);else{u=Rmt(u);continue}var c=IHr(s,u,o);s=u,u=c}i&&(i.data=i.data.replace(/ $/,""),i.data||Rmt(i))}}function Rmt(t){var e=t.nextSibling||t.parentNode;return t.parentNode.removeChild(t),e}function IHr(t,e,r){return t&&t.parentNode===e||r(e)?e.nextSibling||e.parentNode:e.firstChild||e.nextSibling||e.parentNode}function Dri(){var t=$mt.DOMParser,e=!1;try{new t().parseFromString("","text/html")&&(e=!0)}catch{}return e}function $ri(){var t=function(){};return Lri()?t.prototype.parseFromString=function(e){var r=new window.ActiveXObject("htmlfile");return r.designMode="on",r.open(),r.write(e),r.close(),r}:t.prototype.parseFromString=function(e){var r=document.implementation.createHTMLDocument("");return r.open(),r.write(e),r.close(),r},t}function Lri(){var t=!1;try{document.implementation.createHTMLDocument("").open()}catch{$mt.ActiveXObject&&(t=!0)}return t}function kri(t,e){var r;if(typeof t=="string"){var n=qri().parseFromString('<x-turndown id="turndown-root">'+t+"</x-turndown>","text/html");r=n.getElementById("turndown-root")}else r=t.cloneNode(!0);return jri({element:r,isBlock:jmt,isVoid:$Hr,isPre:e.preformattedCode?Uri:null}),r}function qri(){return Amt=Amt||new Fri,Amt}function Uri(t){return t.nodeName==="PRE"||t.nodeName==="CODE"}function Bri(t,e){return t.isBlock=jmt(t),t.isCode=t.nodeName==="CODE"||t.parentNode.isCode,t.isBlank=zri(t),t.flankingWhitespace=Vri(t,e),t}function zri(t){return!$Hr(t)&&!Rri(t)&&/^\s*$/i.test(t.textContent)&&!Iri(t)&&!Ari(t)}function Vri(t,e){if(t.isBlock||e.preformattedCode&&t.isCode)return{leading:"",trailing:""};var r=Hri(t.textContent);return r.leadingAscii&&RHr("left",t,e)&&(r.leading=r.leadingNonAscii),r.trailingAscii&&RHr("right",t,e)&&(r.trailing=r.trailingNonAscii),{leading:r.leading,trailing:r.trailing}}function Hri(t){var e=t.match(/^(([ \t\r\n]*)(\s*))(?:(?=\S)[\s\S]*\S)?((\s*?)([ \t\r\n]*))$/);return{leading:e[1],leadingAscii:e[2],leadingNonAscii:e[3],trailing:e[4],trailingNonAscii:e[5],trailingAscii:e[6]}}function RHr(t,e,r){var n,o,i;return t==="left"?(n=e.previousSibling,o=/ $/):(n=e.nextSibling,o=/^ /),n&&(n.nodeType===3?i=o.test(n.nodeValue):r.preformattedCode&&n.nodeName==="CODE"?i=!1:n.nodeType===1&&!jmt(n)&&(i=o.test(n.textContent))),i}function yDe(t){if(!(this instanceof yDe))return new yDe(t);var e={rules:jy,headingStyle:"setext",hr:"* * *",bulletListMarker:"*",codeBlockStyle:"indented",fence:"```",emDelimiter:"_",strongDelimiter:"**",linkStyle:"inlined",linkReferenceStyle:"full",br:" ",preformattedCode:!1,blankReplacement:function(r,n){return n.isBlock?`
`:""},keepReplacement:function(r,n){return n.isBlock?`
`+n.outerHTML+`
`:n.outerHTML},defaultReplacement:function(r,n){return n.isBlock?`
`+r+`
`:r}};this.options=Pri({},e,t),this.rules=new kHr(this.options)}function qHr(t){var e=this;return Jri.call(t.childNodes,function(r,n){n=new Bri(n,e.options);var o="";return n.nodeType===3?o=n.isCode?n.nodeValue:e.escape(n.nodeValue):n.nodeType===1&&(o=Gri.call(e,n)),UHr(r,o)},"")}function Kri(t){var e=this;return this.rules.forEach(function(r){typeof r.append=="function"&&(t=UHr(t,r.append(e.options)))}),t.replace(/^[\t\r\n]+/,"").replace(/[\t\r\n\s]+$/,"")}function Gri(t){var e=this.rules.forNode(t),r=qHr.call(this,t),n=t.flankingWhitespace;return(n.leading||n.trailing)&&(r=r.trim()),n.leading+e.replacement(r,t,this.options)+n.trailing}function UHr(t,e){var r=NHr(t),n=AHr(e),o=Math.max(t.length-r.length,e.length-n.length),i=`
`.substring(0,o);return r+i+n}function Xri(t){return t!=null&&(typeof t=="string"||t.nodeType&&(t.nodeType===1||t.nodeType===9||t.nodeType===11))}var Mri,DHr,LHr,jy,$mt,Fri,Amt,Jri,Wri,BHr,zHr=v(()=>{Mri=["ADDRESS","ARTICLE","ASIDE","AUDIO","BLOCKQUOTE","BODY","CANVAS","CENTER","DD","DIR","DIV","DL","DT","FIELDSET","FIGCAPTION","FIGURE","FOOTER","FORM","FRAMESET","H1","H2","H3","H4","H5","H6","HEADER","HGROUP","HR","HTML","ISINDEX","LI","MAIN","MENU","NAV","NOFRAMES","NOSCRIPT","OL","OUTPUT","P","PRE","SECTION","TABLE","TBODY","TD","TFOOT","TH","THEAD","TR","UL"];DHr=["AREA","BASE","BR","COL","COMMAND","EMBED","HR","IMG","INPUT","KEYGEN","LINK","META","PARAM","SOURCE","TRACK","WBR"];LHr=["A","TABLE","THEAD","TBODY","TFOOT","TH","TD","IFRAME","SCRIPT","AUDIO","VIDEO"];jy={};jy.paragraph={filter:"p",replacement:function(t){return`
`+t+`
`}};jy.lineBreak={filter:"br",replacement:function(t,e,r){return r.br+`
`}};jy.heading={filter:["h1","h2","h3","h4","h5","h6"],replacement:function(t,e,r){var n=Number(e.nodeName.charAt(1));if(r.headingStyle==="setext"&&n<3){var o=Nmt(n===1?"=":"-",t.length);return`
`+t+`
`+o+`
`}else return`
`+Nmt("#",n)+" "+t+`
`}};jy.blockquote={filter:"blockquote",replacement:function(t){return t=jHr(t).replace(/^/gm,"> "),`
`+t+`
`}};jy.list={filter:["ul","ol"],replacement:function(t,e){var r=e.parentNode;return r.nodeName==="LI"&&r.lastElementChild===e?`
`+t:`
`+t+`
`}};jy.listItem={filter:"li",replacement:function(t,e,r){var n=r.bulletListMarker+" ",o=e.parentNode;if(o.nodeName==="OL"){var i=o.getAttribute("start"),a=Array.prototype.indexOf.call(o.children,e);n=(i?Number(i)+a:a+1)+". "}var s=/\n$/.test(t);return t=jHr(t)+(s?`
`:""),t=t.replace(/\n/gm,`
`+" ".repeat(n.length)),n+t+(e.nextSibling?`
`:"")}};jy.indentedCodeBlock={filter:function(t,e){return e.codeBlockStyle==="indented"&&t.nodeName==="PRE"&&t.firstChild&&t.firstChild.nodeName==="CODE"},replacement:function(t,e,r){return`
`+e.firstChild.textContent.replace(/\n/g,`
`)+`
`}};jy.fencedCodeBlock={filter:function(t,e){return e.codeBlockStyle==="fenced"&&t.nodeName==="PRE"&&t.firstChild&&t.firstChild.nodeName==="CODE"},replacement:function(t,e,r){for(var n=e.firstChild.getAttribute("class")||"",o=(n.match(/language-(\S+)/)||[null,""])[1],i=e.firstChild.textContent,a=r.fence.charAt(0),s=3,u=new RegExp("^"+a+"{3,}","gm"),l;l=u.exec(i);)l[0].length>=s&&(s=l[0].length+1);var c=Nmt(a,s);return`
`+c+o+`
`+i.replace(/\n$/,"")+`
`+c+`
`}};jy.horizontalRule={filter:"hr",replacement:function(t,e,r){return`
`+r.hr+`
`}};jy.inlineLink={filter:function(t,e){return e.linkStyle==="inlined"&&t.nodeName==="A"&&t.getAttribute("href")},replacement:function(t,e){var r=e.getAttribute("href");r&&(r=r.replace(/([()])/g,"\\$1"));var n=gDe(e.getAttribute("title"));return n&&(n=' "'+n.replace(/"/g,'\\"')+'"'),"["+t+"]("+r+n+")"}};jy.referenceLink={filter:function(t,e){return e.linkStyle==="referenced"&&t.nodeName==="A"&&t.getAttribute("href")},replacement:function(t,e,r){var n=e.getAttribute("href"),o=gDe(e.getAttribute("title"));o&&(o=' "'+o+'"');var i,a;switch(r.linkReferenceStyle){case"collapsed":i="["+t+"][]",a="["+t+"]: "+n+o;break;case"shortcut":i="["+t+"]",a="["+t+"]: "+n+o;break;default:var s=this.references.length+1;i="["+t+"]["+s+"]",a="["+s+"]: "+n+o}return this.references.push(a),i},references:[],append:function(t){var e="";return this.references.length&&(e=`
`+this.references.join(`
`)+`
`,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?"!["+r+"]("+n+i+")":""}};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))throw new TypeError(t+" is not a string, or an element/document/fragment node.");if(t==="")return"";var e=qHr.call(this,new kri(t,this.options));return Kri.call(this,e)},use:function(t){if(Array.isArray(t))for(var e=0;e<t.length;e++)this.use(t[e]);else if(typeof t=="function")t(this);else throw new TypeError("plugin must be a Function or an Array of Functions");return this},addRule:function(t,e){return this.rules.add(t,e),this},keep:function(t){return this.rules.keep(t),this},remove:function(t){return this.rules.remove(t),this},escape:function(t){return Wri.reduce(function(e,r){return e.replace(r[0],r[1])},t)}};BHr=yDe});function _X(t){return typeof t=="object"&&t!==null}function vX(t){if(typeof t=="string")return t;if(t==null)return"";try{return String(t)}catch{return""}}function WHr(t){return t instanceof Error?t.message:vX(t)}async function Zri(t){await new Promise(e=>setTimeout(e,t))}async function KHr(t,e,r,n){let o=Date.now();for(;;){if(t())return;if(Date.now()-o>=e)throw new _w(`${n} timed out after ${e}ms`);await Zri(r)}}function VHr(t,e){let r=(t??"").trim();if(!r)return"";if(!e)return r;try{return new URL(r,e).href}catch{return r}}function HHr(t){let e=(t??"").trim();return e?/[\s)]/.test(e)?`<${e}>`:e:""}function Yri(t){let e=new BHr({headingStyle:"atx",hr:"---",bulletListMarker:"-",codeBlockStyle:"fenced",fence:"```",emDelimiter:"*",strongDelimiter:"**",linkStyle:"inlined"});return e.remove(["script","style","noscript"]),e.addRule("webviewer-link",{filter:"a",replacement:(r,n)=>{let o=n,i=o.getAttribute("href")??"",a=HHr(VHr(i,t)),s=r?.trim()||o.textContent||a;return a?`[${s}](${a})`:s}}),e.addRule("webviewer-image",{filter:"img",replacement:(r,n)=>{let o=n,i=o.getAttribute("alt")??"",a=o.getAttribute("src")??"",s=HHr(VHr(a,t));return s?`![${i}](${s})`:""}}),e}function Lmt(t,e){if(!t.trim())return"";let r=Yri(e),i=new DOMParser().parseFromString(`<div>${t}</div>`,"text/html").body.firstElementChild;return i?r.turndown(i).replace(/\n{3,}/g,`
`).trim():""}function Fmt(t){let e=t.commands;return!e||!_X(e)||typeof e.executeCommandById!="function"?null:e}function GHr(t,e){let r=Fmt(t);if(!r)return!1;if(r.commands){if(r.commands instanceof Map)return r.commands.has(e);if(typeof r.commands=="object")return e in r.commands}return typeof r.listCommands=="function"?r.listCommands().some(o=>o.id===e):!1}function XHr(t,e){return t.workspace.getLeavesOfType(vJ).includes(e)}function JHr(t){if(!_X(t)||t.enabled!==!0)return null;let e=t.instance;if(!e||!_X(e))return null;let r=e;return typeof r.openUrl=="function"||typeof r.handleOpenUrl=="function"?r:null}function ZHr(t,e){let r=t.internalPlugins;if(!r||!_X(r))return null;let n=r.plugins;if(!n)return null;let o=n instanceof Map?n.get(vJ):_X(n)?n[vJ]:null;if(o){let a=JHr(o);if(a)return a}let i;if(n instanceof Map)i=Array.from(n.values());else if(_X(n))i=Object.values(n);else return e&&e(),null;for(let a of i){let s=JHr(a);if(s)return s}return null}var bDe=v(()=>{zHr();bX()});function wX(t){return{url:typeof t.view?.url=="string"?t.view.url:"",title:typeof t.view?.title=="string"?t.view.title:"",faviconUrl:typeof t.view?.faviconUrl=="string"?t.view.faviconUrl:"",mode:t.view?.mode==="reader"?"reader":"webview"}}async function YHr(t,e={}){let{signal:r}=e;if(r?.aborted)throw new CU("Operation was aborted");try{let n=Promise.resolve(t.view.getReaderModeContent());if(!r){let i=await n;return typeof i?.md=="string"?i.md:""}let o=await new Promise((i,a)=>{let s=()=>{a(new CU("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)})});return typeof o?.md=="string"?o.md:""}catch(n){throw n instanceof CU||ne("Failed to get reader mode content:",n),n}}async function _De(t,e=!0){let r=yX(t),n='(() => { try { return window.getSelection?.()?.toString?.() ?? ""; } catch { return ""; } })()';try{let o=await r.executeJavaScript(n),i=vX(o);return e?i.trim():i}catch(o){throw ne("Failed to get selected text:",o),o}}async function vDe(t){let e=yX(t),r="";try{r=typeof e.getURL=="function"?e.getURL():""}catch{r=t.view?.url??""}let n=`(() => {
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{let i=await e.executeJavaScript(n);o=vX(i)}catch(i){throw ne("Failed to get selection HTML:",i),i}try{return Lmt(o,r)}catch(i){throw ne("Failed to convert HTML to Markdown:",i),i}}async function QHr(t){let e=yX(t),r="";try{r=typeof e.getURL=="function"?e.getURL():""}catch{r=t.view?.url??""}let n=`(() => {
const clone = document.body.cloneNode(true);
clone.querySelectorAll('script, style, noscript').forEach(el => el.remove());
return clone.innerHTML;
})()`,o="";try{let i=await e.executeJavaScript(n);o=vX(i)}catch(i){throw ne("Failed to get page HTML:",i),i}try{return Lmt(o,r)}catch(i){throw ne("Failed to convert page HTML to Markdown:",i),i}}async function eJr(t,e=!0){let r=yX(t),n=e?'(() => { try { return document.documentElement?.outerHTML ?? ""; } catch { return ""; } })()':'(() => { try { return document.body?.outerHTML ?? ""; } catch { return ""; } })()';try{let o=await r.executeJavaScript(n);return vX(o)}catch(o){throw ne("Failed to get HTML:",o),o}}function wDe(t){try{let e=new URL(t),r=e.hostname.replace(/^www\./,"").replace(/^m\./,"");return r==="youtube.com"&&e.pathname==="/watch"?e.searchParams.get("v"):r==="youtu.be"&&e.pathname.length>1?e.pathname.slice(1).split("/")[0]:(r==="youtube.com"&&e.pathname.startsWith("/shorts/")||r==="youtube.com"&&e.pathname.startsWith("/embed/"))&&e.pathname.split("/")[2]||null}catch{return null}}function tJr(t){return wDe(t)!==null}function Qri(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.videoId=="string"&&typeof e.title=="string"&&typeof e.channel=="string"&&(e.description===void 0||typeof e.description=="string")&&(e.uploadDate===void 0||typeof e.uploadDate=="string")&&(e.duration===void 0||typeof e.duration=="string")&&(e.genre===void 0||typeof e.genre=="string")&&Array.isArray(e.transcript)&&e.transcript.every(r=>typeof r=="object"&&r!==null&&typeof r.timestamp=="string"&&typeof r.text=="string")}async function rJr(t,e={}){let r=yX(t),{timeoutMs:n=1e4}=e,o=Math.ceil(n/500),i="";try{i=typeof r.getURL=="function"?r.getURL():""}catch{i=""}i||(i=t.view?.url??"");let a=wDe(i);if(!a)throw new Error("Not a YouTube video page");let s=`(async () => {
const videoId = ${JSON.stringify(a)};
// =========================================================================
// Step 1: Extract video metadata from JSON-LD (structured data)
// JSON-LD is more reliable than DOM selectors as it's machine-readable
// =========================================================================
let title = '';
let channel = '';
let description = '';
let uploadDate = '';
let duration = '';
let genre = '';
// Helper to extract fields from a VideoObject schema
const extractVideoObject = (data) => {
if (!data || data['@type'] !== 'VideoObject') return;
if (!title && data.name && typeof data.name === 'string') {
title = data.name;
}
if (!description && data.description && typeof data.description === 'string') {
description = data.description;
}
if (!uploadDate && data.uploadDate && typeof data.uploadDate === 'string') {
uploadDate = data.uploadDate;
}
// JSON-LD duration is ISO 8601 format (e.g., "PT12M34S"), convert to readable format
if (!duration && data.duration && typeof data.duration === 'string') {
const match = data.duration.match(/PT(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?/);
if (match) {
const h = match[1] ? match[1] + ':' : '';
const m = match[2] || '0';
const s = match[3] || '0';
duration = h + (h ? m.padStart(2, '0') : m) + ':' + s.padStart(2, '0');
}
}
if (!genre && data.genre) {
genre = Array.isArray(data.genre) ? data.genre.join(', ') : String(data.genre);
}
// author can be string, object {name}, or array [{name}]
if (!channel && data.author) {
const author = data.author;
if (typeof author === 'string') {
channel = author;
} else if (Array.isArray(author) && author[0]?.name) {
channel = String(author[0].name);
} else if (author?.name) {
channel = String(author.name);
}
}
};
// Parse all JSON-LD scripts, handling various formats (@graph, array, single object)
const ldJsonEls = document.querySelectorAll('script[type="application/ld+json"]');
for (const el of ldJsonEls) {
try {
const data = JSON.parse(el.textContent || '');
if (Array.isArray(data)) {
for (const item of data) {
extractVideoObject(item);
}
} else if (data['@graph'] && Array.isArray(data['@graph'])) {
for (const item of data['@graph']) {
extractVideoObject(item);
}
} else {
extractVideoObject(data);
}
// Stop if we have all essential fields
if (title && channel && description) break;
} catch {}
}
// =========================================================================
// Step 2: Fallback to DOM selectors for missing metadata
// =========================================================================
if (!title) {
title = document.querySelector('h1.ytd-watch-metadata yt-formatted-string')?.textContent?.trim()
|| document.querySelector('#title h1')?.textContent?.trim() || '';
}
if (!channel) {
channel = document.querySelector('#owner #channel-name a')?.textContent?.trim()
|| document.querySelector('#channel-name a')?.textContent?.trim()
|| document.querySelector('#channel-name')?.textContent?.trim() || '';
}
if (!duration) {
duration = document.querySelector('#ytd-player .ytp-time-duration')?.textContent?.trim() || '';
}
// =========================================================================
// Step 3: Try to extract transcript
// Check if transcript panel is already open, otherwise click the button
// =========================================================================
let segments = document.querySelectorAll('ytd-transcript-segment-renderer');
let needClose = false;
if (segments.length === 0) {
const btn = document.querySelector('ytd-video-description-transcript-section-renderer button');
if (btn) {
btn.click();
needClose = true;
// Wait for transcript to load (poll every 500ms)
for (let i = 0; i < ${o}; i++) {
await new Promise(r => setTimeout(r, 500));
segments = document.querySelectorAll('ytd-transcript-segment-renderer');
if (segments.length > 0) break;
}
}
}
// Helper to close the transcript panel (called in finally block)
const closePanel = () => {
if (needClose) {
const closeBtn = document.querySelector(
'ytd-engagement-panel-section-list-renderer[target-id="engagement-panel-searchable-transcript"] #visibility-button button'
);
if (closeBtn) closeBtn.click();
}
};
// =========================================================================
// Step 4: Extract transcript segments and return result
// =========================================================================
try {
const transcript = [...segments].map(seg => ({
timestamp: seg.querySelector('.segment-timestamp')?.textContent?.trim() || '',
text: seg.querySelector('yt-formatted-string.segment-text, .segment-text')?.textContent?.trim() || ''
})).filter(t => t.timestamp && t.text);
return { videoId, title, channel, description, uploadDate, duration, genre, transcript };
} finally {
// Step 5: Always close the transcript panel if we opened it
closePanel();
}
})()`,u=await r.executeJavaScript(s);if(!Qri(u))throw new Error("Invalid transcript data structure");return u}async function nJr(t,e,r={}){let{preferCommand:n=!0,focusLeafBeforeCommand:o=!0}=r;if(n)try{return await e(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{return await Promise.resolve(t.view.saveAsMarkdown()),B("Saved via view.saveAsMarkdown()"),{method:"view.saveAsMarkdown"}}catch(i){throw ne("Failed to save Web Viewer page:",i),i}}var kmt=v(()=>{_t();bX();bDe()});function Dy(t){if(typeof t!="string")return null;let e=t.trim();return e||null}function SX(t){if(typeof t!="string")return null;let e=t.trim();if(!e)return null;try{let r=new URL(e);r.hash="",(r.protocol==="http:"&&r.port==="80"||r.protocol==="https:"&&r.port==="443")&&(r.port=""),r.pathname!=="/"&&(r.pathname=r.pathname.replace(/\/+$/,""));let n=Array.from(r.searchParams.entries());return n.length>0?(n.sort(([o,i],[a,s])=>o!==a?o.localeCompare(a):i.localeCompare(s)),r.search=`?${new URLSearchParams(n).toString()}`):r.search="",r.toString()}catch{return e}}function iJr(t){return Dy(t)??void 0}function qmt(t){let e=Dy(t.url);if(!e)return null;let r=iJr(t.title),n=iJr(t.faviconUrl);return{url:e,title:r,faviconUrl:n,isLoaded:t.isLoaded,isActive:t.isActive?!0:void 0}}function wJ(t){let e=new Map;for(let r of t){let n=qmt(r);if(!n)continue;let o=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:void 0})}return Array.from(e.values())}function aJr(t){let e=wJ(t),r=!1;return e.map(n=>{if(!n.isActive)return n;if(!r)return r=!0,n;let{isActive:o,...i}=n;return i})}var CX=v(()=>{});var eni,SDe,sJr=v(()=>{_t();bDe();bX();CX();eni=["did-finish-load","page-favicon-updated","page-title-updated"],SDe=class t{constructor(e){this.lastActiveLeaf=null;this.activeWebTabState={activeWebTabForMentions:null,activeOrLastWebTab:null};this.activeWebTabLeaf=null;this.activeWebTabListeners=new Set;this.activeWebTabTrackingRefs=null;this.activeWebTabTrackingPreserveViewTypes=[];this.webviewLoadListeners=new Map;this.webviewLoadCallbacks=new Set;this.cancelScheduledWebviewLoadNotify=null;this.app=e.app,this.isSupportedPlatform=e.isSupportedPlatform,this.getActiveLeaf=e.getActiveLeaf,this.getLeaves=e.getLeaves,this.getPageInfo=e.getPageInfo}getLastActiveLeaf(){let e=this.lastActiveLeaf;return!e||!bce(e)?(this.lastActiveLeaf=null,null):XHr(this.app,e)?e:(this.lastActiveLeaf=null,null)}findLeafByUrl(e,r={}){let n=e.trim();if(!n)return null;let o=this.getLeaves();for(let c of o)if(c?.view?.url===n)return c;let i=SX(n);if(!i)return null;let a=[];for(let c of o){let d=c?.view?.url;if(!d)continue;SX(d)===i&&a.push(c)}if(a.length===0)return null;if(a.length===1)return a[0];let s=(r.title??"").trim();if(s){let c=s.toLowerCase(),d=[];for(let f of a)try{let m=(this.getPageInfo(f).title||"").trim();m&&m.toLowerCase()===c&&d.push(f)}catch{}if(d.length===1)return d[0];if(d.length>1){let f=this.getActiveLeaf();if(f&&d.includes(f))return f;let p=this.getLastActiveLeaf();return p&&d.includes(p)?p:(Be("[WebViewerStateManager] Multiple leaves matched URL + title; returning first match.",{url:n,title:s,matches:d.length}),d[0])}}let u=this.getActiveLeaf();if(u&&a.includes(u))return u;let l=this.getLastActiveLeaf();return l&&a.includes(l)?l:(Be("[WebViewerStateManager] Multiple leaves matched URL; returning first match as fallback.",{url:n,matches:a.length}),a[0])}getActiveWebTabState(){return this.activeWebTabState}subscribeActiveWebTabState(e){return this.activeWebTabListeners.add(e),()=>{this.activeWebTabListeners.delete(e)}}subscribeToWebviewLoad(e){return this.webviewLoadCallbacks.add(e),()=>{this.webviewLoadCallbacks.delete(e)}}startActiveWebTabTracking(e={}){this.activeWebTabTrackingRefs&&this.stopActiveWebTabTracking(),this.activeWebTabTrackingPreserveViewTypes=[...e.preserveOnViewTypes??[]];let r=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.
Title: {title}
Path: {path}
Content:
{content}
Summary:`;this.URL_BASED_TYPES=["url_content","web_tab_context","active_web_tab","youtube_video_context"];this.chatModelManager=l0.getInstance()}static getInstance(){return t.instance||(t.instance=new t),t.instance}async compact(e){let r=e.length;B(`[ContextCompactor] Starting compaction of ${r} chars`);let n=this.parseItems(e);if(n.length===0)return this.noOpResult(e);let o=await this.summarizeItems(n);if(o.size===0)return this.noOpResult(e);let i=this.rebuild(e,n,o);return B(`[ContextCompactor] Done: ${r} -> ${i.length} chars (${((1-i.length/r)*100).toFixed(0)}% reduction)`),{content:i,wasCompacted:!0,originalCharCount:r,compactedCharCount:i.length,itemsProcessed:n.length,itemsSummarized:o.size}}noOpResult(e){return{content:e,wasCompacted:!1,originalCharCount:e.length,compactedCharCount:e.length,itemsProcessed:0,itemsSummarized:0}}parseItems(e){let r=[];for(let n of this.BLOCK_TYPES){let o=new RegExp(`<${n}>[\\s\\S]*?<\\/${n}>`,"g"),i;for(;(i=o.exec(e))!==null;){let a=this.parseBlock(i[0],n,i.index);a&&r.push(a)}}return r.sort((n,o)=>n.startIndex-o.startIndex),r.filter((n,o)=>!r.some((i,a)=>o!==a&&i.startIndex<=n.startIndex&&i.endIndex>=n.endIndex))}parseBlock(e,r,n){let o=l=>new RegExp(`<${l}>([^<]*)</${l}>`).exec(e)?.[1]||"",i=()=>/<content>([\s\S]*?)<\/content>/.exec(e)?.[1]||"",a=o("path")||o("url"),s=o("title")||a.split("/").pop()||"Untitled",u=i();return{type:r,path:a,title:s,content:u,metadata:{ctime:o("ctime"),mtime:o("mtime")},originalXml:e,startIndex:n,endIndex:n+e.length}}async summarizeItems(e){let r=new Map,n=e.map((o,i)=>({index:i,item:o})).filter(({item:o})=>o.content.length>=this.MIN_ITEM_SIZE);if(n.length===0)return r;B(`[ContextCompactor] Summarizing ${n.length} items`);for(let o=0;o<n.length;o+=this.MAX_CONCURRENCY){let i=n.slice(o,o+this.MAX_CONCURRENCY);(await Promise.all(i.map(async({index:s,item:u})=>{try{return{index:s,summary:await this.summarize(u)}}catch(l){return B(`[ContextCompactor] Failed to summarize item ${s}:`,l),{index:s,summary:null}}}))).forEach(({index:s,summary:u})=>{u&&r.set(s,u)})}return r.size<n.length*.5?(B("[ContextCompactor] High failure rate, aborting compaction"),new Map):r}async summarize(e){let r=e.content;r.length>this.MAX_ITEM_SIZE&&(r=r.slice(0,this.MAX_ITEM_SIZE)+`
[TRUNCATED]`);let n=this.PROMPT.replace("{title}",e.title).replace("{path}",e.path).replace("{content}",r),i=await(await this.chatModelManager.getChatModelWithTemperature(this.TEMPERATURE)).invoke([new Hs(n)]);return typeof i.content=="string"?i.content.trim():""}rebuild(e,r,n){let o=e;return Array.from(n.keys()).sort((i,a)=>a-i).forEach(i=>{let a=r[i],s=n.get(i),u=this.buildBlock(a,s);o=o.slice(0,a.startIndex)+u+o.slice(a.endIndex)}),o}buildBlock(e,r){let n=[`<${e.type}>`];if(e.title&&n.push(`<title>${e.title}</title>`),e.path){let o=this.URL_BASED_TYPES.includes(e.type)?"url":"path";n.push(`<${o}>${e.path}</${o}>`)}return e.metadata.ctime&&n.push(`<ctime>${e.metadata.ctime}</ctime>`),e.metadata.mtime&&n.push(`<mtime>${e.metadata.mtime}</mtime>`),n.push(`<content>[SUMMARIZED]
${r}</content>`),n.push(`</${e.type}>`),n.join(`
`)}}});var Tbi={};Rn(Tbi,{default:()=>Bke});module.exports=zfe(Tbi);mR();k1();qs();Ez();Dot();iG();_t();F1();var THr=require("obsidian");to();var Xje=L(X());kn();var Zo=Xje.forwardRef(({className:t,type:e,...r},n)=>Xje.createElement("input",{type:e,className:Te("!tw-h-9 !tw-min-w-[50px] !tw-rounded-md !tw-border tw-border-solid tw-border-border !tw-bg-transparent !tw-px-3 !tw-py-1 !tw-text-sm !tw-transition-colors md:!tw-text-base","focus-visible:!tw-shadow-sm focus-visible:!tw-outline-none focus-visible:!tw-ring-1 focus-visible:!tw-ring-ring","placeholder:tw-text-sm","tw-flex tw-w-full tw-shadow-sm placeholder:tw-text-muted disabled:tw-cursor-not-allowed disabled:tw-opacity-50",t),ref:n,...r}));Zo.displayName="Input";var Zje=L(X());var eHr=L(X(),1);var ZVr=L(X(),1),Yti=L(cu(),1);Vu();var YVr=L(vr(),1),Qti=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],QVr=Qti.reduce((t,e)=>{let r=Fn(`Primitive.${e}`),n=ZVr.forwardRef((o,i)=>{let{asChild:a,...s}=o,u=a?r:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,YVr.jsx)(u,{...s,ref:i})});return n.displayName=`Primitive.${e}`,{...t,[e]:n}},{});var tHr=L(vr(),1),eri="Label",rHr=eHr.forwardRef((t,e)=>(0,tHr.jsx)(QVr.label,{...t,ref:e,onMouseDown:r=>{r.target.closest("button, input, select, textarea")||(t.onMouseDown?.(r),!r.defaultPrevented&&r.detail>1&&r.preventDefault())}}));rHr.displayName=eri;var mmt=rHr;Wye();kn();var rri=N6("tw-text-sm tw-font-medium tw-leading-none peer-disabled:tw-cursor-not-allowed peer-disabled:tw-opacity-70"),im=Zje.forwardRef(({className:t,...e},r)=>Zje.createElement(mmt,{ref:r,className:Te(rri(),t),...e}));im.displayName=mmt.displayName;var lX=L(X());var yw=L(X(),1);var oHr=L(X(),1);function nHr(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function hmt(...t){return e=>{let r=!1,n=t.map(o=>{let i=nHr(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():nHr(t[o],null)}}}}function iHr(...t){return oHr.useCallback(hmt(...t),t)}var FD=L(X(),1),aHr=L(vr(),1);function Yje(t,e=[]){let r=[];function n(i,a){let s=FD.createContext(a),u=r.length;r=[...r,a];let l=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[u]||s,y=FD.useMemo(()=>m,Object.values(m));return(0,aHr.jsx)(h.Provider,{value:y,children:p})};l.displayName=i+"Provider";function c(d,f){let p=f?.[t]?.[u]||s,m=FD.useContext(p);if(m)return m;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[l,c]}let o=()=>{let i=r.map(a=>FD.createContext(a));return function(s){let u=s?.[t]||i;return FD.useMemo(()=>({[`__scope${t}`]:{...s,[t]:u}}),[s,u])}};return o.scopeName=t,[n,nri(o,...e)]}function nri(...t){let e=t[0];if(t.length===1)return e;let r=()=>{let n=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let a=n.reduce((s,{useScope:u,scopeName:l})=>{let d=u(i)[`__scope${l}`];return{...s,...d}},{});return FD.useMemo(()=>({[`__scope${e.scopeName}`]:a}),[a])}};return r.scopeName=e.scopeName,r}function gmt(t,e,{checkForDefaultPrevented:r=!0}={}){return function(o){if(t?.(o),r===!1||!o.defaultPrevented)return e?.(o)}}var yU=L(X(),1);var sX=L(X(),1);function ymt(t){let e=sX.useRef(t);return sX.useEffect(()=>{e.current=t}),sX.useMemo(()=>(...r)=>e.current?.(...r),[])}function Qje({prop:t,defaultProp:e,onChange:r=()=>{}}){let[n,o]=ori({defaultProp:e,onChange:r}),i=t!==void 0,a=i?t:n,s=ymt(r),u=yU.useCallback(l=>{if(i){let d=typeof l=="function"?l(t):l;d!==t&&s(d)}else o(l)},[i,t,o,s]);return[a,u]}function ori({defaultProp:t,onChange:e}){let r=yU.useState(t),[n]=r,o=yU.useRef(n),i=ymt(e);return yU.useEffect(()=>{o.current!==n&&(i(n),o.current=n)},[n,o,i]),r}var eDe=L(X(),1);function sHr(t){let e=eDe.useRef({value:t,previous:t});return eDe.useMemo(()=>(e.current.value!==t&&(e.current.previous=e.current.value,e.current.value=t),e.current.previous),[t])}var lHr=L(X(),1);var uHr=L(X(),1),kD=globalThis?.document?uHr.useLayoutEffect:()=>{};function cHr(t){let[e,r]=lHr.useState(void 0);return kD(()=>{if(t){r({widt
1. Preserve the meaning and tone
2. Maintain appropriate cultural context
3. Keep formatting and structure
Return only the translated text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1010,modelKey:"",lastUsedMs:0},{title:"Summarize",content:"Create a bullet-point summary of {}. Each bullet point should capture a key point. Return only the bullet-point summary.",showInContextMenu:!0,showInSlashMenu:!0,order:1020,modelKey:"",lastUsedMs:0},{title:"Simplify",content:"Simplify {} to a 6th-grade reading level (ages 11-12). Use simple sentences, common words, and clear explanations. Maintain the original key concepts. Return only the simplified text.",showInContextMenu:!0,showInSlashMenu:!0,order:1030,modelKey:"",lastUsedMs:0},{title:"Explain like I am 5",content:`Explain {} in simple terms that a 5-year-old would understand:
1. Use basic vocabulary
2. Include simple analogies
3. Break down complex concepts
Return only the simplified explanation.`,showInContextMenu:!0,showInSlashMenu:!0,order:1040,modelKey:"",lastUsedMs:0},{title:"Emojify",content:`Add relevant emojis to enhance {}. Follow these rules:
1. Insert emojis at natural breaks in the text
2. Never place two emojis next to each other
3. Keep all original text unchanged
4. Choose emojis that match the context and tone
Return only the emojified text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1050,modelKey:"",lastUsedMs:0},{title:"Make shorter",content:`Reduce {} to half its length while preserving these elements:
1. Main ideas and key points
2. Essential details
3. Original tone and style
Return only the shortened text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1060,modelKey:"",lastUsedMs:0},{title:"Make longer",content:`Expand {} to twice its length by:
1. Adding relevant details and examples
2. Elaborating on key points
3. Maintaining the original tone and style
Return only the expanded text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1070,modelKey:"",lastUsedMs:0},{title:"Generate table of contents",content:"Generate a hierarchical table of contents for {}. Use appropriate heading levels (H1, H2, H3, etc.). Include page numbers if present. Return only the table of contents.",showInContextMenu:!1,showInSlashMenu:!1,order:1080,modelKey:"",lastUsedMs:0},{title:"Generate glossary",content:'Create a glossary of important terms, concepts, and phrases from {}. Format each entry as "Term: Definition". Sort entries alphabetically. Return only the glossary.',showInContextMenu:!1,showInSlashMenu:!1,order:1090,modelKey:"",lastUsedMs:0},{title:"Remove URLs",content:"Remove all URLs from {}. Preserve all other content and formatting. URLs may be in various formats (http, https, www). Return only the text with URLs removed.",showInContextMenu:!1,showInSlashMenu:!1,order:1100,modelKey:"",lastUsedMs:0},{title:"Rewrite as tweet",content:`Rewrite {} as a single tweet with these requirements:
1. Maximum 280 characters
2. Use concise, impactful language
3. Maintain the core message
Return only the tweet text.`,showInContextMenu:!1,showInSlashMenu:!1,order:1110,modelKey:"",lastUsedMs:0},{title:"Rewrite as tweet thread",content:`Convert {} into a Twitter thread following these rules:
1. Each tweet must be under 240 characters
2. Start with "THREAD START" on its own line
3. Separate tweets with "
---
"
4. End with "THREAD END" on its own line
5. Make content engaging and clear
Return only the formatted thread.`,showInContextMenu:!1,showInSlashMenu:!1,order:1120,modelKey:"",lastUsedMs:0},{title:"Clip YouTube Transcript",content:`
Based on the YouTube video information and transcript provided in the context, generate a complete Obsidian note in the following format.
IMPORTANT: If no YouTube video context is found, remind the user to:
1. Open a YouTube video in Web Viewer (or use @ to select a YouTube web tab)
2. Then use this command again
Generate the note with this exact structure:
---
title: "<video title>"
description: "<first 200 chars of description>"
channel: "<channel name>"
url: "<video url>"
duration: "<duration>"
published: <upload date in YYYY-MM-DD format>
thumbnailUrl: "<YouTube thumbnail URL: i.ytimg.com/vi/VIDEO_ID/maxresdefault.jpg with https protocol>"
genre:
- "<genre>"
watched:
---
![<video title>](<video url>)
> [!summary]- Description
> <full video description, preserve line breaks>
## Summary
<Brief 2-3 paragraph summary of the video 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
- Do NOT use icons or emojis
- Keep all node text short and simple - max 3-4 words per node
- Use only letters, numbers, and spaces
Example of CORRECT syntax:
\`\`\`mermaid
mindmap
root(Video Main Topic)
First Theme
Detail one
Detail two
Second Theme
Detail three
Third Theme
\`\`\`
## Notable Quotes
<List 5-10 notable quotes from the transcript. Format each as:>
- [<timestamp>: <quote text>](<video_url>&t=<seconds>s)
Return only the markdown content without any explanations or comments.`,showInContextMenu:!1,showInSlashMenu:!0,order:1130,modelKey:"",lastUsedMs:0},{title:"Clip Web Page",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: "<page title>"
source: "<page url>"
description: "<brief description>"
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?"Command name cannot have leading or trailing spaces":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"}function pX(t){return encodeURIComponent(t.toLowerCase())}function vU(){return(0,fX.normalizePath)(ae().customPromptsFolder)}function mX(t){return`${vU()}/${t}.md`}function hX(t){if(!(t instanceof fX.TFile)||t.extension!=="md")return!1;let e=vU();return!(!t.path.startsWith(e+"/")||t.path.slice(e.length+1).includes("/"))}function xHr(t){return app.metadataCache.getFileCache(t)?.frontmatter?.[fA]!=null}async function mce(t){let e=await app.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}}async function aDe(){let t=app.vault.getFiles().filter(r=>hX(r)),e=await Promise.all(t.map(mce));return nDe(e),e}function hce(t){return mO(t,"manual",{getName:e=>e.title,getCreatedAtMs:()=>0,getLastUsedAtMs:()=>0,getManualOrder:e=>e.order})}function vri(t){return mO(t,"recent",{getName:e=>e.title,getCreatedAtMs:()=>0,getLastUsedAtMs:e=>e.lastUsedMs})}function wri(t){return mO(t,"name",{getName:e=>e.title,getCreatedAtMs:()=>0,getLastUsedAtMs:()=>0})}function sDe(t){switch(ae().promptSortStrategy){case"timestamp":return vri(t);case"alphabetical":return wri(t);case"manual":return hce(t);default:return t}}async function Emt(t,e,r=!1){let o=(await gce(t,e,app.vault,app.workspace.getActiveFile())).processedPrompt;if(o.includes(`{${n_}}`)||r)return o;let i=o.indexOf(Omt);return i===-1&&e.trim()?o+`
<`+n_+">"+e+"</"+n_+">":o.slice(0,i)+e+o.slice(i+Omt.length)}var Sri=/\{(?!copilot-selection\}|\[\[)([^}]+)\}/g;async function Cri(t,e,r){let n=new Map,o=new Set,i;for(;(i=Sri.exec(t))!==null;){let a=i[1].trim(),s={content:"",files:[]},u=a.toLowerCase();if(u==="activenote")if(r){let l=await BW(r,e);l&&(s.content=`<${Nz}>
<path>${r.path}</path>
## ${uge(r)}
${l}
</${Nz}>`,s.files.push(r))}else new fX.Notice("No active note found.");else{if(u==="activewebtab")continue;if(a.startsWith("#")){let l=a.slice(1).split(",").map(f=>f.trim()),c=await sge(e,l),d=[];for(let f of c){let p=await BW(f,e);p&&(d.push(`<${Nz}>
<path>${f.path}</path>
## ${uge(f)}
${p}
</${Nz}>`),s.files.push(f))}s.content=d.join(`
`)}else{let l=IRt(a),c=await Eee(e,l),d=[];for(let f of c){let p=await BW(f,e);p&&(d.push(`<${Nz}>
<path>${f.path}</path>
## ${uge(f)}
${p}
</${Nz}>`),s.files.push(f))}s.content=d.join(`
`)}}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}}async function gce(t,e,r,n,o=!1){let i=ae(),a=new Set;if(!i.enableCustomPromptTemplating)return!o&&t.includes("{}")&&!e&&n&&a.add(n),{processedPrompt:t+`
`,includedFiles:Array.from(a)};let{variablesMap:s,includedFiles:u}=await Cri(t,r,n);u.forEach(p=>a.add(p));let l=t,c="",d=null;!o&&l.includes("{}")&&(l=l.replace(/\{\}/g,`{${n_}}`),e?c+=`<${n_}>
${e}
</${n_}>`:n?(d=await BW(n,r),c+=`<${n_} type="active_note">
${d||""}
</${n_}>`,a.add(n)):c+=`<${n_}>
(No selected text or active note available)
</${n_}>`);for(let[p,m]of s.entries())p.toLowerCase()==="activenote"&&d!==null||(c?c+=`
<${jee} name="${p}">
${m}
</${jee}>`:c+=`<${jee} name="${p}">
${m}
</${jee}>`);let f=MRt(l,r);for(let p of f)if(!a.has(p)){let m=await BW(p,r);if(m){let h=await r.adapter.stat(p.path),y=h?new Date(h.ctime).toISOString():"Unknown",g=h?new Date(h.mtime).toISOString():"Unknown",b=`<${Nee}>
<title>${p.basename}</title>
<path>${p.path}</path>
<ctime>${y}</ctime>
<mtime>${g}</mtime>
<content>
${m}
</content>
</${Nee}>`;c&&(c+=`
`),c+=`${b}`,a.add(p)}}return{processedPrompt:c?`${l}
${c}`:`${l}
`,includedFiles:Array.from(a)}}function OHr(t,e){let n=`${t} (copy)`,o=1;for(;e.some(i=>i.title.toLowerCase()===n.toLowerCase());)o++,n=`${t} (copy ${o})`;return n}function uDe(){let e=z_().reduce((r,n)=>r>n.order?r:n.order,0);return e===Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:e+10}async function Pmt(t,e){try{yJ(t.path),await app.fileManager.processFrontMatter(t,r=>{r[qD]==null&&(r[qD]=e.showInContextMenu),r[UD]==null&&(r[UD]=e.showInSlashMenu),r[fA]==null&&(r[fA]=e.order),r[BD]==null&&(r[BD]=e.modelKey),r[zD]==null&&(r[zD]=e.lastUsedMs)})}finally{bJ(t.path)}}function lDe(t){let e=t.getCursor("from"),r=t.getCursor("to"),o=t.getValue().split(`
`),i=!1,a=[],s=0,u=0,l=0;for(;l<o.length;)if(o[l].trim()===`\`\`\`${dX}`){i=!0;let c=l;for(l++;l<o.length&&o[l].trim()!=="```";)l++;l++;let d=l-c;c<=e.line&&(s+=d),c<=r.line&&(u+=d)}else a.push(o[l]),l++;if(i){t.setValue(a.join(`
`));let c=Math.max(0,e.line-s),d=Math.max(0,r.line-u);t.setSelection({line:c,ch:e.ch},{line:d,ch:r.ch})}return i}function xri({commands:t,command:e,onConfirm:r,onCancel:n}){let i=zr().activeModels.filter(f=>f.enabled).map(f=>({label:rDe(f),value:oo(f)})),[a,s]=(0,$s.useState)(e),[u,l]=(0,$s.useState)({}),c=(f,p)=>{s(m=>({...m,[f]:p})),l(m=>({...m,[f]:void 0}))},d=()=>{let f={},p=iDe(a.title,t,e.title);if(p&&(f.title=p),a.content.trim()||(f.content="Prompt is required"),Object.keys(f).length>0){l(f);return}r(a)};return $s.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4 tw-p-4"},$s.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},$s.default.createElement(im,{htmlFor:"title"},"Name"),$s.default.createElement(Zo,{id:"title",value:a.title,onChange:f=>c("title",f.target.value),placeholder:"Enter command name"}),u.title&&$s.default.createElement("div",{className:"tw-text-sm tw-text-error"},u.title)),$s.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},$s.default.createElement(im,{htmlFor:"content"},"Prompt"),$s.default.createElement(SHr,null),$s.default.createElement(bw,{id:"content",value:a.content,onChange:f=>c("content",f.target.value),placeholder:"Enter command prompt",className:"tw-min-h-[200px]"}),u.content&&$s.default.createElement("div",{className:"tw-text-sm tw-text-error"},u.content)),$s.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},$s.default.createElement(im,{htmlFor:"modelKey"},"Model (Optional)"),$s.default.createElement("div",{className:"tw-group tw-relative tw-w-full"},$s.default.createElement("select",{value:a.modelKey,onChange:f=>{let p=f.target.value;if(!p){c("modelKey","");return}if(!i.find(h=>h.value===p)){ne(`Model ${p} not found`),c("modelKey","");return}c("modelKey",f.target.value)},className:Te("tw-w-full tw-appearance-none","tw-flex tw-h-9 tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-dropdown tw-px-3 tw-py-1 tw-pr-8","tw-text-sm !tw-shadow tw-transition-colors","focus:tw-outline-none focus:tw-ring-1 focus:tw-ring-ring","disabled:tw-cursor-not-allowed disabled:tw-opacity-50","hover:tw-bg-interactive-hover hover:tw-text-normal")},$s.default.createElement("option",{value:""},"Inherit from chat model"),i.map(f=>$s.default.createElement("option",{key:f.value,value:f.value.toString()},f.label))),$s.default.createElement("div",{className:Te("tw-pointer-events-none tw-absolute tw-inset-y-0 tw-right-0 tw-flex tw-items-center tw-pr-2","tw-transition-colors group-hover:[&>svg]:tw-text-normal")},$s.default.createElement(ts,{className:"tw-size-4"})))),$s.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},$s.default.createElement(Qc,{id:"showInContextMenu",checked:a.showInContextMenu,onCheckedChange:f=>c("showInContextMenu",f)}),$s.default.createElement(im,{htmlFor:"showInContextMenu"},"Show in context menu")),$s.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},$s.default.createElement(Qc,{id:"showInSlashMenu",checked:a.showInSlashMenu,onCheckedChange:f=>c("showInSlashMenu",f)}),$s.default.createElement(im,{htmlFor:"showInSlashMenu"},"Show in slash menu")),$s.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},$s.default.createElement(ge,{variant:"secondary",onClick:n},"Cancel"),$s.default.createElement(ge,{variant:"default",onClick:d},"Save")))}var wU=class extends THr.Modal{constructor(r,n,o,i){super(r);this.commands=n;this.command=o;this.onUpdate=i;this.setTitle("Edit Command")}onOpen(){let{contentEl:r}=this;this.root=(0,EHr.createRoot)(r);let n=o=>{this.onUpdate(o),this.close()};this.root.render($s.default.createElement(xri,{commands:this.commands,command:this.command,onConfirm:n,onCancel:()=>this.close()}))}onClose(){this.root.unmount()}};var yce=require("obsidian");Xw();Zt();var Um=class t{static getInstance(){return t.instance||(t.instance=new t),t.instance}async createCommand(e,r={}){let n={skipStoreUpdate:!1,autoOrder:!0,...r},o=mX(e.title);try{yJ(o);let i=e.order;n.autoOrder&&(i=uDe()),e={...e,order:i};let a=vU();await xc(a);let
Source: ${d.url}
${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=`# YouTube Video Transcript
Source: ${d.url}
${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(`Selected text contains ${i} words and ${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(`Total tokens in your vault: ${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}
\`\`\`
`;return i.replaceRange(l,{line:u,ch:0}),!0}),Ah(t,Nn.CLEAR_LOCAL_COPILOT_INDEX,async()=>{try{await(await Promise.resolve().then(()=>(Am(),xg))).default.getInstance().clearIndex(),new Ci.Notice("Cleared local Copilot semantic index.")}catch(n){ne("Error clearing semantic index:",n),new Ci.Notice("Failed to clear semantic index.")}}),Ah(t,Nn.GARBAGE_COLLECT_COPILOT_INDEX,async()=>{try{let o=await(await Promise.resolve().then(()=>(Am(),xg))).default.getInstance().garbageCollectVectorStore();new Ci.Notice(`Garbage collection completed. Removed ${o} stale documents.`)}catch(n){ne("Error during garbage collection:",n),new Ci.Notice("Failed to garbage collect semantic index.")}}),Ah(t,Nn.INDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let{getSettings:n}=await Promise.resolve().then(()=>(ot(),See));if(n().enableSemanticSearchV3){let a=await(await Promise.resolve().then(()=>(Am(),xg))).default.getInstance().indexVaultToVectorStore(!1);new Ci.Notice(`Semantic search index refreshed with ${a} documents.`)}else new Ci.Notice("Lexical search builds indexes on demand. No manual indexing required.")}catch(n){ne("Error building index:",n),new Ci.Notice("An error occurred while building the index.")}}),Ah(t,Nn.FORCE_REINDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let{getSettings:n}=await Promise.resolve().then(()=>(ot(),See));if(n().enableSemanticSearchV3){let a=await(await Promise.resolve().then(()=>(Am(),xg))).default.getInstance().indexVaultToVectorStore(!0);new Ci.Notice(`Semantic search index rebuilt with ${a} documents.`)}else new Ci.Notice("Lexical search builds indexes on demand. No manual indexing required.")}catch(n){ne("Error rebuilding index:",n),new Ci.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{let o=await(await Promise.resolve().then(()=>(Am(),xg))).default.getInstance().getIndexedFiles(),{getMatchingPatterns:i,shouldIndexFile:a}=await Promise.resolve().then(()=>(vb(),vgr)),{inclusions:s,exclusions:u}=i(),l=t.app.vault.getMarkdownFiles(),c=new Set,d=new Set,f=new Set,p=new Set(o);for(let w of l){if(!a(w,s,u)){f.add(w.path);continue}let O=await t.app.vault.cachedRead(w);!O||O.trim().length===0?c.add(w.path):p.has(w.path)||d.add(w.path)}let m=["# 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-${new Date().toLocaleDateString().replace(/\//g,"-")}.md`,y="copilot",g=`${y}/${h}`;await xc(y);let b=t.app.vault.getAbstractFileByPath(g);b?await t.app.vault.modify(b,m):await t.app.vault.create(g,m);let _=t.app.vault.getAbstractFileByPath(g);_&&(await t.app.workspace.getLeaf().openFile(_),new Ci.Notice(`Listed ${p.size} indexed files`))}catch(n){ne("Error listing indexed files:",n),new Ci.Notice("Failed to list indexed files.")}}),Ah(t,Nn.INSPECT_COPILOT_INDEX_BY_NOTE_PATHS,async()=>{try{let n=t.app.workspace.getActiveFile();if(!n){new Ci.Notice("No active file. Please open a note first.");return}let o=(await Promise.resolve().then(()=>(Am(),xg))).default,{DBOperations:i}=await Promise.resolve().then(()=>(_ie(),Cgr)),a=await o.getInstance().getDb(),s=await i.getDocsByPath(a,n.path);if(!s||s.length===0){new Ci.Notice(`No embedding data found for: ${n.path}`);return}let u=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)=>{let g=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}`;await xc(d);let p=t.app.vault.getAbstractFileByPath(f);p?await t.app.vault.modify(p,l):await t.app.vault.create(f,l);let m=t.app.vault.getAbstractFileByPath(f);m&&(await t.app.workspace.getLeaf().openFile(m),new Ci.Notice(`Embedding debug info for ${u.length} chunk(s)`))}catch(n){ne("Error inspecting embeddings:",n),new Ci.Notice("Failed to inspect embeddings. Is the index loaded?")}}),Ah(t,Nn.CLEAR_COPILOT_CACHE,async()=>{try{await t.fileParserManager.clearPDFCache(),await Yv.getInstance().clearAllCache(),await nG.getInstance().clear(),new Ci.Notice("All Copilot caches cleared successfully")}catch(n){ne("Error clearing Copilot caches:",n),new Ci.Notice("Failed to clear Copilot caches")}}),Ah(t,Nn.OPEN_LOG_FILE,async()=>{try{await $Te(),await pm.openLogFile()}catch(n){ne("Error creating Copilot log file:",n),new Ci.Notice("Failed to create Copilot log file.")}}),Ah(t,Nn.CLEAR_LOG_FILE,async()=>{try{await pm.clear(),new Ci.Notice("Copilot log cleared.")}catch(n){ne("Error clearing Copilot log file:",n),new Ci.Notice("Failed to clear Copilot log file.")}}),fJr(t,Nn.ADD_SELECTION_TO_CHAT_CONTEXT,async n=>{let o=n.getSelection();if(!o){new Ci.Notice("No text selected");return}let i=t.app.workspace.getActiveFile();if(!i){new Ci.Notice("No active file");return}let a=n.listSelections()[0];if(!a){new Ci.Notice("Could not determine selection range");return}let s=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}=await import("obsidian");if(!n.isDesktopApp){new Ci.Notice("Web selection is only available on desktop");return}let{getWebViewerService:o}=await Promise.resolve().then(()=>(SJ(),dJr));try{let i=o(t.app),a=i.getActiveLeaf()??i.getLastActiveLeaf();if(!a){new Ci.Notice("No active Web Tab found");return}let s=await i.getSelectedMarkdown(a);if(!s.trim()){new Ci.Notice("No text selected in Web Tab");return}let u=i.getPageInfo(a),l={id:Zm(),content:s,sourceType:"web",title:u.title||"Untitled",url:u.url,faviconUrl:u.faviconUrl||void 0};yN([l]),t.activateView()}catch(i){ne("Error adding web selection to context:",i),new Ci.Notice("Failed to get web selection")}}),Ah(t,Nn.ADD_CUSTOM_COMMAND,async()=>{let n=z_(),o={...dA};new wU(t.app,n,o,async a=>{await Um.getInstance().createCommand(a)}).open()}),Ah(t,Nn.APPLY_CUSTOM_COMMAND,()=>{new cDe(t.app).open()}),Ah(t,Nn.DOWNLOAD_YOUTUBE_SCRIPT,async()=>{if(!await $S()){new Ci.Notice("Download YouTube Script (plus) is a Copilot Plus feature");return}new fDe(t.app).open()})}qs();var OX={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";var xU=require("obsidian");ot();Zt();YH();_t();function _ce(t,e,r){let n=t.trim();return n?t!==n?"Prompt name cannot have leading or trailing spaces":r&&t===r?null:/[#<>:"/\\|?*[\]^\x00-\x1F]/g.test(n)?'Prompt name contains invalid characters. Avoid using: < > : " / \\ | ? * [ ] ^':e.some(i=>i.title.toLowerCase()===n.toLowerCase())?"A prompt with this name already exists":null:"Prompt name cannot be empty"}function y0(){return(0,xU.normalizePath)(ae().userSystemPromptsFolder)}function b0(t){return(0,xU.normalizePath)(`${y0()}/${t}.md`)}function sni(t,e){let r=e?(0,xU.normalizePath)(e):y0();return(0,xU.normalizePath)(`${r}/${t}.md`)}function MX(t){if(!(t instanceof xU.TFile)||t.extension!=="md")return!1;let e=y0();if(!t.path.startsWith(e+"/"))return!1;let r=t.path.slice(e.length+1);return!(r.startsWith("unsupported/")||r.includes("/"))}function Vmt(t,e){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let r=Number(t);if(Number.isFinite(r))return r}return e}async function CJ(t){let e=await app.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=`> Migration failed: ${r}
>
> To fix: Review the content below, then move this file to ${n}
${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(`Migration verification failed: content mismatch. 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(`Default name already exists, using unique name: "${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,()=>{},`We have upgraded your system prompt to the new file-based format. It is now stored as "${o}" in ${n}.
You can now:
\u2022 Edit your system prompt directly in the file
\u2022 Create multiple system prompts
\u2022 Manage prompts through the settings UI
Your migrated prompt has been set as the default system prompt.`,"\u{1F680} System Prompt Upgraded","OK","").open()}else{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\uFE0F System Prompt Migration Issue
Your system prompt was migrated but verification failed. Your data has been saved to:
${d}
To recover:
1. Open the file and review the content
2. Move it to ${n}
3. The prompt will be available immediately`,"Migration Verification Failed","OK","").open()}}catch(n){ne("Failed to migrate legacy userSystemPrompt:",n);try{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\uFE0F System Prompt Migration Failed
An error occurred during migration. Your data has been saved to:
${o}
To recover:
1. Open the file and review the content
2. Move it to ${y0()}
3. The prompt will be available immediately`,"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,()=>{},`Failed to migrate system prompt: ${n.message}
Unable to save to file system. Your system prompt is still in settings and will continue to work.
Please check:
- Folder permissions for ${y0()}
- Available disk space
- Vault is accessible
You can retry by reloading the plugin.`,"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]}let o=()=>{let i=r.map(a=>VD.createContext(a));return function(s){let u=s?.[t]||i;return VD.useMemo(()=>({[`__scope${t}`]:{...s,[t]:u}}),[s,u])}};return o.scopeName=t,[n,pni(o,...e)]}function pni(...t){let e=t[0];if(t.length===1)return e;let r=()=>{let n=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let a=n.reduce((s,{useScope:u,scopeName:l})=>{let d=u(i)[`__scope${l}`];return{...s,...d}},{});return VD.useMemo(()=>({[`__scope${e.scopeName}`]:a}),[a])}};return r.scopeName=e.scopeName,r}var _0=L(X(),1);var OJr=L(X(),1),ODe=globalThis?.document?OJr.useLayoutEffect:()=>{};var TDe=L(X(),1);var mni=_0[" useInsertionEffect ".trim().toString()]||ODe;function TJr({prop:t,defaultProp:e,onChange:r=()=>{},caller:n}){let[o,i,a]=hni({defaultProp:e,onChange:r}),s=t!==void 0,u=s?t:o;{let c=_0.useRef(t!==void 0);_0.useEffect(()=>{let d=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])}let l=_0.useCallback(c=>{if(s){let d=gni(c)?c(t):c;d!==t&&a.current?.(d)}else i(c)},[s,t,i,a]);return[u,l]}function hni({defaultProp:t,onChange:e}){let[r,n]=_0.useState(t),o=_0.useRef(r),i=_0.useRef(e);return mni(()=>{i.current=e},[e]),_0.useEffect(()=>{o.current!==r&&(i.current?.(r),o.current=r)},[r,o]),[r,n,i]}function gni(t){return typeof t=="function"}var TSs=Symbol("RADIX:SYNC_STATE");var EJr=L(X(),1),yni=L(cu(),1);Vu();var PJr=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)=>{let r=Fn(`Primitive.${e}`),n=EJr.forwardRef((o,i)=>{let{asChild:a,...s}=o,u=a?r:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,PJr.jsx)(u,{...s,ref:i})});return n.displayName=`Primitive.${e}`,{...t,[e]:n}},{});var Ur=L(X(),1);var ISs=!!(typeof window<"u"&&window.document&&window.document.createElement);function Dc(t,e,{checkForDefaultPrevented:r=!0}={}){return function(o){if(t?.(o),r===!1||!o.defaultPrevented)return e?.(o)}}var OU=L(X(),1);var HD=L(X(),1),IJr=L(vr(),1);function RJr(t,e=[]){let r=[];function n(i,a){let s=HD.createContext(a),u=r.length;r=[...r,a];let l=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";function c(d,f){let p=f?.[t]?.[u]||s,m=HD.useContext(p);if(m)return m;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[l,c]}let o=()=>{let i=r.map(a=>HD.createContext(a))
.`.concat(Eht,` {
overflow: hidden `).concat(n,`;
padding-right: `).concat(s,"px ").concat(n,`;
}
body[`).concat(HX,`] {
overflow: hidden `).concat(n,`;
overscroll-behavior: contain;
`).concat([e&&"position: relative ".concat(n,";"),r==="margin"&&`
padding-left: `.concat(o,`px;
padding-top: `).concat(i,`px;
padding-right: `).concat(a,`px;
margin-left:0;
margin-top:0;
margin-right: `).concat(s,"px ").concat(n,`;
`),r==="padding"&&"padding-right: ".concat(s,"px ").concat(n,";")].filter(Boolean).join(""),`
}
.`).concat(jJ,` {
right: `).concat(s,"px ").concat(n,`;
}
.`).concat(DJ,` {
margin-right: `).concat(s,"px ").concat(n,`;
}
.`).concat(jJ," .").concat(jJ,` {
right: 0 `).concat(n,`;
}
.`).concat(DJ," .").concat(DJ,` {
margin-right: 0 `).concat(n,`;
}
body[`).concat(HX,`] {
`).concat(Pht,": ").concat(s,`px;
}
`)},S6r=function(){var t=parseInt(document.body.getAttribute(HX)||"0",10);return isFinite(t)?t:0},Pii=function(){JX.useEffect(function(){return document.body.setAttribute(HX,(S6r()+1).toString()),function(){var t=S6r()-1;t<=0?document.body.removeAttribute(HX):document.body.setAttribute(HX,t.toString())}},[])},Lht=function(t){var e=t.noRelative,r=t.noImportant,n=t.gapMode,o=n===void 0?"margin":n;Pii();var i=JX.useMemo(function(){return $ht(o)},[o]);return JX.createElement(Tii,{styles:Eii(i,!e,o,r?"":"!important")})};var Fht=!1;if(typeof window<"u")try{jce=Object.defineProperty({},"passive",{get:function(){return Fht=!0,!0}}),window.addEventListener("test",jce,jce),window.removeEventListener("test",jce,jce)}catch{Fht=!1}var jce,$J=Fht?{passive:!1}:!1;var Mii=function(t){return t.tagName==="TEXTAREA"},C6r=function(t,e){if(!(t instanceof Element))return!1;var r=window.getComputedStyle(t);return r[e]!=="hidden"&&!(r.overflowY===r.overflowX&&!Mii(t)&&r[e]==="visible")},Iii=function(t){return C6r(t,"overflowY")},Rii=function(t){return C6r(t,"overflowX")},kht=function(t,e){var r=e.ownerDocument,n=e;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var o=x6r(t,n);if(o){var i=O6r(t,n),a=i[1],s=i[2];if(a>s)return!0}n=n.parentNode}while(n&&n!==r.body);return!1},Aii=function(t){var e=t.scrollTop,r=t.scrollHeight,n=t.clientHeight;return[e,r,n]},Nii=function(t){var e=t.scrollLeft,r=t.scrollWidth,n=t.clientWidth;return[e,r,n]},x6r=function(t,e){return t==="v"?Iii(e):Rii(e)},O6r=function(t,e){return t==="v"?Aii(e):Nii(e)},jii=function(t,e){return t==="h"&&e==="rtl"?-1:1},T6r=function(t,e,r,n,o){var i=jii(t,window.getComputedStyle(e).direction),a=i*n,s=r.target,u=e.contains(s),l=!1,c=a>0,d=0,f=0;do{if(!s)break;var p=O6r(t,s),m=p[0],h=p[1],y=p[2],g=h-y-i*m;(m||g)&&x6r(t,s)&&(d+=g,f+=m);var b=s.parentNode;s=b&&b.nodeType===Node.DOCUMENT_FRAGMENT_NODE?b.host:b}while(!u&&s!==document.body||u&&(e.contains(s)||e===s));return(c&&(o&&Math.abs(d)<1||!o&&a>d)||!c&&(o&&Math.abs(f)<1||!o&&-a>f))&&(l=!0),l};var t$e=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},E6r=function(t){return[t.deltaX,t.deltaY]},P6r=function(t){return t&&"current"in t?t.current:t},Dii=function(t,e){return t[0]===e[0]&&t[1]===e[1]},$ii=function(t){return`
.block-interactivity-`.concat(t,` {pointer-events: none;}
.allow-interactivity-`).concat(t,` {pointer-events: all;}
`)},Lii=0,WX=[];function M6r(t){var e=wl.useRef([]),r=wl.useRef([0,0]),n=wl.useRef(),o=wl.useState(Lii++)[0],i=wl.useState(Nce)[0],a=wl.useRef(t);wl.useEffect(function(){a.current=t},[t]),wl.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var h=p6r([t.lockRef.current],(t.shards||[]).map(P6r),!0).filter(Boolean);return h.forEach(function(y){return y.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),h.forEach(function(y){return y.classList.remove("allow-interactivity-".concat(o))})}}},[t.inert,t.lockRef.current,t.shards]);var s=wl.useCallback(function(h,y){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!a.current.allowPinchZoom;var g=t$e(h),b=r.current,_="deltaX"in h?h.deltaX:b[0]-g[0],w="deltaY"in h?h.deltaY:b[1]-g[1],O,T=h.target,P=Math.abs(_)>Math.abs(w)?"h":"v";if("touches"in h&&P==="h"&&T.type==="range")return!1;var M=kht(P,T);if(!M)return!0;if(M?O=P:(O=P==="v"?"h":"v",M=kht(P,T)),!M)return!1;if(!n.current&&"changedTouches"in h&&(_||w)&&(n.current=O),!O)return!0;var I=n.current||O;return T6r(I,y,h,I==="h"?_:w,!0)},[]),u=wl.useCallback(function(h){var y=h;if(!(!WX.length||WX[WX.length-1]!==i)){var g="deltaY"in y?E6r(y):t$e(y),b=e.current.filter(function(O){return O.name===y.type&&(O.target===y.target||y.target===O.shadowParent)&&Dii(O.delta,g)})[0];if(b&&b.should){y.cancelable&&y.preventDefault();return}if(!b){var _=(a.current.shards||[]).map(P6r).filter(Boolean).filter(function(O){return O.contains(y.target)}),w=_.length>0?s(y,_[0]):!a.current.noIsolation;w&&y.cancelable&&y.preventDefault()}}},[]),l=wl.useCallback(function(h,y,g,b){var _={name:h,delta:y,target:g,should:b,shadowParent:Fii(g)};e.current.push(_),setTimeout(function(){e.current=e.current.filter(function(w){return w!==_})},1)},[]),c=wl.useCallback(function(h){r.current=t$e(h),n.current=void 0},[]),d=wl.useCallback(function(h){l(h.type,E6r(h),h.target,s(h,t.lockRef.current))},[]),f=wl.useCallback(function(h){l(h.type,t$e(h),h.target,s(h,t.lockRef.current))},[]);wl.useEffect(function(){return WX.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,$J),document.addEventListener("touchmove",u,$J),document.addEventListener("touchstart",c,$J),function(){WX=WX.filter(function(h){return h!==i}),document.removeEventListener("wheel",u,$J),document.removeEventListener("touchmove",u,$J),document.removeEventListener("touchstart",c,$J)}},[]);var p=t.removeScrollBar,m=t.inert;return wl.createElement(wl.Fragment,null,m?wl.createElement(i,{styles:$ii(o)}):null,p?wl.createElement(Lht,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function Fii(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var I6r=Rht(e$e,M6r);var R6r=r$e.forwardRef(function(t,e){return r$e.createElement(Ace,W_({},t,{ref:e,sideCar:I6r}))});R6r.classNames=Ace.classNames;var QD=R6r;var Oo=L(vr(),1),qht=["Enter"," "],kii=["ArrowDown","PageUp","Home"],N6r=["ArrowUp","PageDown","End"],qii=[...kii,...N6r],Uii={ltr:[...qht,"ArrowRight"],rtl:[...qht,"ArrowLeft"]},Bii={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Fce="Menu",[$ce,zii,Vii]=TU(Fce),[LJ,Uht]=LJr(Fce,[Vii,C0,Oht]),kce=C0(),j6r=Oht(),[D6r,DU]=LJ(Fce),[Hii,qce]=LJ(Fce),$6r=t=>{let{__scopeMenu:e,open:r=!1,children:n,dir:o,onOpenChange:i,modal:a=!0}=t,s=kce(e),[u,l]=Ur.useState(null),c=Ur.useRef(!1),d=KDe(i),f=FJr(o);return Ur.useEffect(()=>{let p=()=>{c.current=!0,document.addEventListener("pointerdown",m,{capture:!0,once:!0}),document.addEventListener("pointermove",m,{capture:!0,once:!0})},m=()=>c.current=!1;return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",m,{capture:!0}),document.removeEventListener("pointermove",m,{capture:!0})}},[]),(0,Oo.jsx)(XD,{...s,children:(0,Oo.jsx)(D6r,{scope:e,open:r,onOpenChange:d,content:u,onContentChange:l,children:(0,Oo.jsx)(Hii,{scope:e,onClose:Ur.useCallb
`,Uli=QJ?"\xA0":yLe,$9r="\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC",L9r="A-Za-z\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u0300-\u0590\u0800-\u1FFF\u200E\u2C00-\uFB1C\uFE00-\uFE6F\uFEFD-\uFFFF",Bli=new RegExp("^[^"+L9r+"]*["+$9r+"]"),zli=new RegExp("^[^"+$9r+"]*["+L9r+"]"),Ly={bold:1,capitalize:1024,code:16,highlight:gLe,italic:2,lowercase:256,strikethrough:lde,subscript:32,superscript:64,underline:cde,uppercase:512},Vli={directionless:1,unmergeable:2},zGr={center:jyt,end:Fyt,justify:$yt,left:Nyt,right:Dyt,start:Lyt},Hli={[jyt]:"center",[Fyt]:"end",[$yt]:"justify",[Nyt]:"left",[Dyt]:"right",[Lyt]:"start"},Jli={normal:0,segmented:2,token:1},Wli={[Nli]:"normal",[Dli]:"segmented",[jli]:"token"},Kli="$",VGr="$config";function F9r(t,e,r,n,o,i){let a=t.getFirstChild();for(;a!==null;){let s=a.__key;a.__parent===e&&(Ze(a)&&F9r(a,s,r,n,o,i),r.has(s)||i.delete(s),o.push(s)),a=a.getNextSibling()}}var Gli=100,ayt=!1,kyt=0;function Xli(t){kyt=t.timeStamp}function Wgt(t,e,r){let n=t.nodeName==="BR",o=e.__lexicalLineBreak;return o&&(t===o||n&&t.previousSibling===o)||n&&xLe(t,r)!==void 0}function Zli(t,e,r){let n=OA(R0(r)),o=null,i=null;n!==null&&n.anchorNode===t&&(o=n.anchorOffset,i=n.focusOffset);let a=t.nodeValue;a!==null&&ibt(e,a,o,i,!1)}function Yli(t,e,r){if(un(t)){let n=t.anchor.getNode();if(n.is(r)&&t.format!==n.getFormat())return!1}return TA(e)&&r.isAttached()}function Qli(t,e,r,n){for(let o=t;o&&!sXr(o);o=wde(o)){let i=xLe(o,e);if(i!==void 0){let a=Jm(i,r);if(a)return Lu(a)||!Fb(o)?void 0:[o,a]}else if(o===n)return[n,H7r(r)]}}function k9r(t,e,r){ayt=!0;let n=performance.now()-kyt>Gli;try{ww(t,()=>{let o=Ls()||function(f){return f.getEditorState().read(()=>{let p=Ls();return p!==null?p.clone():null})}(t),i=new Map,a=t.getRootElement(),s=t._editorState,u=t._blockCursorElement,l=!1,c="";for(let f=0;f<e.length;f++){let p=e[f],m=p.type,h=p.target,y=Qli(h,t,s,a);if(!y)continue;let[g,b]=y;if(m==="characterData")n&&Pr(b)&&TA(h)&&Yli(o,h,b)&&Zli(h,b,t);else if(m==="childList"){l=!0;let _=p.addedNodes;for(let T=0;T<_.length;T++){let P=_[T],M=z7r(P),I=P.parentNode;if(I!=null&&P!==u&&M===null&&!Wgt(P,I,t)){if(QJ){let j=(Fb(P)?P.innerText:null)||P.nodeValue;j&&(c+=j)}I.removeChild(P)}}let w=p.removedNodes,O=w.length;if(O>0){let T=0;for(let P=0;P<O;P++){let M=w[P];(Wgt(M,h,t)||u===M)&&(h.appendChild(M),T++)}O!==T&&i.set(g,b)}}}if(i.size>0)for(let[f,p]of i)p.reconcileObservedMutation(f,t);let d=r.takeRecords();if(d.length>0){for(let f=0;f<d.length;f++){let p=d[f],m=p.addedNodes,h=p.target;for(let y=0;y<m.length;y++){let g=m[y],b=g.parentNode;b==null||g.nodeName!=="BR"||Wgt(g,h,t)||b.removeChild(g)}}r.takeRecords()}o!==null&&(l&&nv(o),QJ&&Z7r(t)&&o.insertRawText(c))})}finally{ayt=!1}}function q9r(t){let e=t._observer;e!==null&&k9r(t,e.takeRecords(),e)}function U9r(t){(function(e){kyt===0&&R0(e).addEventListener("textInput",Xli,!0)})(t),t._observer=new MutationObserver((e,r)=>{k9r(t,e,r)})}var syt=class{constructor(e,r){this.key=e,this.parse=r.parse.bind(r),this.unparse=(r.unparse||nci).bind(r),this.isEqual=(r.isEqual||Object.is).bind(r),this.defaultValue=this.parse(void 0)}};function eci(t,e){return new syt(t,e)}function eLe(t,e,r="latest"){let n=(r==="latest"?t.getLatest():t).__state;return n?n.getValue(e):e.defaultValue}function tci(t,e,r){let n=eLe(t,r,"direct"),o=eLe(e,r,"direct");return r.isEqual(n,o)?null:[n,o]}function rci(t,e,r){let n;if(Lh(),typeof r=="function"){let i=t.getLatest(),a=eLe(i,e);if(n=r(a),e.isEqual(a,n))return i}else n=r;let o=t.getWritable();return qyt(o).updateFromKnown(e,n),o}function B9r(t){let e=new Map,r=new Set;for(let n=typeof t=="function"?t:t.replace;n.prototype&&n.prototype.getType!==void 0;n=Object.getPrototypeOf(n)){let{ownNodeConfig:o}=dbt(n);if(o&&o.stateConfigs)for(let i of o.stateConfigs){let a;"stateConfig"in i?(a=i.stateConfig,i.flat&&r.add(a.key)):a=i,e.set(a.key,a)}}return{flatKeys:r,sharedConfigMap:e}}var uyt=class t{constructor(e,r,n=void 0,o=new Map,i=void 0){this.node=e,this.sharedNodeState=r,this.unknownState=n,this.knownState=o;let{sharedConfigMap:a}=this.sharedNodeState,s=i!==void 0?i:function(u,l,c){let
`)r.preventDefault(),gr(n,rde,!1);else if(u===g$)r.preventDefault(),gr(n,hyt,void 0);else if(u==null&&r.dataTransfer){let p=r.dataTransfer.getData("text/plain");r.preventDefault(),a.insertRawText(p)}else u!=null&&_7r(a,i,u,r.timeStamp,!0)?(r.preventDefault(),gr(n,cZ,u)):uZ=u;y7r=r.timeStamp}})}(t,e)]);var nde=0,g7r=null,y7r=0,uZ=null,aLe=new WeakMap,vyt=!1,wyt=!1,ode=!1,Qce=!1,Ggt=!1,Xgt="",ZJ=null,b7r=[0,"",0,"root",0];function _7r(t,e,r,n,o){let i=t.anchor,a=t.focus,s=i.getNode(),u=ec(),l=OA(R0(u)),c=l!==null?l.anchorNode:null,d=i.key,f=u.getElementByKey(d),p=r.length;return d!==a.key||!Pr(s)||(!o&&(!Z$e||y7r<n+50)||s.isDirty()&&p<2||J7r(r))&&i.offset!==a.offset&&!s.isComposing()||c$(s)||s.isDirty()&&p>1||(o||!Z$e)&&f!==null&&!s.isComposing()&&c!==o3(f)||l!==null&&e!==null&&(!e.collapsed||e.startContainer!==l.anchorNode||e.startOffset!==l.anchorOffset)||s.getFormat()!==t.format||s.getStyle()!==t.style||function(m,h){if(h.isSegmented())return!0;if(!m.isCollapsed())return!1;let y=m.anchor.offset,g=h.getParentOrThrow(),b=ZU(h);return y===0?!h.canInsertTextBefore()||!g.canInsertTextBefore()&&!h.isComposing()||b||function(_){let w=_.getPreviousSibling();return(Pr(w)||Ze(w)&&w.isInline())&&!w.canInsertTextAfter()}(h):y===h.getTextContentSize()&&(!h.canInsertTextAfter()||!g.canInsertTextAfter()&&!h.isComposing()||b)}(t,s)}function e9r(t,e){return TA(t)&&t.nodeValue!==null&&e!==0&&e!==t.nodeValue.length}function t9r(t,e,r){let{anchorNode:n,anchorOffset:o,focusNode:i,focusOffset:a}=t;vyt&&(vyt=!1,e9r(n,o)&&e9r(i,a)&&!ZJ)||ww(e,()=>{if(!r)return void nv(null);if(!_de(e,n,i))return;let s=Ls();if(ZJ&&un(s)&&s.isCollapsed()){let u=s.anchor,l=ZJ.anchor;(u.key===l.key&&u.offset===l.offset+1||u.offset===1&&l.getNode().is(u.getNode().getPreviousSibling()))&&(s=ZJ.clone(),nv(s))}if(ZJ=null,un(s)){let u=s.anchor,l=u.getNode();if(s.isCollapsed()){t.type==="Range"&&t.anchorNode===t.focusNode&&(s.dirty=!0);let c=R0(e).event,d=c?c.timeStamp:performance.now(),[f,p,m,h,y]=b7r,g=rv(),b=e.isComposing()===!1&&g.getTextContent()==="";if(d<y+200&&u.offset===m&&u.key===h)K$e(s,f,p);else if(u.type==="text")Pr(l)||Qe(141),v7r(s,l);else if(u.type==="element"&&!b){Ze(l)||Qe(259);let _=u.getNode();_.isEmpty()?function(w,O){let T=O.getTextFormat(),P=O.getTextStyle();K$e(w,T,P)}(s,_):K$e(s,0,"")}}else{let c=u.key,d=s.focus.key,f=s.getNodes(),p=f.length,m=s.isBackward(),h=m?a:o,y=m?o:a,g=m?d:c,b=m?c:d,_=D9r,w=!1;for(let O=0;O<p;O++){let T=f[O],P=T.getTextContentSize();if(Pr(T)&&P!==0&&!(O===0&&T.__key===g&&h===P||O===p-1&&T.__key===b&&y===0)&&(w=!0,_&=T.getFormat(),_===0))break}s.format=w?_:0}}gr(e,Uyt,void 0)})}function K$e(t,e,r){t.format===e&&t.style===r||(t.format=e,t.style=r,t.dirty=!0)}function v7r(t,e){K$e(t,e.getFormat(),e.getStyle())}function w7r(t){if(!t.getTargetRanges)return null;let e=t.getTargetRanges();return e.length===0?null:e[0]}function B$e(t,e){let r=t._compositionKey;if(Fh(null),r!==null&&e!=null){if(e===""){let n=Jm(r),o=o3(t.getElementByKey(r));return void(o!==null&&o.nodeValue!==null&&Pr(n)&&ibt(n,o.nodeValue,null,null,!0))}if(e[e.length-1]===`
`){let n=Ls();if(un(n)){let o=n.focus;return n.anchor.set(o.key,o.offset,o.type),void gr(t,iLe,null)}}}obt(!0,t,e)}function S7r(t){let e=t.__lexicalEventHandles;return e===void 0&&(e=[],t.__lexicalEventHandles=e),e}var dZ=new Map;function C7r(t){let e=rXr(t.target);if(e===null)return;let r=rbt(e.anchorNode);if(r===null)return;wyt&&(wyt=!1,ww(r,()=>{let u=a3(),l=e.anchorNode;(Fb(l)||TA(l))&&nv(wLe(u,e,r,t))}));let n=nbt(r),o=n[n.length-1],i=o._key,a=dZ.get(i),s=a||o;s!==r&&t9r(e,s,!1),t9r(e,r,!0),r!==o?dZ.set(i,r):a&&dZ.delete(i)}function r9r(t){t._lexicalHandled=!0}function n9r(t){return t._lexicalHandled===!0}var gci=()=>{};function yci(t){let e=t.ownerDocument,r=aLe.get(e);if(r===void 0)return void gci();let n=r-1;n>=0||Qe(164),aLe.set(e,n),n===0&&e.removeEventListener("selectionchange",C7r);let o=vde(t);CLe(o)?(function(a){if(a._parentEditor!==null){let s=nbt(a),u=s[s.length-1]._key;dZ.get(u)===a&&dZ.delete(u)}else dZ.delete(a._key)}(o),t.__lexicalEditor=null):o&&Qe(198);let i=S7r(t);for(let a=0;a<i.length;a++)i[a]();t.__lexicalEventHandles=[]}function Syt(t,e,r){Lh();let n=t.__key,o=t.getParent();if(o===null)return;let i=function(s){let u=Ls();if(!un(u)||!Ze(s))return u;let{anchor:l,focus:c}=u,d=l.getNode(),f=c.getNode();return mLe(d,s)&&l.set(s.__key,0,"element"),mLe(f,s)&&c.set(s.__key,0,"element"),u}(t),a=!1;if(un(i)&&e){let s=i.anchor,u=i.focus;s.key===n&&(lLe(s,t,o,t.getPreviousSibling(),t.getNextSibling()),a=!0),u.key===n&&(lLe(u,t,o,t.getPreviousSibling(),t.getNextSibling()),a=!0)}else vLe(i)&&e&&t.isSelected()&&t.selectPrevious();if(un(i)&&e&&!a){let s=t.getIndexWithinParent();YU(t),uLe(i,o,s,-1)}else YU(t);r||Lx(o)||o.canBeEmpty()||!o.isEmpty()||Syt(o,e),e&&i&&ev(o)&&o.isEmpty()&&o.selectEnd()}function bci(t){return t}var eB=class{static getType(){let{ownNodeType:e}=dbt(this);return e===void 0&&Qe(64,this.name),e}static clone(e){Qe(65,this.name)}$config(){return{}}config(e,r){let n=r.extends||Object.getPrototypeOf(this.constructor);return Object.assign(r,{extends:n,type:e}),{[e]:r}}afterCloneFrom(e){this.__key===e.__key?(this.__parent=e.__parent,this.__next=e.__next,this.__prev=e.__prev,this.__state=e.__state):e.__state&&(this.__state=e.__state.getWritable(this))}constructor(e){this.__type=this.constructor.getType(),this.__parent=null,this.__prev=null,this.__next=null,Object.defineProperty(this,"__state",{configurable:!0,enumerable:!1,value:void 0,writable:!0}),B7r(this,e)}getType(){return this.__type}isInline(){Qe(137,this.constructor.name)}isAttached(){let e=this.__key;for(;e!==null;){if(e==="root")return!0;let r=Jm(e);if(r===null)break;e=r.__parent}return!1}isSelected(e){let r=e||Ls();if(r==null)return!1;let n=r.getNodes().some(o=>o.__key===this.__key);if(Pr(this))return n;if(un(r)&&r.anchor.type==="element"&&r.focus.type==="element"){if(r.isCollapsed())return!1;let o=this.getParent();if(Lu(this)&&this.isInline()&&o){let i=r.isBackward()?r.focus:r.anchor;if(o.is(i.getNode())&&i.offset===o.getChildrenSize()&&this.is(o.getLastChild()))return!1}}return n}getKey(){return this.__key}getIndexWithinParent(){let e=this.getParent();if(e===null)return-1;let r=e.getFirstChild(),n=0;for(;r!==null;){if(this.is(r))return n;n++,r=r.getNextSibling()}return-1}getParent(){let e=this.getLatest().__parent;return e===null?null:Jm(e)}getParentOrThrow(){let e=this.getParent();return e===null&&Qe(66,this.__key),e}getTopLevelElement(){let e=this;for(;e!==null;){let r=e.getParent();if(Lx(r))return Ze(e)||e===this&&Lu(e)||Qe(194),e;e=r}return null}getTopLevelElementOrThrow(){let e=this.getTopLevelElement();return e===null&&Qe(67,this.__key),e}getParents(){let e=[],r=this.getParent();for(;r!==null;)e.push(r),r=r.getParent();return e}getParentKeys(){let e=[],r=this.getParent();for(;r!==null;)e.push(r.__key),r=r.getParent();return e}getPreviousSibling(){let e=this.getLatest().__prev;return e===null?null:Jm(e)}getPreviousSiblings(){let e=[],r=this.getParent();if(r===null)return e;let n=r.getFirstChild();for(;n!==null&&!n.is(this);)e.push(n),n=n.getNextSibling();return e}getNextSibling(){let e=this.getLatest().__next;return e===null?nu
`}createDOM(){return document.createElement("br")}updateDOM(){return!1}isInline(){return!0}static importDOM(){return{br:e=>function(r){let n=r.parentElement;if(n!==null&&Pyt(n)){let o=n.firstChild;if(o===r||o.nextSibling===r&&z$e(o)){let i=n.lastChild;if(i===r||i.previousSibling===r&&z$e(i))return!0}}return!1}(e)||function(r){let n=r.parentElement;if(n!==null&&Pyt(n)){let o=n.firstChild;if(o===r||o.nextSibling===r&&z$e(o))return!1;let i=n.lastChild;if(i===r||i.previousSibling===r&&z$e(i))return!0}return!1}(e)?null:{conversion:_ci,priority:0}}}static importJSON(e){return gZ().updateFromJSON(e)}};function _ci(t){return{node:gZ()}}function gZ(){return Sde(new hZ)}function YJ(t){return t instanceof hZ}function z$e(t){return TA(t)&&/^( |\t|\r?\n)+$/.test(t.textContent||"")}function Zgt(t,e){return 16&e?"code":e&gLe?"mark":32&e?"sub":64&e?"sup":null}function Ygt(t,e){return 1&e?"strong":2&e?"em":"span"}function x7r(t,e,r,n,o){let i=n.classList,a=fZ(o,"base");a!==void 0&&i.add(...a),a=fZ(o,"underlineStrikethrough");let s=!1,u=e&cde&&e&lde;a!==void 0&&(r&cde&&r&lde?(s=!0,u||i.add(...a)):u&&i.remove(...a));for(let l in Ly){let c=Ly[l];if(a=fZ(o,l),a!==void 0)if(r&c){if(s&&(l==="underline"||l==="strikethrough")){e&c&&i.remove(...a);continue}e&c&&(!u||l!=="underline")&&l!=="strikethrough"||i.add(...a)}else e&c&&i.remove(...a)}}function O7r(t,e,r){let n=e.firstChild,o=r.isComposing(),i=t+(o?yLe:"");if(n==null)e.textContent=i;else{let a=n.nodeValue;if(a!==i)if(o||QJ){let[s,u,l]=function(c,d){let f=c.length,p=d.length,m=0,h=0;for(;m<f&&m<p&&c[m]===d[m];)m++;for(;h+m<f&&h+m<p&&c[f-h-1]===d[p-h-1];)h++;return[m,f-m-h,d.slice(m,p-h)]}(a,i);u!==0&&n.deleteData(s,u),n.insertData(s,l)}else n.nodeValue=i}}function o9r(t,e,r,n,o,i){O7r(o,t,e);let a=i.theme.text;a!==void 0&&x7r(0,0,n,t,a)}function V$e(t,e){let r=document.createElement(e);return r.appendChild(t),r}var r3=class t extends eB{static getType(){return"text"}static clone(e){return new t(e.__text,e.__key)}afterCloneFrom(e){super.afterCloneFrom(e),this.__text=e.__text,this.__format=e.__format,this.__style=e.__style,this.__mode=e.__mode,this.__detail=e.__detail}constructor(e="",r){super(r),this.__text=e,this.__format=0,this.__style="",this.__mode=0,this.__detail=0}getFormat(){return this.getLatest().__format}getDetail(){return this.getLatest().__detail}getMode(){let e=this.getLatest();return Wli[e.__mode]}getStyle(){return this.getLatest().__style}isToken(){return this.getLatest().__mode===1}isComposing(){return this.__key===XU()}isSegmented(){return this.getLatest().__mode===2}isDirectionless(){return!!(1&this.getLatest().__detail)}isUnmergeable(){return!!(2&this.getLatest().__detail)}hasFormat(e){let r=Ly[e];return!!(this.getFormat()&r)}isSimpleText(){return this.__type==="text"&&this.__mode===0}getTextContent(){return this.getLatest().__text}getFormatFlags(e,r){return fLe(this.getLatest().__format,e,r)}canHaveFormat(){return!0}isInline(){return!0}createDOM(e,r){let n=this.__format,o=Zgt(0,n),i=Ygt(0,n),a=o===null?i:o,s=document.createElement(a),u=s;this.hasFormat("code")&&s.setAttribute("spellcheck","false"),o!==null&&(u=document.createElement(i),s.appendChild(u)),o9r(u,this,0,n,this.__text,e);let l=this.__style;return l!==""&&(s.style.cssText=l),s}updateDOM(e,r,n){let o=this.__text,i=e.__format,a=this.__format,s=Zgt(0,i),u=Zgt(0,a),l=Ygt(0,i),c=Ygt(0,a);if((s===null?l:s)!==(u===null?c:u))return!0;if(s===u&&l!==c){let h=r.firstChild;h==null&&Qe(48);let y=document.createElement(c);return o9r(y,this,0,a,o,n),r.replaceChild(y,h),!1}let d=r;u!==null&&s!==null&&(d=r.firstChild,d==null&&Qe(49)),O7r(o,d,this);let f=n.theme.text;f!==void 0&&i!==a&&x7r(0,i,a,d,f);let p=e.__style,m=this.__style;return p!==m&&(r.style.cssText=m),!1}static importDOM(){return{"#text":()=>({conversion:Cci,priority:0}),b:()=>({conversion:wci,priority:0}),code:()=>({conversion:u$,priority:0}),em:()=>({conversion:u$,priority:0}),i:()=>({conversion:u$,priority:0}),mark:()=>({conversion:u$,priority:0}),s:()=>({conversion:u$,priority:0}),span:()=>({conversion:vci,priority:0}),strong:()=>({conversion:u$,priority:0}),sub
`||s===`\r
`?o.push(gZ()):s===" "?o.push(_Le()):s!==""&&o.push($h(s))}return{node:o}}if(r=r.replace(/\r/g,"").replace(/[ \t\n]+/g," "),r==="")return{node:null};if(r[0]===" "){let n=e,o=!0;for(;n!==null&&(n=a9r(n,!1))!==null;){let i=n.textContent||"";if(i.length>0){/[ \t\n]$/.test(i)&&(r=r.slice(1)),o=!1;break}}o&&(r=r.slice(1))}if(r[r.length-1]===" "){let n=e,o=!0;for(;n!==null&&(n=a9r(n,!0))!==null;)if((n.textContent||"").replace(/^( |\t|\r?\n)+/,"").length>0){o=!1;break}o&&(r=r.slice(0,r.length-1))}return r===""?{node:null}:{node:$h(r)}}function a9r(t,e){let r=t;for(;;){let n;for(;(n=e?r.nextSibling:r.previousSibling)===null;){let i=r.parentElement;if(i===null)return null;r=i}if(r=n,Fb(r)){let i=r.style.display;if(i===""&&!oXr(r)||i!==""&&!i.startsWith("inline"))return null}let o=r;for(;(o=e?r.firstChild:r.lastChild)!==null;)r=o;if(TA(r))return r;if(r.nodeName==="BR")return null}}var xci={code:"code",em:"italic",i:"italic",mark:"highlight",s:"strikethrough",strong:"bold",sub:"subscript",sup:"superscript",u:"underline"};function u$(t){let e=xci[t.nodeName.toLowerCase()];return e===void 0?{node:null}:{forChild:Wyt(t.style,e),node:null}}function $h(t=""){return Sde(new r3(t))}function Pr(t){return t instanceof r3}function Wyt(t,e){let r=t.fontWeight,n=t.textDecoration.split(" "),o=r==="700"||r==="bold",i=n.includes("line-through"),a=t.fontStyle==="italic",s=n.includes("underline"),u=t.verticalAlign;return l=>(Pr(l)&&(o&&!l.hasFormat("bold")&&l.toggleFormat("bold"),i&&!l.hasFormat("strikethrough")&&l.toggleFormat("strikethrough"),a&&!l.hasFormat("italic")&&l.toggleFormat("italic"),s&&!l.hasFormat("underline")&&l.toggleFormat("underline"),u!=="sub"||l.hasFormat("subscript")||l.toggleFormat("subscript"),u!=="super"||l.hasFormat("superscript")||l.toggleFormat("superscript"),e&&!l.hasFormat(e)&&l.toggleFormat(e)),l)}var yZ=class t extends r3{static getType(){return"tab"}static clone(e){return new t(e.__key)}constructor(e){super(" ",e),this.__detail=2}static importDOM(){return null}createDOM(e){let r=super.createDOM(e),n=fZ(e.theme,"tab");return n!==void 0&&r.classList.add(...n),r}static importJSON(e){return _Le().updateFromJSON(e)}setTextContent(e){return e!==" "&&e!==""&&Qe(126),super.setTextContent(" ")}spliceText(e,r,n,o){return n===""&&r===0||n===" "&&r===1||Qe(286),this}setDetail(e){return e!==2&&Qe(127),this}setMode(e){return e!=="normal"&&Qe(128),this}canInsertTextBefore(){return!1}canInsertTextAfter(){return!1}};function _Le(){return Sde(new yZ)}function Kyt(t){return t instanceof yZ}var Cyt=class{constructor(e,r,n){this._selection=null,this.key=e,this.offset=r,this.type=n}is(e){return this.key===e.key&&this.offset===e.offset&&this.type===e.type}isBefore(e){return this.key===e.key?this.offset<e.offset:hbt(Ax(oB(this,"next")),Ax(oB(e,"next")))<0}getNode(){let e=Jm(this.key);return e===null&&Qe(20),e}set(e,r,n,o){let i=this._selection,a=this.key;o&&this.key===e&&this.offset===r&&this.type===n||(this.key=e,this.offset=r,this.type=n,EZ()||(XU()===a&&Fh(e),i!==null&&(i.setCachedNodes(null),i.dirty=!0)))}};function $x(t,e,r){return new Cyt(t,e,r)}function Qgt(t,e){let r=e.__key,n=t.offset,o="element";if(Pr(e)){o="text";let i=e.getTextContentSize();n>i&&(n=i)}else if(!Ze(e)){let i=e.getNextSibling();if(Pr(i))r=i.__key,n=0,o="text";else{let a=e.getParent();a&&(r=a.__key,n=e.getIndexWithinParent()+1)}}t.set(r,n,o)}function s9r(t,e){if(Ze(e)){let r=e.getLastDescendant();Ze(r)||Pr(r)?Qgt(t,r):Qgt(t,e)}else Qgt(t,e)}var sLe=class t{constructor(e){this._cachedNodes=null,this._nodes=e,this.dirty=!1}getCachedNodes(){return this._cachedNodes}setCachedNodes(e){this._cachedNodes=e}is(e){if(!vLe(e))return!1;let r=this._nodes,n=e._nodes;return r.size===n.size&&Array.from(r).every(o=>n.has(o))}isCollapsed(){return!1}isBackward(){return!1}getStartEndPoints(){return null}add(e){this.dirty=!0,this._nodes.add(e),this._cachedNodes=null}delete(e){this.dirty=!0,this._nodes.delete(e),this._cachedNodes=null}clear(){this.dirty=!0,this._nodes.clear(),this._cachedNodes=null}has(e){return this._nodes.has(e)}clone(){return new t(new Set(this._nodes))}extract(){re
`),c=!f.isEmpty();else if(c=!1,Pr(f)){let p=f.getTextContent();f===r?f===n?o.type==="element"&&i.type==="element"&&i.offset!==o.offset||(p=s<u?p.slice(s,u):p.slice(u,s)):p=a?p.slice(s):p.slice(u):f===n&&(p=a?p.slice(0,u):p.slice(0,s)),l+=p}else!Lu(f)&&!YJ(f)||f===n&&this.isCollapsed()||(l+=f.getTextContent())}return l}applyDOMRange(e){let r=ec(),n=r.getEditorState()._selection,o=E7r(e.startContainer,e.startOffset,e.endContainer,e.endOffset,r,n);if(o===null)return;let[i,a]=o;this.anchor.set(i.key,i.offset,i.type,!0),this.focus.set(a.key,a.offset,a.type,!0),tLe(this)}clone(){let e=this.anchor,r=this.focus;return new t($x(e.key,e.offset,e.type),$x(r.key,r.offset,r.type),this.format,this.style)}toggleFormat(e){this.format=fLe(this.format,e,null),this.dirty=!0}setFormat(e){this.format=e,this.dirty=!0}setStyle(e){this.style=e,this.dirty=!0}hasFormat(e){let r=Ly[e];return!!(this.format&r)}insertRawText(e){let r=e.split(/(\r?\n|\t)/),n=[],o=r.length;for(let i=0;i<o;i++){let a=r[i];a===`
`||a===`\r
`?n.push(gZ()):a===" "?n.push(_Le()):n.push($h(a))}this.insertNodes(n)}insertText(e){let r=this.anchor,n=this.focus,o=this.format,i=this.style,a=r,s=n;!this.isCollapsed()&&n.isBefore(r)&&(a=n,s=r),a.type==="element"&&function(y,g,b,_){let w=y.getNode(),O=w.getChildAtIndex(y.offset),T=$h(),P=ev(w)?m$().append(T):T;T.setFormat(b),T.setStyle(_),O===null?w.append(P):O.insertBefore(P),y.is(g)&&g.set(T.__key,0,"text"),y.set(T.__key,0,"text")}(a,s,o,i),s.type==="element"&&TZ(s,Ax(oB(s,"next")));let u=a.offset,l=s.offset,c=this.getNodes(),d=c.length,f=c[0];Pr(f)||Qe(26);let p=f.getTextContent().length,m=f.getParentOrThrow(),h=c[d-1];if(d===1&&s.type==="element"&&(l=p,s.set(a.key,l,"text")),this.isCollapsed()&&u===p&&(c$(f)||!f.canInsertTextAfter()||!m.canInsertTextAfter()&&f.getNextSibling()===null)){let y=f.getNextSibling();if(Pr(y)&&y.canInsertTextBefore()&&!c$(y)||(y=$h(),y.setFormat(o),y.setStyle(i),m.canInsertTextAfter()?f.insertAfter(y):m.insertAfter(y)),y.select(0,0),f=y,e!=="")return void this.insertText(e)}else if(this.isCollapsed()&&u===0&&(c$(f)||!f.canInsertTextBefore()||!m.canInsertTextBefore()&&f.getPreviousSibling()===null)){let y=f.getPreviousSibling();if(Pr(y)&&!c$(y)||(y=$h(),y.setFormat(o),m.canInsertTextBefore()?f.insertBefore(y):m.insertBefore(y)),y.select(),f=y,e!=="")return void this.insertText(e)}else if(f.isSegmented()&&u!==p){let y=$h(f.getTextContent());y.setFormat(o),f.replace(y),f=y}else if(!this.isCollapsed()&&e!==""){let y=h.getParent();if(!m.canInsertTextBefore()||!m.canInsertTextAfter()||Ze(y)&&(!y.canInsertTextBefore()||!y.canInsertTextAfter()))return this.insertText(""),T7r(this.anchor,this.focus,null),void this.insertText(e)}if(d===1){if(ZU(f)){let _=$h(e);return _.select(),void f.replace(_)}let y=f.getFormat(),g=f.getStyle();if(u!==l||y===o&&g===i){if(Kyt(f)){let _=$h(e);return _.setFormat(o),_.setStyle(i),_.select(),void f.replace(_)}}else{if(f.getTextContent()!==""){let _=$h(e);if(_.setFormat(o),_.setStyle(i),_.select(),u===0)f.insertBefore(_,!1);else{let[w]=f.splitText(u);w.insertAfter(_,!1)}return void(_.isComposing()&&this.anchor.type==="text"&&(this.anchor.offset-=e.length))}f.setFormat(o),f.setStyle(i)}let b=l-u;f=f.spliceText(u,b,e,!0),f.getTextContent()===""?f.remove():this.anchor.type==="text"&&(f.isComposing()?this.anchor.offset-=e.length:(this.format=y,this.style=g))}else{let y=new Set([...f.getParentKeys(),...h.getParentKeys()]),g=Ze(f)?f:f.getParentOrThrow(),b=Ze(h)?h:h.getParentOrThrow(),_=h;if(!g.is(b)&&b.isInline())do _=b,b=b.getParentOrThrow();while(b.isInline());if(s.type==="text"&&(l!==0||h.getTextContent()==="")||s.type==="element"&&h.getIndexWithinParent()<l)if(Pr(h)&&!ZU(h)&&l!==h.getTextContentSize()){if(h.isSegmented()){let M=$h(h.getTextContent());h.replace(M),h=M}ev(s.getNode())||s.type!=="text"||(h=h.spliceText(0,l,"")),y.add(h.__key)}else{let M=h.getParentOrThrow();M.canBeEmpty()||M.getChildrenSize()!==1?h.remove():M.remove()}else y.add(h.__key);let w=b.getChildren(),O=new Set(c),T=g.is(b),P=g.isInline()&&f.getNextSibling()===null?g:f;for(let M=w.length-1;M>=0;M--){let I=w[M];if(I.is(f)||Ze(I)&&I.isParentOf(f))break;I.isAttached()&&(!O.has(I)||I.is(_)?T||P.insertAfter(I,!1):I.remove())}if(!T){let M=b,I=null;for(;M!==null;){let j=M.getChildren(),A=j.length;(A===0||j[A-1].is(I))&&(y.delete(M.__key),I=M),M=M.getParent()}}if(ZU(f))if(u===p)f.select();else{let M=$h(e);M.select(),f.replace(M)}else f=f.spliceText(u,p-u,e,!0),f.getTextContent()===""?f.remove():f.isComposing()&&this.anchor.type==="text"&&(this.anchor.offset-=e.length);for(let M=1;M<d;M++){let I=c[M],j=I.__key;y.has(j)||I.remove()}}}removeText(){let e=Ls()===this;sde(this,dXr(Ayt(this))),e&&Ls()!==this&&nv(this)}formatText(e,r=null){if(this.isCollapsed())return this.toggleFormat(e),void Fh(null);let n=this.getNodes(),o=[];for(let w of n)Pr(w)&&o.push(w);let i=w=>{n.forEach(O=>{if(Ze(O)){let T=O.getFormatFlags(e,w);O.setTextFormat(T)}})},a=o.length;if(a===0)return this.toggleFormat(e),Fh(null),void i(r);let s=this.anchor,u=this.focus,l=this.isBackward(),c=l?u:s,d=l?s:u,f=0,p=o[0],m=c.type==="element"?0:c.of
`);let u=s.length;if(!Gi(n)||o>=u){let l=n.getParent();n.remove(),l==null||l.getChildrenSize()!==0||RZ(l)||l.remove(),o-=u+a,n=i}else{let l=n.getKey(),c=t.getEditorState().read(()=>{let p=vXr(l);return Gi(p)&&p.isSimpleText()?p.getTextContent():null}),d=u-o,f=s.slice(0,d);if(c!==null&&c!==s){let p=xde(),m=n;if(n.isSimpleText())n.setTextContent(c);else{let h=Sw(c);n.replace(h),m=h}if(Rr(p)&&p.isCollapsed()){let h=p.anchor.offset;m.select(h,h)}}else if(n.isSimpleText()){let p=e.key===l,m=e.offset;m<o&&(m=u);let h=p?m-o:0,y=p?m:d;if(p&&h===0){let[g]=n.splitText(h,y);g.remove()}else{let[,g]=n.splitText(h,y);g.remove()}}else{let p=Sw(f);n.replace(p)}o=0}}}function ifi(t){let e=t.getStyle(),r=aYr(e);sFe.set(e,r)}function Hbt(t,e){(Rr(t)?t.isCollapsed():Gi(t)||fi(t))||Kbt(280);let r=uFe(Rr(t)?t.style:Gi(t)?t.getStyle():t.getTextStyle()),n=Object.entries(e).reduce((i,[a,s])=>(typeof s=="function"?i[a]=s(r[a],t):s===null?delete i[a]:i[a]=s,i),{...r}),o=sYr(n);Rr(t)||Gi(t)?t.setStyle(o):t.setTextStyle(o),sFe.set(o,n)}function afi(t,e){if(Rr(t)&&t.isCollapsed()){Hbt(t,e);let r=t.anchor.getNode();fi(r)&&r.isEmpty()&&Hbt(r,e)}lYr(r=>{Hbt(r,e)})}function lYr(t){let e=hn();if(!e)return;let r=new Map;if(Rr(e))for(let i of mXr(e).getTextSlices())i&&r.set(i.caret.origin.getKey(),i.getSliceIndices());let n=e.getNodes();for(let i of n){if(!Gi(i)||!i.canHaveFormat())continue;let[a,s]=(o=i,r.get(o.getKey())||[0,o.getTextContentSize()]);s!==a&&(Sbt(i)||a===0&&s===i.getTextContentSize()?t(i):t(i.splitText(a,s)[a===0?0:1]))}var o;Rr(e)&&e.anchor.type==="text"&&e.focus.type==="text"&&e.anchor.key===e.focus.key&&cYr(e)}function cYr(t){if(t.isBackward()){let{anchor:e,focus:r}=t,{key:n,offset:o,type:i}=e;e.set(r.key,r.offset,r.type),r.set(n,o,i)}}function dYr(t,e){let r=t.getFormatType(),n=t.getIndent();r!==e.getFormatType()&&e.setFormat(r),n!==e.getIndent()&&e.setIndent(n)}function sfi(t,e,r=dYr){if(t===null)return;let n=t.getStartEndPoints(),o=new Map,i=null;if(n){let[a,s]=n;i=ELe(),i.anchor.set(a.key,a.offset,a.type),i.focus.set(s.key,s.offset,s.type);let u=Wbt(a.getNode(),Pde),l=Wbt(s.getNode(),Pde);fi(u)&&o.set(u.getKey(),u),fi(l)&&o.set(l.getKey(),l)}for(let a of t.getNodes())if(fi(a)&&Pde(a))o.set(a.getKey(),a);else if(n===null){let s=Wbt(a,Pde);fi(s)&&o.set(s.getKey(),s)}for(let[a,s]of o){let u=e();r(s,u),s.replace(u,!0),i&&(a===i.anchor.key&&i.anchor.set(u.getKey(),i.anchor.offset,i.anchor.type),a===i.focus.key&&i.focus.set(u.getKey(),i.focus.offset,i.focus.type))}i&&t.is(hn())&&u3(i)}function iYr(t){return t.getNode().isAttached()}function ufi(t){let e=t;for(;e!==null&&!s3(e);){let r=e.getLatest(),n=e.getParent();r.getChildrenSize()===0&&e.remove(!0),e=n}}function lfi(t,e,r=null){let n=t.getStartEndPoints(),o=n?n[0]:null,i=t.getNodes(),a=i.length;if(o!==null&&(a===0||a===1&&o.type==="element"&&o.getNode().getChildrenSize()===0)){let l=o.type==="text"?o.getNode().getParentOrThrow():o.getNode(),c=l.getChildren(),d=e();return d.setFormat(l.getFormatType()),d.setIndent(l.getIndent()),c.forEach(f=>d.append(f)),r&&(d=r.append(d)),void l.replace(d)}let s=null,u=[];for(let l=0;l<a;l++){let c=i[l];s3(c)?(Jbt(t,u,u.length,e,r),u=[],s=c):s===null||s!==null&&SXr(c,s)?u.push(c):(Jbt(t,u,u.length,e,r),u=[c])}Jbt(t,u,u.length,e,r)}function Jbt(t,e,r,n,o=null){if(e.length===0)return;let i=e[0],a=new Map,s=[],u=fi(i)?i:i.getParentOrThrow();u.isInline()&&(u=u.getParentOrThrow());let l=!1;for(;u!==null;){let m=u.getPreviousSibling();if(m!==null){u=m,l=!0;break}if(u=u.getParentOrThrow(),s3(u))break}let c=new Set;for(let m=0;m<r;m++){let h=e[m];fi(h)&&h.getChildrenSize()===0&&c.add(h.getKey())}let d=new Set;for(let m=0;m<r;m++){let h=e[m],y=h.getParent();if(y!==null&&y.isInline()&&(y=y.getParent()),y!==null&&xXr(h)&&!d.has(h.getKey())){let g=y.getKey();if(a.get(g)===void 0){let b=n();b.setFormat(y.getFormatType()),b.setIndent(y.getIndent()),s.push(b),a.set(g,b),y.getChildren().forEach(_=>{b.append(_),d.add(_.getKey()),fi(_)&&_.getChildrenKeys().forEach(w=>d.add(w))}),ufi(y)}}else if(c.has(h.getKey())){fi(h)||Kbt(179);let g=n();g.setFormat(h.getFormatType()),g
`||c===`\r
`?l.insertParagraph():c===" "?l.insertNodes([hXr()]):l.insertText(c)}}}else e.insertRawText(a)}function a_t(t,e,r){t.dispatchCommand(nZr,{nodes:e,selection:r})||(r.insertNodes(e),function(n){if(Rr(n)&&n.isCollapsed()){let o=n.anchor,i=null,a=IZ(o,"previous");if(a)if(RLe(a))i=a.origin;else{let s=yXr(a,uB(Ri(),"next").getFlipped());for(let u of s){if(Gi(u.origin)){i=u.origin;break}if(fi(u.origin)&&!u.origin.isInline())break}}if(i&&Gi(i)){let s=i.getFormat(),u=i.getStyle();n.format===s&&n.style===u||(n.format=s,n.style=u,n.dirty=!0)}}}(r))}function VYr(t,e,r,n=[]){let o=e===null||r.isSelected(e),i=fi(r)&&r.excludeFromCopy("html"),a=r;if(e!==null){let l=sB(r);l=Gi(l)&&e!==null?lFe(e,l):l,a=l}let s=fi(a)?a.getChildren():[],u=function(l){let c=l.exportJSON(),d=l.constructor;if(c.type!==d.getType()&&dFe(58,d.name),fi(l)){let f=c.children;Array.isArray(f)||dFe(59,d.name)}return c}(a);if(Gi(a)){let l=a.__text;l.length>0?u.text=l:o=!1}for(let l=0;l<s.length;l++){let c=s[l],d=VYr(t,e,c,u.children);!o&&fi(r)&&d&&r.extractWithChild(c,e,"clone")&&(o=!0)}if(o&&!i)n.push(u);else if(Array.isArray(u.children))for(let l=0;l<u.children.length;l++){let c=u.children[l];n.push(c)}return o}function HYr(t,e){let r=[],n=Ri().getChildren();for(let o=0;o<n.length;o++)VYr(t,e,n[o],r);return{namespace:t._config.namespace,nodes:r}}function JYr(t){let e=[];for(let r=0;r<t.length;r++){let n=t[r],o=PXr(n);Gi(o)&&mYr(o),e.push(o)}return e}var BZ=null;async function cpi(t,e,r){if(BZ!==null)return!1;if(e!==null)return new Promise((l,c)=>{t.update(()=>{l(UYr(t,e,r))})});let n=t.getRootElement(),o=t._window||window,i=window.document,a=Obt(o);if(n===null||a===null)return!1;let s=i.createElement("span");s.style.cssText="position: fixed; top: -1000px;",s.append(i.createTextNode("#")),n.append(s);let u=new Range;return u.setStart(s,0),u.setEnd(s,1),a.removeAllRanges(),a.addRange(u),new Promise((l,c)=>{let d=t.registerCommand(jLe,f=>(Bde(f,ClipboardEvent)&&(d(),BZ!==null&&(window.clearTimeout(BZ),BZ=null),l(UYr(t,f,r))),!0),NLe);BZ=window.setTimeout(()=>{d(),BZ=null,l(!1)},50),i.execCommand("copy"),s.remove()})}function UYr(t,e,r){if(r===void 0){let o=Obt(t._window);if(!o)return!1;let i=o.anchorNode,a=o.focusNode;if(i!==null&&a!==null&&!fZr(t,i,a))return!1;let s=hn();if(s===null)return!1;r=WYr(s)}e.preventDefault();let n=e.clipboardData;return n!==null&&(KYr(n,r),!0)}var dpi=[["text/html",BYr],["application/x-lexical-editor",zYr]];function WYr(t=hn()){let e={"text/plain":t?t.getTextContent():""};if(t){let r=PLe();for(let[n,o]of dpi){let i=o(r,t);i!==null&&(e[n]=i)}}return e}function KYr(t,e){for(let r in e){let n=e[r];n!==void 0&&t.setData(r,n)}}var AA=s_t,v$s=AA.$generateJSONFromSelectedNodes,w$s=AA.$generateNodesFromSerializedNodes,S$s=AA.$getClipboardDataFromSelection,GYr=AA.$getHtmlContent,C$s=AA.$getLexicalContent,u_t=AA.$insertDataTransferForPlainText,x$s=AA.$insertDataTransferForRichText,O$s=AA.$insertGeneratedNodes,T$s=AA.copyToClipboard,E$s=AA.setLexicalClipboardDataTransfer;var l_t={};Rn(l_t,{registerPlainText:()=>ypi});var zZ=typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0,fpi=zZ&&"documentMode"in document?document.documentMode:null,ppi=!(!zZ||!("InputEvent"in window)||fpi)&&"getTargetRanges"in new window.InputEvent("input"),mpi=zZ&&/Version\/[\d.]+.*Safari/.test(navigator.userAgent),XYr=zZ&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,hpi=zZ&&/^(?=.*Chrome).*/i.test(navigator.userAgent),gpi=zZ&&/AppleWebKit\/[\d.]+/.test(navigator.userAgent)&&!hpi;function ZYr(t,e){e.update(()=>{if(t!==null){let r=Bde(t,KeyboardEvent)?null:t.clipboardData,n=hn();if(n!==null&&r!=null){t.preventDefault();let o=GYr(e);o!==null&&r.setData("text/html",o),r.setData("text/plain",n.getTextContent())}}})}function ypi(t){return S$(t.registerCommand(AZ,e=>{let r=hn();return!!Rr(r)&&(r.deleteCharacter(e),!0)},Zu),t.registerCommand(UXr,e=>{let r=hn();return!!Rr(r)&&(r.deleteWord(e),!0)},Zu),t.registerCommand(qXr,e=>{let r=hn();return!!Rr(r)&&(r.deleteLine(e),!0)},Zu),t.registerCommand(FXr,e=>{let r=hn();if(!Rr(r))return!1;if(ty
`)};function KQr({onWebTabsChange:t,onWebTabsRemoved:e,onActiveWebTabAdded:r,onActiveWebTabRemoved:n}){return hB.default.createElement(hB.default.Fragment,null,hB.default.createElement(Vx,{config:rmi,onChange:t,onRemoved:e}),(r||n)&&hB.default.createElement(nmi,{onActiveWebTabAdded:r,onActiveWebTabRemoved:n}))}function nmi({onActiveWebTabAdded:t,onActiveWebTabRemoved:e}){let r={isPillNode:Lbt,extractData:()=>!0,getKey:()=>"active-web-tab"},n=hB.default.useCallback(i=>{i.length>0&&t&&t()},[t]),o=hB.default.useCallback(i=>{i.length>0&&e&&e()},[e]);return hB.default.createElement(Vx,{config:r,onChange:n,onRemoved:o})}var GQr=L(X());function XQr({enableURLPills:t=!1,onImagePaste:e}){let[r]=Ai();return GQr.default.useEffect(()=>r.registerCommand(LLe,n=>{let o=n.clipboardData;if(!o)return!1;if(e){let p=o.items;if(p){let m=Array.from(p).filter(h=>h.type.indexOf("image")!==-1);if(m.length>0)return n.preventDefault(),Promise.all(m.map(h=>h.getAsFile())).then(h=>{let y=h.filter(g=>g!==null);y.length>0&&e(y)}),!0}}let i=o.getData("text/plain"),a=i.includes("[["),s=t&&i.includes("http"),u=i.includes("@"),l=i.includes("#"),c=i.includes("{")&&i.includes("}");if(!i||!a&&!s&&!u&&!l&&!c)return!1;let d=bFe(i,{includeNotes:!0,includeURLs:t,includeTools:!0,includeCustomTemplates:!0});return d.some(p=>p.type==="note-pill"||p.type==="active-note-pill"||t&&p.type==="url-pill"||p.type==="tool-pill"||p.type==="folder-pill")?(n.preventDefault(),r.update(()=>{let p=hn();if(!Rr(p))return;let m=_Fe(d);m.length>0&&p.insertNodes(m)}),!0):!1},w$),[r,t,e]),null}var ZQr=L(X());function YQr(){let[t]=Ai();return ZQr.default.useEffect(()=>t.registerCommand(yFe,e=>{let{text:r,options:n={}}=e;return t.update(()=>{_Qr(r,n)}),!0},Zu),[t]),null}var iv=L(X());var QQr=(0,iv.createContext)(void 0);function gB(){let t=(0,iv.useContext)(QQr);if(t===void 0)throw new Error("useChatInput must be used within a ChatInputProvider");return t}function een({children:t}){let[e,r]=(0,iv.useState)(null),[n,o]=(0,iv.useState)(null),i=(0,iv.useCallback)(c=>{r(c)},[]),a=(0,iv.useCallback)(c=>{o(()=>c)},[]),s=(0,iv.useCallback)((c,d=!1)=>{e&&e.dispatchCommand(yFe,{text:c,options:{enableURLPills:d,insertAtSelection:!0}})},[e]),u=(0,iv.useCallback)(()=>{n&&n()},[n]),l={insertTextWithPills:s,focusInput:u,registerEditor:i,registerFocusHandler:a};return iv.default.createElement(QQr.Provider,{value:l},t)}kn();_t();Bc();ot();var omi=({value:t,onChange:e,onSubmit:r,placeholder:n="Type a message...",disabled:o=!1,className:i="",onNotesChange:a,onNotesRemoved:s,onURLsChange:u,onURLsRemoved:l,onToolsChange:c,onToolsRemoved:d,onFoldersChange:f,onFoldersRemoved:p,onActiveNoteAdded:m,onActiveNoteRemoved:h,onWebTabsChange:y,onWebTabsRemoved:g,onActiveWebTabAdded:b,onActiveWebTabRemoved:_,onEditorReady:w,onImagePaste:O,onTagSelected:T,isCopilotPlus:P=!1,currentActiveFile:M=null,currentChain:I})=>{let[j,A]=Xi.default.useState(null),[k,V]=Xi.default.useState(null),q=gB(),J=zr(),K=Xi.default.useCallback(Y=>{A(()=>Y)},[]);(0,Xi.useEffect)(()=>{k&&q.registerEditor(k)},[k,q]),(0,Xi.useEffect)(()=>{j&&q.registerFocusHandler(j)},[j,q]);let ue=Xi.default.useMemo(()=>({namespace:"ChatEditor",theme:{root:"tw-outline-none",paragraph:"tw-m-0"},nodes:[LZ,kZ,p3,f3,h3,qZ,...u?[d3]:[]],onError:Y=>{ne("Lexical error:",Y)},editable:!o}),[u,o]),oe=(0,Xi.useCallback)(Y=>{Y.read(()=>{let ie=Ri().getTextContent();e(ie)})},[e]),G=(0,Xi.useCallback)(Y=>{V(Y),w?.(Y)},[w]);return Xi.default.createElement(QZr,{initialConfig:ue},Xi.default.createElement($Zr,{currentActiveFile:M},Xi.default.createElement("div",{className:Te("tw-relative",i)},Xi.default.createElement(eQr,{contentEditable:Xi.default.createElement(iQr,{className:"tw-max-h-40 tw-min-h-[60px] tw-w-full tw-resize-none tw-overflow-y-auto tw-rounded-md tw-border-none tw-bg-transparent tw-px-2 tw-text-sm tw-text-normal tw-outline-none focus-visible:tw-ring-0","aria-label":"Chat input"}),placeholder:Xi.default.createElement("div",{className:"tw-pointer-events-none tw-absolute tw-left-2 tw-top-0 tw-select-none tw-text-sm tw-text-muted/60"},n),ErrorBoundary:mQr}),Xi.defau
\u2026 (truncated ${(r.length-Vde).toLocaleString()} characters for display)`:r}catch{return e.length>Vde?`Tool '${t}' returned ${e.length.toLocaleString()} characters. The full output is preserved in chat history but omitted here to keep the UI responsive.`:e}},wen=({toolName:t,displayName:e,emoji:r,isExecuting:n,result:o,confirmationMessage:i,onAccept:a,onReject:s})=>{let[u,l]=(0,Yu.useState)(!1),c=(0,Yu.useMemo)(()=>_mi(t,o),[t,o]),d=n&&!o,f=!d&&c!==null;return Yu.default.createElement(kb,{open:f?u:!1,onOpenChange:l,disabled:!f,"aria-disabled":!f,className:"tw-my-3 tw-w-full sm:tw-max-w-sm"},Yu.default.createElement("div",{className:Te("tw-rounded-md tw-border tw-border-border tw-bg-secondary/50",d&&"tw-relative tw-overflow-hidden")},d&&Yu.default.createElement("div",{className:"tw-absolute tw-inset-0 tw-z-[1] tw-overflow-hidden"},Yu.default.createElement("div",{className:"tw-absolute tw-inset-0 -tw-translate-x-full",style:{background:"linear-gradient(90deg, transparent 0%, rgba(255, 255, 255, 0.3) 50%, transparent 100%)",animation:bmi}})),Yu.default.createElement(O$,{className:Te("tw-flex tw-w-full tw-items-center tw-justify-between tw-px-3 tw-py-2.5 tw-text-sm sm:tw-px-4 sm:tw-py-3",f&&"hover:tw-bg-secondary/70",!f&&"tw-cursor-default")},Yu.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Yu.default.createElement("span",{className:"tw-text-base"},r),Yu.default.createElement("span",{className:"tw-font-medium"},t==="readNote"?`${d?"Reading":"Read"} ${e}`:`${d?"Calling":"Called"} ${e}`,d&&t!=="readNote"&&"..."),d&&i&&Yu.default.createElement("span",{className:"tw-text-xs tw-text-muted"},"\u2022 ",i,"...")),Yu.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},!d&&a&&s&&Yu.default.createElement(Yu.default.Fragment,null,Yu.default.createElement("button",{onClick:p=>{p.stopPropagation(),a()},className:"hover:tw-bg-green-rgb/20 tw-rounded tw-p-1",title:"Accept"},Yu.default.createElement(Hu,{className:"tw-size-4 tw-text-success"})),Yu.default.createElement("button",{onClick:p=>{p.stopPropagation(),s()},className:"hover:tw-bg-red-rgb/20 tw-rounded tw-p-1",title:"Reject"},Yu.default.createElement($o,{className:"tw-size-4 tw-text-error"}))),f&&Yu.default.createElement(bm,{className:Te("tw-size-4 tw-text-muted tw-transition-transform",u&&"tw-rotate-90")}))),Yu.default.createElement(qb,null,Yu.default.createElement("div",{className:"tw-border-t tw-border-border tw-px-3 tw-py-2.5 sm:tw-px-4 sm:tw-py-3"},Yu.default.createElement("div",{className:"tw-text-sm tw-text-muted"},Yu.default.createElement("pre",{className:"tw-overflow-x-auto tw-whitespace-pre-wrap tw-font-mono tw-text-xs"},c??"No result available"))))))};_t();var Sen=60*60*1e3,KZ=()=>(window.__copilotToolCallRoots||(window.__copilotToolCallRoots=new Map),window.__copilotToolCallRoots),GZ=()=>(window.__copilotErrorBlocks||(window.__copilotErrorBlocks=new Map),window.__copilotErrorBlocks),$_t=(t,e,r)=>{if(e.size>0)return;r.get(t)===e&&r.delete(t)},L_t=(t,e,r,n,o,i)=>{try{n.root.unmount()}catch(a){Be(`Error unmounting tool call root during ${o}`,r,a)}n.isUnmounting=!1,e.get(r)===n&&e.delete(r),$_t(t,e,i)},Cen=(t,e,r,n,o,i)=>{e.delete(r),n.isUnmounting=!0,setTimeout(()=>{try{n.root.unmount()}catch(a){Be(`Error unmounting tool call root during ${o}`,r,a)}n.isUnmounting=!1,$_t(t,e,i)},0)},yB=(t,e,r,n,o,i)=>{n.isUnmounting||(n.isUnmounting=!0,setTimeout(()=>{let a=i.get(t),s=a?.get(r);if(!a||s!==n){n.isUnmounting=!1,$_t(t,e,i);return}L_t(t,a,r,s,o,i)},0))},xen=(t,e,r,n,o)=>{let i=e.get(r);return i?.isUnmounting&&(L_t(t,e,r,i,`${o} (finalizing stale root)`,KZ()),i=void 0),i&&i.container&&i.container!==n&&(Cen(t,e,r,i,`${o} (container changed)`,KZ()),i=void 0),i||(i={root:(0,D_t.createRoot)(n),isUnmounting:!1,container:n},e.set(r,i)),i},Oen=(t,e,r,n,o)=>{let i=e.get(r);return i?.isUnmounting&&(L_t(t,e,r,i,`${o} (finalizing stale error root)`,GZ()),i=void 0),i&&i.container&&i.container!==n&&(Cen(t,e,r,i,`${o} (container changed)`,GZ()),i=void 0),i||(i={root:(0,D_t.createRoot)(n),isUnmounting:!1,container:n},e.set(r,i)),i},Ten=(t,e)
<summary style="${Je}">${ce}</summary>
<div class="tw-text-muted" style="${tt}">${st.trim()}</div>
</details>
`});let Ne=new RegExp(`<${ee}>([\\s\\S]*)$`);return U=U.replace(Ne,(Tr,st)=>`<div style="${Oe}">
<div style="${Je}">${ve}</div>
<div class="tw-text-muted" style="${tt}">${st.trim()}</div>
</div>`),U}let Pt=new RegExp(`<${ee}>([\\s\\S]*?)<\\/${ee}>`,"g");return U.replace(Pt,(Nt,Ne)=>{let Tr=`${ee}-${dt}`;dt+=1;let st=F_t(p.current,Tr),Le=g.get(st)?" open":"";return`<details id="${st}"${Le} style="${Oe}">
<summary style="${Je}">${ce}</summary>
<div class="tw-text-muted" style="${tt}">${Ne.trim()}</div>
</details>
`})},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;return Oe.replace(Je,(tt,Ke)=>Ke.trim())},ve=ee(U);return ve=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)=>{let dt=e.metadataCache.getFirstLinkpathDest(Ke,V);return dt?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=>`![](${e.vault.getResourcePath(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)return U;let ee=/!\[([^\]]*)\]\(([^)]+)\)/g;return U.replace(ee,(ce,ve,Oe)=>{let Je=sHe(Oe);if(!Je)return ce;let tt=ve||"YouTube Video",Ke=`https://i.ytimg.com/vi/${Je}/hqdefault.jpg`;return`[![${tt}](${Ke})](${Oe})`})})(R)},[e,r,b.enableInlineCitations,g]);(0,ur.useEffect)(()=>{let A=c.current;if(!A||t.sender===Ws||!r)return;let k=J=>{if(J instanceof PointerEvent&&(J.button!==0||!J.isPrimary))return;let K=IFe(J,A);if(!K||!k_t(J,K))return;let ue=!K.open;K.open=ue,g.set(K.id,ue)},V=J=>{let K=IFe(J,A);!K||!k_t(J,K)||J.preventDefault()},q=J=>{let K=IFe(J,A);K&&g.set(K.id,K.open)};return A.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});let A=t.message,k=w(A),V=Hot(k,p.current);if(!f.current){let q=new Set,J=new Set;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());let G=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++}else if(ie.type==="toolCall"&&ie.toolCall){let $=ie.toolCall.id,H=document.getElementById(`tool-call-${$}`);if(!H){let D=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}let re=xen(p.current,m.current,$,H,"render refresh");!f.current&&!re.isUnmounting&&Ten(re,ie.toolCall),G++}else if(ie.type==="error"&&ie.error){let $=ie.error.id,H=document.getElementById(`error-block-${$}`);if(!H){let D=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}let re=Oen(p.current,h.current,$,H,"error render");!f.current&&!re.isUnmounting&&Een(re,ie.error),G++}});let Y=new Set(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())}});let se=new Set(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)(()=>{let A=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(`
`).map(b=>{if(!b.trim())return b;try{let _=new URL(b.trim());return _.hostname.includes("youtube.com")||_.hostname.includes("youtu.be"),b}catch{return b}});p("contextSource.youtubeUrls",g.join(`
`))},placeholder:"Enter YouTube URLs, one per line",className:"tw-min-h-20 tw-w-full"})))),gn.default.createElement("div",{className:"tw-mt-4 tw-flex tw-items-center tw-justify-end tw-gap-2"},gn.default.createElement(ge,{variant:"ghost",onClick:r,disabled:o},"Cancel"),gn.default.createElement(ge,{onClick:m,disabled:o||!f()},o?"Saving...":"Save")))}var tfe=class extends efe.Modal{constructor(r,n,o){super(r);this.onSave=n;this.initialProject=o}onOpen(){let{contentEl:r}=this;this.root=(0,Itn.createRoot)(r);let n=async i=>{await this.onSave(i),this.close()},o=()=>{this.close()};this.root.render(gn.default.createElement(whi,{initialProject:this.initialProject,onSave:n,onCancel:o}))}onClose(){this.root.unmount()}};to();kn();_t();ot();lN();Jr();var Atn=require("obsidian"),et=L(X());function Shi(t,e,r={}){let{caseSensitive:n=!1,searchInName:o=!0,searchInDescription:i=!0}=r;if(!e.trim())return!0;let a=n?e:e.toLowerCase();return!!(o&&(n?t.name:t.name.toLowerCase()).includes(a)||i&&t.description&&(n?t.description:t.description.toLowerCase()).includes(a))}function Rtn(t,e,r={}){return!t||t.length===0?[]:e.trim()?t.filter(n=>Shi(n,e,r)):t}function Chi(t){let[e,r]=(0,et.useState)(()=>t?.getRevision()??0);return(0,et.useEffect)(()=>{if(!t){r(0);return}return r(t.getRevision()),t.subscribe(()=>{r(t.getRevision())})},[t]),e}function xhi({project:t,loadContext:e,onEdit:r,onDelete:n}){return et.default.createElement("div",{className:"tw-group tw-flex tw-cursor-pointer tw-items-center tw-justify-between tw-gap-2 tw-rounded-lg tw-border tw-border-solid tw-border-border tw-p-3 tw-transition-all tw-duration-200 tw-bg-secondary/40 hover:tw-border-interactive-accent hover:tw-text-accent hover:tw-shadow-[0_2px_12px_rgba(0,0,0,0.1)] active:tw-scale-[0.98]",onClick:()=>e(t)},et.default.createElement("div",{className:"tw-flex tw-flex-1 tw-items-center tw-gap-2 tw-overflow-hidden"},et.default.createElement("div",{className:"tw-text-accent"},et.default.createElement(ah,{className:"tw-size-4"})),et.default.createElement("div",{className:"tw-flex tw-flex-1 tw-flex-col tw-gap-1.5 tw-overflow-hidden"},et.default.createElement("span",{className:"tw-w-full tw-truncate tw-text-[13px] tw-font-medium tw-text-normal"},t.name),t.description&&et.default.createElement("span",{className:"tw-w-full tw-truncate tw-text-[12px] tw-text-muted/80"},t.description))),et.default.createElement("div",{className:"tw-flex tw-flex-row tw-items-center tw-gap-1 tw-opacity-100 tw-transition-opacity tw-duration-200"},et.default.createElement(pn,null,et.default.createElement(mn,{asChild:!0},et.default.createElement(ge,{variant:"ghost2",size:"icon",onClick:o=>{o.stopPropagation(),r(t)}},et.default.createElement(pb,{className:"tw-size-4"}))),et.default.createElement(sn,{side:"bottom"},"Edit Project")),et.default.createElement(pn,null,et.default.createElement(mn,{asChild:!0},et.default.createElement(ge,{variant:"ghost2",size:"icon",onClick:o=>{o.stopPropagation(),e(t)}},et.default.createElement(k6,{className:"tw-size-4"}))),et.default.createElement(sn,{side:"bottom"},"Start Chat")),et.default.createElement(pn,null,et.default.createElement(mn,{asChild:!0},et.default.createElement(ge,{variant:"ghost2",size:"icon",onClick:o=>{o.stopPropagation(),new vl(app,()=>n(t),`Are you sure you want to delete project "${t.name}"?`,"Delete Project").open()}},et.default.createElement(ly,{className:"tw-size-4"}))),et.default.createElement(sn,{side:"bottom"},"Delete Project"))))}var uvt=(0,et.memo)(({className:t,projects:e,defaultOpen:r=!1,app:n,plugin:o,onProjectAdded:i,onEditProject:a,hasMessages:s=!1,showChatUI:u,onClose:l,onProjectClose:c})=>{let[d,f]=(0,et.useState)(r),[p,m]=(0,et.useState)(!1),[h,y]=(0,et.useState)(null),[g,b]=(0,et.useState)(""),_=gB(),w=zr(),O=o?.projectManager?.getProjectUsageTimestampsManager?.(),T=Chi(O);(0,et.useEffect)(()=>{s&&f(!1)},[s]);let P=(0,et.useMemo)(()=>mO(e,w.projectListSortStrategy,{getName:q=>q.name,getCreatedAtMs:q=>q.created,getLastUsedAtMs:q=>O?O.getEffectiveLastUsedAt(q.id,q.UsageTimestamps):q.UsageTimestamps}),[e,w.projectListSortStrategy,O,T]),M=(0,et.useM
- a positive number
- less than the value passed to \`max\` (or ${fvt} if no \`max\` prop is set)
- \`null\` or \`undefined\` if the progress is indeterminate.
Defaulting to \`null\`.`}var pvt=ktn,ztn=Utn;kn();var mvt=rfe.forwardRef(({className:t,value:e,...r},n)=>rfe.createElement(pvt,{ref:n,className:Te("tw-relative tw-h-2 tw-w-full tw-overflow-hidden tw-rounded-full tw-bg-interactive-accent/20 tw-border-interactive-accent/30",t),...r},rfe.createElement(ztn,{className:"tw-size-full tw-flex-1 tw-bg-interactive-accent tw-transition-all",style:{transform:`translateX(-${100-Math.min(Math.max(e||0,0),100)}%)`}})));mvt.displayName=pvt.displayName;Jr();qs();to();_t();function gvt({plugin:t,setHiddenCard:e,onEditContext:r}){let[n]=r6(),o=n.total,i=n.success,a=n.failed,s=n.processingFiles,[u,l]=(0,hvt.useState)(!1),[c,d]=(0,hvt.useState)(!1),f=i.length+a.length,p=o.length>0?Math.round(f/o.length*100):0,m=y=>y.path,h=async y=>{if(!t?.projectManager){ne("ProjectManager not available");return}try{await t.projectManager.retryFailedItem(y)}catch(g){ne(`Error retrying failed item: ${g}`)}};return _n.createElement(v3,{className:"tw-w-full tw-border tw-border-solid tw-border-border tw-bg-transparent tw-shadow-none"},_n.createElement(w3,null,_n.createElement(Jde,{className:"tw-flex tw-items-center tw-justify-between tw-gap-2"},_n.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},_n.createElement(Ju,{className:"tw-size-5"}),"Context Loading",_n.createElement(ge,{size:"sm",variant:"ghost2",className:"tw-size-6 tw-p-0 tw-text-muted",title:"Edit Context",onClick:()=>r?.()},_n.createElement(bm,{className:"tw-size-4"}),_n.createElement("span",{className:"tw-sr-only"},"Edit Context"))),_n.createElement("div",{className:"tw-flex tw-items-center tw-gap-2 tw-rounded tw-p-1"},_n.createElement(ge,{size:"sm",variant:"ghost2",className:"tw-size-6 tw-p-0 tw-text-muted",title:"Close Progress Bar",onClick:()=>e(!0)},_n.createElement($o,{className:"tw-size-4"}))))),_n.createElement(S3,{className:"tw-space-y-6"},_n.createElement("div",{className:"tw-space-y-2"},_n.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-text-sm"},_n.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},_n.createElement("span",{className:"tw-text-muted"},"Total progress"),_n.createElement("span",{className:"tw-text-xs tw-text-muted"},"(Success:"," ",_n.createElement("span",{className:"tw-font-medium tw-text-success"},i.length),", Failed: ",_n.createElement("span",{className:"tw-font-medium tw-text-error"},a.length),")")),_n.createElement("span",{className:"tw-font-medium"},f,"/",o.length," (",p,"%)")),_n.createElement(mvt,{value:p,className:"tw-h-2"})),s.length>0&&_n.createElement("div",{className:"tw-space-y-3"},_n.createElement("div",{className:"tw--m-1 tw-flex tw-cursor-pointer tw-items-center tw-gap-2 tw-rounded-md tw-p-1 tw-transition-colors hover:tw-bg-muted/10",onClick:()=>l(!u)},_n.createElement(du,{className:"tw-size-4 tw-animate-spin tw-text-accent"}),_n.createElement("span",{className:"tw-text-sm tw-font-medium"},"Processing"),u?_n.createElement(ts,{className:"tw-ml-auto tw-size-4"}):_n.createElement(bm,{className:"tw-ml-auto tw-size-4"})),u&&_n.createElement("div",{className:"tw-max-h-32 tw-space-y-2 tw-overflow-y-auto"},s.map((y,g)=>_n.createElement("div",{key:g,className:"tw-flex tw-items-center tw-gap-2 tw-rounded-md tw-p-2 tw-text-sm tw-bg-faint/10"},_n.createElement("div",{className:"tw-size-2 tw-animate-pulse tw-rounded-full tw-bg-interactive-accent"}),_n.createElement(tc,{className:"tw-flex-1",title:y},y))))),a.length>0&&_n.createElement("div",{className:"tw-space-y-3"},_n.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},_n.createElement("div",{className:"-tw-m-1 tw-flex tw-flex-1 tw-cursor-pointer tw-items-center tw-gap-2 tw-rounded-md tw-p-1 tw-transition-colors hover:tw-bg-muted/10",onClick:()=>d(!c)},_n.createElement(sS,{className:"tw-size-4 tw-text-error"}),_n.createElement("span",{className:"tw-text-sm tw-font-medium"},"Failed"),_n.createElement(Bh,{variant:"destructive",className:"tw-text-xs"},a.length," files"),c?_n.createElement(ts,{className:"tw-ml-auto tw-size-4"}):_n.createElement(bm,{className:"tw-ml-auto tw-size-4"}))),c&&_n.cre
`).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(`Unsupported file type: ${w.extension}. Supported types: md, pdf, canvas, and images.`)}else if(y.length>0){let g=[];for(let b of y){let _=b.getAsFile();_&&_.type.startsWith("image/")&&g.push(_)}g.length>0&&i(g)}};return l.addEventListener("dragover",c),l.addEventListener("dragleave",d),l.addEventListener("drop",f),()=>{l.removeEventListener("dragover",c),l.removeEventListener("dragleave",d),l.removeEventListener("drop",f)}},[e,r,o,i,n,a]),{isDragActive:s}}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
`));let Ge={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);let Ee=await i.sendMessage(Ft,Ge,f,ee,ce,rl.length>0?rl:void 0,R.setLoadingMessage);h&&r(h),s.autosaveChat&&rt();let yr=i.getLLMMessage(Ee);yr&&await yvt(yr,t,O,R.setCurrentAiMessage,T,{debug:s.debug,updateLoadingMessage:R.setLoadingMessage}),s.autosaveChat&&rt()}catch(rl){ne("Error sending message:",rl),new Sl.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{await i.saveChat(d)}catch(pt){ne("Error saving chat as note:",Sn(pt)),new Sl.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")}),[]);let We=(0,lr.useCallback)(async pt=>{if(pt<=0){new Sl.Notice("Cannot regenerate the first message.");return}let Br=l[pt];if(!Br){new Sl.Notice("Message not found.");return}R.setCurrentAiMessage(""),w.current=`msg-${Zm()}`,R.setLoading(!0);try{await i.regenerateMessage(Br.id,R.setCurrentAiMessage,O)?s.debug&&console.log("Message regenerated successfully"):new Sl.Notice("Failed to regenerate message. Please try again."),s.autosaveChat&&rt()}catch(Ti){ne("Error regenerating message:",Ti),new Sl.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)=>{let Ti=l[pt];if(!(!Ti||Ti.message===Br))try{if(!await i.editMessage(Ti.id,Br,f,ee)){new Sl.Notice("Failed to edit message. Please try again.");return}if(Ti.sender===Ws){let tu=pt<l.length-1;if(await i.truncateAfterMessageId(Ti.id),tu){w.current=`msg-${Zm()}`,R.setLoading(!0);try{let Pi=i.getLLMMessage(Ti.id);Pi&&await yvt(Pi,t,O,R.setCurrentAiMessage,T,{debug:s.debug,updateLoadingMessage:R.setLoadingMessage})}catch(Pi){ne("Error regenerating AI response:",Pi),new Sl.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),new Sl.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]);let Lt=(0,lr.useCallback)(pt=>{let Br=s.projectList||[];if(Br.findIndex(Pi=>Pi.name===pt.name)>=0)throw new Error(`Project "${pt.name}" already exists, please use a different name`);let Ei=[...Br,pt];return Ue("projectList",Ei),Uu()?.id===pt.id?k$e().then(()=>{new Sl.Notice(`${pt.name} added and context loaded`)}).catch(Pi=>{ne("Error loading project context:",Pi),new Sl.Notice(`${pt.name} added but context loading failed`)}):new Sl.Notice(`${pt.name} added successfully`),!0},[s.projectList]),Eo=(0,lr.useCallback)((pt,Br)=>{let Ti=s.projectList||[];if(!Ti.find(tl=>tl.name===pt.name))throw new Error(`Project "${pt.name}" does not exist`);let tu=Ti.map(tl=>tl.name===pt.name?Br:tl);return Ue("projectList",tu),Uu()?.id===pt.id?(Fz(Br),k$e().then(()=>{new Sl.Notice(`${pt.name} updated and context reloaded`)}).catch(tl=>{ne("Error reloading project context:",tl),new Sl.Notice(`${pt.name} updated but context reload failed`)})):new Sl.Notice(`${pt.name} updated successfully`),!0},[s.projectList]),xl=(0,lr.useCallback)(pt=>{let Br=z.find(Ti=>Ti.id===pt);yAt(pt),Br?.sourceType==="web"&&o.suppressCurrentWebSelection(Br.url)},[o,z]);(0,lr.useEffect)(()=>{let pt=()=>{a.focusInput()};return u?.addEventListener(Zw.CHAT_IS_VISIBLE,pt),()=>{u?.removeEventListener(Zw.CHAT_IS_VISIBLE,pt)}},[u,a]);let In=(0,lr.useCallback)(async pt=>{let Br=l[pt];if(!Br){new Sl.Notice("Message not found.");return}try{await i.deleteMessage(Br.id)||new Sl.Notice("Failed to delete message. Please try again.")}c
Original name: ${a.title}
${a.content}`}):e.push(a)}await Um.getInstance().updateCommands([...n.map(a=>({...a,showInSlashMenu:!0})),...e]);let i=`We have upgraded your commands to the new format. They are now also stored as notes in ${vU()}.`;r.length>0&&(await qhi(r),i+=`
We found ${r.length} unsupported commands. They are saved in ${vU()}/unsupported. To fix them, please resolve the errors and move the note file out of the unsupported folder.`),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=`
You are an AI assistant designed to execute user instructions with precision. Your responses should be:
- Direct and focused: Address only what is explicitly requested
- Concise: Avoid unnecessary elaboration unless the user asks for details
- Context-aware: When text is selected or highlighted, treat it as the primary target for any requested action
- Action-oriented: Prioritize completing the task over explaining the process
Key principles:
- Follow instructions literally and completely
- Assume selected/highlighted text is the focus unless told otherwise
- Use all provided context: Consider any additional information, examples, or constraints the user provides to better complete the task
- Add explanations only when explicitly requested or when clarification is essential
- Maintain the user's preferred format and style
Response format: Match the format implied by the user's request (e.g., if they ask for a list, provide a list; if they ask for a rewrite, provide only the rewritten text).
`,g=r;if(c){let w=g.includes("{}"),O=/\{activenote\}/i.test(g),T=[];w||T.push("{}"),O||T.push("{activeNote}"),T.length>0&&(g+=`
${T.join(`
`)}`)}let b={title:"Quick Command",content:g,showInContextMenu:!1,showInSlashMenu:!1,order:0,modelKey:l,lastUsedMs:Date.now()};new SU(t.app,{selectedText:i,command:b,systemPrompt:y}).open(),e()},f=()=>{e()},p=y=>{y.key==="Escape"?(y.preventDefault(),f()):y.key==="Enter"&&!y.shiftKey&&(y.preventDefault(),d())},m=y=>{Ue("quickCommandModelKey",y)},h=y=>{Ue("quickCommandIncludeNoteContext",y)};return Fc.default.createElement("div",{className:"tw-rounded-lg tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-4",onKeyDown:p},Fc.default.createElement("div",{className:"tw-space-y-4"},Fc.default.createElement(bw,{ref:u,value:r,onChange:y=>n(y.target.value),placeholder:"Ask me anything...",className:"tw-min-h-24 tw-resize-none",rows:3}),Fc.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-gap-4"},Fc.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-4"},Fc.default.createElement(U$e,{size:"sm",variant:"ghost",value:l,onChange:m}),Fc.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Fc.default.createElement(Qc,{id:"includeActiveNote",checked:c,onCheckedChange:y=>h(!!y)}),Fc.default.createElement("label",{htmlFor:"includeActiveNote",className:"tw-cursor-pointer tw-text-sm tw-text-muted"},"Include note context"))),Fc.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Fc.default.createElement(ge,{variant:"secondary",onClick:f,size:"sm"},"Cancel"),Fc.default.createElement(ge,{onClick:d,size:"sm"},"Submit")))))}function rrn({plugin:t,element:e}){let r=document.createElement("div");e.appendChild(r);let n=(0,trn.createRoot)(r),o=()=>{let i=t.app.workspace.getActiveViewOfType(sfe.MarkdownView);i&&i.editor&&lDe(i.editor),n.unmount(),r.remove()};return n.render(Fc.default.createElement(Uhi,{plugin:t,onRemove:o})),{root:n,container:r}}Or();ot();Vq();Bc();qs();_t();k1();Or();async function nrn(t,e){await e.clearChatMemory();for(let r=0;r<t.length-1;r++){let n=t[r];if(n.sender===Ws){let o=t[r+1];o?.sender===nC&&await e.getMemory().saveContext({input:n.message},{output:o.message})}}}qs();Bc();Or();var arn=L(mV());_t();var orn=["L1_SYSTEM","L2_PREVIOUS","L3_TURN","L4_STRIP","L5_USER"],irn={L1_SYSTEM:"System Instructions",L2_PREVIOUS:"Previous Turn Context",L3_TURN:"Current Turn Context",L4_STRIP:"Conversation Strip",L5_USER:"User Message"};var wB=class wB{constructor(){}static getInstance(){return wB.instance||(wB.instance=new wB),wB.instance}buildEnvelope(e){let r=orn.map(s=>this.buildLayer(s,e.layerSegments[s]??[])),n=this.serializeLayers(r),o=this.collectLayerHashes(r),i=this.hash(n),a=typeof e.metadata?.debugLabel=="string"?e.metadata.debugLabel:void 0;return a&&B(`[PromptContextEngine] Built envelope for ${a}`,o),{version:wB.ENVELOPE_VERSION,conversationId:e.conversationId,messageId:e.messageId,layers:r,serializedText:n,layerHashes:o,combinedHash:i,debug:{warnings:this.collectWarnings(r)}}}buildLayer(e,r){let n=r.map((i,a)=>({...i,id:i.id||`${e}-segment-${a}`,content:this.normalizeWhitespace(i.content),stable:i.stable??!0})),o=this.normalizeWhitespace(n.map(i=>i.content).filter(Boolean).join(`
`));return{id:e,label:irn[e],text:o,segments:n,stable:n.every(i=>i.stable),metadata:n.length===1?n[0].metadata:void 0,hash:this.hash(o)}}serializeLayers(e){return e.map(r=>r.text).filter(r=>r.length>0).join(`
`)}collectLayerHashes(e){return e.reduce((r,n)=>(r[n.id]=n.hash,r),{})}hash(e){return(0,arn.SHA256)(e||"").toString()}normalizeWhitespace(e){return e.replace(/\s+$/g,"").trim()}collectWarnings(e){let r=[];return e.forEach(n=>{if(!n.text)return;n.text.includes("\0")&&r.push(`Layer ${n.id} contains control characters and was normalized`)}),r}};wB.ENVELOPE_VERSION=1;var ZFe=wB;qs();Or();_t();Yle();SJ();bX();Zt();CX();var ufe=require("obsidian");Or();var YFe=class t{constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}async processEmbeddedPDFs(e,r,n){let o=/!\[\[(.*?\.pdf)\]\]/g,i=[...e.matchAll(o)];for(let a of i){let s=a[1],u=r.getAbstractFileByPath(s);if(u instanceof ufe.TFile)try{let l=await n.parseFile(u,r);e=e.replace(a[0],`
<${Dee}>
<name>${s}</name>
<content>
${l}
</content>
</${Dee}>
`)}catch(l){ne(`Error processing embedded PDF ${s}:`,l),e=e.replace(a[0],`
<${Dee}>
<name>${s}</name>
<error>Could not process PDF</error>
</${Dee}>
`)}}return e}async processDataviewBlocks(e,r){let n=app.plugins?.plugins?.dataview;if(!n)return e;let o=n.api;if(!o)return e;let i=/```(dataview|dataviewjs)\s*\n([\s\S]*?)```/g,a=[...e.matchAll(i)];for(let s=a.length-1;s>=0;s--){let u=a[s],l=u[1],c=u[2].trim(),d=u.index,f=d+u[0].length;try{let p=await Promise.race([this.executeDataviewQuery(o,c,l,r),new Promise((h,y)=>setTimeout(()=>y(new Error("Query timeout")),5e3))]),m=`
<${$ee}>
<query_type>${l}</query_type>
<original_query>
${c}
</original_query>
<executed_result>
${p}
</executed_result>
</${$ee}>
`;e=e.slice(0,d)+m+e.slice(f)}catch(p){ne("Error executing Dataview query:",p);let m=`
<${$ee}>
<query_type>${l}</query_type>
<original_query>
${c}
</original_query>
<error>${p instanceof Error?p.message:"Query execution failed"}</error>
</${$ee}>
`;e=e.slice(0,d)+m+e.slice(f)}}return e}async executeDataviewQuery(e,r,n,o){if(n==="dataviewjs")return"[DataviewJS execution not yet supported - showing original query]";let i=await e.query(r,o);if(!i.successful)throw new Error(i.error||"Query failed");return this.formatDataviewResult(i.value)}formatDataviewResult(e){return e?e.type==="list"?this.formatDataviewList(e.values):e.type==="table"?this.formatDataviewTable(e.headers,e.values):e.type==="task"?this.formatDataviewTasks(e.values):Array.isArray(e)?e.map(r=>this.formatDataviewValue(r)).join(`
`):String(e):"No results"}formatDataviewList(e){return!e||e.length===0?"No results":e.map(r=>`- ${this.formatDataviewValue(r)}`).join(`
`)}formatDataviewTable(e,r){if(!r||r.length===0)return"No results";let n=`| ${e.join(" | ")} |
`;n+=`| ${e.map(()=>"---").join(" | ")} |
`;for(let o of r)n+=`| ${o.map(i=>this.formatDataviewValue(i)).join(" | ")} |
`;return n}formatDataviewTasks(e){return!e||e.length===0?"No results":e.map(r=>`- ${r.completed?"[x]":"[ ]"} ${this.formatDataviewValue(r.text||r)}`).join(`
`)}formatDataviewValue(e){return e==null?"":e&&typeof e=="object"&&e.path?`[[${e.path}]]`:Array.isArray(e)?e.map(r=>this.formatDataviewValue(r)).join(", "):String(e)}async buildMarkdownContextContent(e,r,n,o){let i=await n.parseFile(e,r);return i=await this.processEmbeddedNotes(i,e,r,n,o),sb(o)&&(i=await this.processEmbeddedPDFs(i,r,n)),await this.processDataviewBlocks(i,e.path)}async processEmbeddedNotes(e,r,n,o,i){let a=/!\[\[([^\]]+)\]\]/g,s,u=0,l="";for(;(s=a.exec(e))!==null;){l+=e.slice(u,s.index);let c=s[1].trim(),d=await this.buildEmbeddedNoteBlock(c,s[0],r,n,o,i);l+=d,u=s.index+s[0].length}return l+=e.slice(u),l}async buildEmbeddedNoteBlock(e,r,n,o,i,a){let s=this.parseEmbeddedLinkTarget(e);if(!s)return r;let u=s.path===null?n:app.metadataCache.getFirstLinkpathDest(s.path,n.path);if(!(u instanceof ufe.TFile))return this.formatEmbeddedNoteBlock({title:s.path??n.basename,path:s.path??n.path,heading:s.heading,blockId:s.blockId,error:"Embedded note not found"});if(u.extension!=="md")return r;try{let l=await i.parseFile(u,o);if(s.heading||s.blockId){let c=this.extractMarkdownSegment(u,l,s);if(!c.found){let d=s.blockId?`block reference "${s.blockId}"`:`heading "${s.heading??""}"`;throw new Error(`Embedded note ${d} not found in ${u.path}`)}l=c.content}return sb(a)&&(l=await this.processEmbeddedPDFs(l,o,i)),l=await this.processDataviewBlocks(l,u.path),this.formatEmbeddedNoteBlock({title:u.basename,path:u.path,heading:s.heading,blockId:s.blockId,content:l})}catch(l){Be("Failed to process embedded note",l);let c=l instanceof Error?l.message:"Could not process embedded note";return this.formatEmbeddedNoteBlock({title:u.basename,path:u.path,heading:s.heading,blockId:s.blockId,error:c})}}parseEmbeddedLinkTarget(e){if(!e)return null;let r=e.indexOf("|"),o=(r>=0?e.slice(0,r):e).trim();if(!o)return{path:null};let i,a,s=o.indexOf("#^");s!==-1&&(i=o.slice(s+2).trim(),o=o.slice(0,s));let u=o.indexOf("#");return u!==-1&&(a=o.slice(u+1).trim(),o=o.slice(0,u)),{path:o.length>0?o:null,heading:a&&a.length>0?a:void 0,blockId:i&&i.length>0?i:void 0}}extractMarkdownSegment(e,r,n){let o=app.metadataCache.getFileCache(e);if(n.blockId){let i=o?.blocks?.[n.blockId],a=i?.position?.start?.offset,s=i?.position?.end?.offset;return a===void 0||s===void 0?{content:"",found:!1}:{content:r.slice(a,s),found:!0}}if(n.heading){let i=o?.headings??[],a=this.normalizeHeadingForMatch(n.heading),s=i.findIndex(d=>this.normalizeHeadingForMatch(d.heading)===a);if(s===-1)return{content:"",found:!1};let u=i[s],l=u.position?.start?.offset??0,c=r.length;for(let d=s+1;d<i.length;d++)if(i[d].level<=u.level){c=i[d].position?.start?.offset??c;break}return{content:r.slice(l,c),found:!0}}return{content:r,found:!0}}normalizeHeadingForMatch(e){return e.trim().toLowerCase().replace(/\s+/g," ")}formatEmbeddedNoteBlock(e){let{title:r,path:n,heading:o,blockId:i,content:a,error:s}=e,u=`
<${mHe}>
<title>${r}</title>
<path>${n}</path>`;return o&&(u+=`
<heading>${o}</heading>`),i&&(u+=`
<block_id>${i}</block_id>`),s?u+=`
<error>${s}</error>`:u+=`
<content>
${a??""}
</content>`,u+=`
</${mHe}>
`,u}async processContextNotes(e,r,n,o,i,a,s){let u="",l=async(d,f=Nee)=>{try{if(e.has(d.path)){B(`Skipping note ${d.path} as it was included via custom prompt.`);return}if(!r.supportsExtension(d.extension)){Be(`Unsupported file type: ${d.extension}`);return}if(!sb(s)&&d.extension!=="md"&&d.extension!=="canvas"){Be(`File type ${d.extension} requires Copilot Plus mode for context processing.`),new ufe.Notice(GW.NON_MARKDOWN_FILES_RESTRICTED);return}let p=d.extension==="md"?await this.buildMarkdownContextContent(d,n,r,s):await r.parseFile(d,n),m=await n.adapter.stat(d.path),h=m?new Date(m.ctime).toISOString():"Unknown",y=m?new Date(m.mtime).toISOString():"Unknown";u+=`
<${f}>
<title>${d.basename}</title>
<path>${d.path}</path>
<ctime>${h}</ctime>
<mtime>${y}</mtime>
<content>
${p}
</content>
</${f}>`}catch(p){ne(`Error processing file ${d.path}:`,p),u+=`
<${f}_error>
<title>${d.basename}</title>
<path>${d.path}</path>
<error>[Error: Could not process file]</error>
</${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)}async addNoteToContext(e,r,n,o,i,a){if(n.some(l=>l.path===e.path))return;let s=await r.read(e),u=await this.hasEmbeddedPDFs(s);o&&e.path===o.path&&a(!0),i(l=>[...l,Object.assign(e,{wasAddedViaReference:!0,hasEmbeddedPDFs:u})])}processSelectedTextContexts(){let e=bL();if(!e||e.length===0)return"";let r="";for(let n of e)n.sourceType==="web"?r+=`
<${pHe}>
<title>${Yc(n.title)}</title>
<url>${Yc(n.url)}</url>
<content>
${Yc(n.content)}
</content>
</${pHe}>`:r+=`
<${n_}>
<title>${Yc(n.noteTitle)}</title>
<path>${Yc(n.notePath)}</path>
<start_line>${n.startLine.toString()}</start_line>
<end_line>${n.endLine.toString()}</end_line>
<content>
${n.content}
</content>
</${n_}>`;return r}async processContextWebTabs(e){if(!e||e.length===0)return"";let r=2500,n=8e3,o=15e3,i=2,a=(b,_)=>{let w=[`
<${b}>`,`
<title>${Yc(_.title)}</title>`,`
<url>${Yc(_.url)}</url>`];return _.mode&&w.push(`
<mode>${Yc(_.mode)}</mode>`),_.error?w.push(`
<error>${Yc(_.error)}</error>`):_.content!==void 0&&w.push(`
<content>
${Yc(_.content)}
</content>`),w.push(`
</${b}>`),w.join("")},s=b=>{let _=[`
<${yHe}>`,`
<title>${Yc(b.title)}</title>`,`
<url>${Yc(b.url)}</url>`,`
<video_id>${Yc(b.videoId)}</video_id>`];b.isActive&&_.push(`
<is_active>true</is_active>`),b.channel&&_.push(`
<channel>${Yc(b.channel)}</channel>`),b.uploadDate&&_.push(`
<upload_date>${Yc(b.uploadDate)}</upload_date>`),b.duration&&_.push(`
<duration>${Yc(b.duration)}</duration>`),b.genre&&_.push(`
<genre>${Yc(b.genre)}</genre>`),b.description&&_.push(`
<description>${Yc(b.description)}</description>`),b.error&&_.push(`
<error>${Yc(b.error)}</error>`);let w=b.transcript||"No transcript available for this video";return _.push(`
<content>
${Yc(w)}
</content>`),_.push(`
</${yHe}>`),_.join("")},u=null,l=[],c=new Set,d=new Set,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(let b of e){let _=Dy(b.url);_&&b.isActive&&!u&&(u={...b,url:_},p(_))}for(let b of e){let _=Dy(b.url);!_||p(_)||l.push({...b,url:_})}if(!u&&l.length===0)return"";let m=f.getAvailability();if(!m.supported||!m.available){let b=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(let w of l)_.push(a(gHe,{title:w.title||"Unknown",url:w.url,error:b}));return _.join("")}let h=async(b,_)=>{try{let w=b.url,O=f.getYouTubeVideoId(w);if(O)return await y(b,O,_===mge);let T=f.findLeafByUrl(w,{title:b.title});if(!T)return a(_,{title:b.title||"Unknown",url:w,error:"Web tab not found or closed"});let P=f.getPageInfo(T),M=T.view;if(!(M.webviewMounted===void 0||M.webviewFirstLoadFinished===void 0?!0:!!(M.webviewMounted&&M.webviewFirstLoadFinished)))try{await f.waitForWebviewReady(T,r),P=f.getPageInfo(T)}catch(k){return Be(`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"})}let j=new AbortController,A=setTimeout(()=>{j.abort()},n);try{let k=await f.getReaderModeMarkdown(T,{signal:j.signal});return P=f.getPageInfo(T),a(_,{title:P.title||b.title||"Untitled",url:P.url||w,mode:P.mode,content:k})}finally{clearTimeout(A)}}catch(w){return ne(`Error processing web tab ${b.url}:`,w),a(_,{title:b.title||"Unknown",url:b.url,error:w instanceof CU?"Web tab content extraction timed out":"Could not process web tab"})}},y=async(b,_,w)=>{try{let O=null,T=b.url;for(let A of f.getLeaves()){let k=f.getPageInfo(A).url;if(f.getYouTubeVideoId(k)===_){O=A,T=k;break}}if(!O)return s({title:b.title||"YouTube Video",url:b.url,videoId:_,isActive:w,error:"Web tab not found or closed"});let P=O.view;if(!(P.webviewMounted===void 0||P.webviewFirstLoadFinished===void 0?!0:!!(P.webviewMounted&&P.webviewFirstLoadFinished)))try{await f.waitForWebviewReady(O,r)}catch(A){return Be(`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"})}let I=await f.getYouTubeTranscript(O,{timeoutMs:o}),j=I.transcript.length>0?I.transcript.map(A=>`${A.timestamp}: ${A.text}`).join(`
`):void 0;return s({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){return Be(`YouTube transcript extraction failed for ${b.url}:`,O),s({title:b.title||"YouTube Video",url:b.url,videoId:_,isActive:w,error:O instanceof Error?O.message:"Failed to extract video info"})}},g=[];if(u){let b=await h(u,mge);g.push(b)}for(let b=0;b<l.length;b+=i){let _=l.slice(b,b+i),w=await Promise.all(_.map(O=>h(O,gHe)));g.push(...w)}return g.join("")}};_t();kot();ot();Zt();var vvt=null;async function Bhi(){return vvt||(vvt=(await Promise.resolve().then(()=>(urn(),srn))).ContextCompactor),vvt.getInstance()}var QFe=class t{constructor(){this.contextProcessor=YFe.getInstance(),this.mention=aG.getInstance(),this.promptContextEngine=ZFe.getInstance()}static getInstance(){return t.instance||(t.instance=new t),t.instance}async processMessageContext(e,r,n,o,i,a,s,u,l=[],c){try{B(`[ContextManager] Processing context for message ${e.id}`);let d=e.originalMessage||e.message,{processedPrompt:f,includedFiles:p}=await gce(d,"",n,a),{l2Context:m,l2Paths:h}=this.buildL2ContextFromPreviousTurns(e.id,s),y=e.context?.urls||[],g=o==="copilot_plus"?await this.mention.processUrlList(y):{urlContext:"",imageUrls:[]},b=new Set([...p.map(H=>H.path),...l.map(H=>H.path),...h]),_=new Set,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);let T=await this.contextProcessor.processContextNotes(b,r,n,O,i,a,o);O.forEach(H=>{b.add(H.path),_.add(H.path)});let P=e.context?.tags||[],M="",I=[];if(P.length>0){let re=sge(n,P).filter(D=>!b.has(D.path));re.length>0&&(M=await this.contextProcessor.processContextNotes(new Set,r,n,re,!1,null,o),re.forEach(D=>{b.add(D.path),_.add(D.path),I.push(D.path)}))}let j=e.context?.folders||[],A="",k=[];if(j.length>0){let re=j.flatMap(D=>Eee(n,D)).filter(D=>!b.has(D.path));re.length>0&&(A=await this.contextProcessor.processContextNotes(new Set,r,n,re,!1,null,o),re.forEach(D=>{b.add(D.path),_.add(D.path),k.push(D.path)}))}let V=this.contextProcessor.processSelectedTextContexts(),q=e.context?.webTabs||[],J=await this.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);let re=await(await Bhi()).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){return B(`[ContextManager] Error processing context for message ${e.id}:`,d),{processedContent:e.originalMessage||e.message,contextEnvelope:void 0}}}async reprocessMessageContext(e,r,n,o,i,a,s,u,l=[]){let c=r.getMessage(e);if(!c||c.sender!=="user"||!c.id)return;B(`[ContextManager] Reprocessing context for message ${e}`);let{processedContent:d,contextEnvelope:f}=await this.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){let n=r.getDisplayMessages(),o=n.findIndex(l=>l.id===e);if(o===-1||o===0)return{l2Context:"",l2Paths:new Set};let i=n.slice(0,o).filter(l=>l.sender==="user"),a=[],s=new Set,u=-1;for(let l=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(let l=0;l<i.length;l++){let d=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] Added message with ID: ${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] Added message with ID: ${s}`),s}editMessage(e,r){let n=this.messages.find(o=>o.id===e);return n?n.displayText===r?(B(`[MessageRepository] No changes needed for message: ${e}`),!0):(n.displayText=r,n.sender==="user"||n.sender==="USER"?B(`[MessageRepository] Edited user message ${e}, needs context reprocessing`):(n.processedText=r,B(`[MessageRepository] Edited AI message ${e}`)),!0):(B(`[MessageRepository] Message not found for edit: ${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] Updated p
[Context: ${i.join(" | ")}]`)}return o+=`
[Timestamp: ${n}]`,o}).join(`
`)}parseChatContent(e){let r=[],n=e.match(/^---\n([\s\S]*?)\n---/),o=e;n&&(o=e.slice(n[0].length).trim());let i=/\*\*(user|ai)\*\*: ([\s\S]*?)(?=(?:\n\*\*(?:user|ai)\*\*: )|$)/g,a;for(;(a=i.exec(o))!==null;){let s=a[1]==="user"?Ws:nC,u=a[2].trim(),l=u.split(`
`),c=u,d="Unknown time",f,p=l.length;if(l[p-1]?.startsWith("[Timestamp: ")){let h=l[p-1].match(/\[Timestamp: (.*?)\]/);h&&(d=h[1],p--)}if(p>0&&l[p-1]?.startsWith("[Context: ")){let h=l[p-1].match(/\[Context: (.*?)\]/);if(h){let y=h[1];f=this.parseContextString(y),p--}}c=l.slice(0,p).join(`
`).trim();let m;if(d!=="Unknown time"){let h=new Date(d);isNaN(h.getTime())||(m=h.getTime())}r.push({message:c,sender:s,isVisible:!0,timestamp:m?{epoch:m,display:d,fileName:""}:null,context:f})}return r}parseContextString(e){let r={notes:[],urls:[],tags:[],folders:[],webTabs:[]},n=e.split(" | ");for(let o of n){let i=o.trim();if(i.startsWith("Notes: ")){let a=i.substring(7);a&&(r.notes=a.split(", ").map(s=>{let u=s.trim(),l=this.app.vault.getAbstractFileByPath(u);if(l instanceof sv.TFile)return l;let c=u.includes("/")?u.split("/").pop():u,d=this.app.vault.getMarkdownFiles().filter(f=>f.basename===c);return d.length===1?(B(`[ChatPersistenceManager] Resolved legacy basename "${c}" to ${d[0].path}`),d[0]):(d.length>1?Be(`[ChatPersistenceManager] Ambiguous basename "${c}", skipping. Matches: ${d.map(f=>f.path).join(", ")}`):Be(`[ChatPersistenceManager] Note not found: ${u}`),null)}).filter(s=>s!==null))}else if(i.startsWith("URLs: ")){let a=i.substring(6);a&&(r.urls=a.split(", ").map(s=>s.trim()))}else if(i.startsWith("Web Tabs: ")||i.startsWith("WebTabs: ")){let a=i.startsWith("Web Tabs: ")?i.substring(10):i.substring(9);a&&(r.webTabs=a.split(", ").map(s=>s.trim()).filter(s=>s.length>0).map(s=>({url:s})))}else if(i.startsWith("Tags: ")){let a=i.substring(6);a&&(r.tags=a.split(", ").map(s=>s.trim()))}else if(i.startsWith("Folders: ")){let a=i.substring(9);a&&(r.folders=a.split(", ").map(s=>s.trim()))}}if(r.notes.length>0||r.urls.length>0||r.tags.length>0||r.folders.length>0||r.webTabs.length>0)return r}async findFileByEpoch(e){let r=await this.getChatHistoryFiles();for(let n of r){let o=this.app.metadataCache.getFileCache(n)?.frontmatter,i=typeof o?.epoch=="number"?o.epoch:typeof o?.epoch=="string"?Number(o.epoch):void 0;if(typeof i=="number"&&!Number.isNaN(i)&&i===e)return n}return null}async generateAITopic(e){if(this.chainManager)try{let r=this.chainManager.chatModelManager.getChatModel();if(!r)return;let n=6,o=200,a=`Generate a concise title (max 5 words) for this conversation based on its content. Return only the title without any explanation or quotes.
Conversation:
${e.reduce((c,d,f)=>f>=n?c:c+(c?`
`:"")+`${d.sender}: ${d.message.slice(0,o)}`,"")}`,s=await r.invoke(a),u=typeof s=="string"?s:s.content??s.text??s;return Rz(u).trim().replace(/^["']|["']$/g,"").replace(/[\\/:*?"<>|]/g,"").slice(0,50)||void 0}catch(r){ne("[ChatPersistenceManager] Error generating AI topic:",r);return}}generateFileName(e,r,n){let o=ae(),a=eg(new Date(r)).fileName,s;if(n)s=n;else{let w=e.find(O=>O.sender===Ws);s=w&&w.message.replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/[{}[\]]/g,"").split(/\s+/).slice(0,10).join(" ").replace(/[\\/:*?"<>|\x00-\x1F]/g,"").trim()||"Untitled Chat"}let u=o.defaultConversationNoteName||"{$date}_{$time}__{$topic}",l=Uu(),c=l?`${l.id}__`:"",d=Iee(".md"),f=Iee(c),p=u.replace("{$topic}","").replace("{$date}",a.split("_")[0]).replace("{$time}",a.split("_")[1]),m=Iee(p),h=Math.max(20,wvt-d-f-m),y=s.replace(/\s+/g,"_"),g=cHe(y,h);u=u.replace("{$topic}",g).replace("{$date}",a.split("_")[0]).replace("{$time}",a.split("_")[1]);let b=u.replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/[{}[\]]/g,"_").replace(/[\\/:*?"<>|\x00-\x1F]/g,"_"),_=`${c}${b}.md`;if(Iee(_)>wvt){let w=wvt-d-f,O=cHe(b,w);return`${o.defaultSaveFolder}/${c}${O}.md`}return`${o.defaultSaveFolder}/${_}`}generateNoteContent(e,r,n,o,i){let a=ae(),s=Uu();return`---
epoch: ${r}
modelKey: "${zhi(n)}"
${o?`topic: "${o}"`:""}
${i?`lastAccessedAt: ${i}`:""}
${s?`projectId: ${s.id}`:""}
${s?`projectName: ${s.name}`:""}
tags:
- ${a.defaultConversationTag}
---
${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] Applied AI topic to chat file: ${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] Project changed from ${this.lastKnownProjectId} to ${e}`),this.lastKnownProjectId=e),!this.projectMessageRepos.has(r)){B(`[ChatManager] Creating new message repository for project: ${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}
<project_system_prompt>
${d.processedPrompt}
</project_system_prompt>`;return c&&(f+=`
<project_context>
${c}
</project_context>`),{processedPrompt:f,includedFiles:i}}}return{processedPrompt:u,includedFiles:i}}buildWebTabsWithActiveSnapshot(e,r){let n=aJr(e);if(!r)return n;try{let a=ed(this.plugin.app).getActiveWebTabState().activeWebTabForMentions,s=SX(a?.url);if(!s)return n;let u=n.map(c=>{if(c.isActive){let{isActive:d,...f}=c;return f}return c}),l=u.findIndex(c=>SX(c.url)===s);if(l>=0){let c=u[l];return u[l]={...c,url:Dy(a?.url)??c.url,title:a?.title??c.title,faviconUrl:a?.faviconUrl??c.faviconUrl,isActive:!0},u}return[...u,{url:Dy(a?.url)??s,title:a?.title,faviconUrl:a?.faviconUrl,isActive:!0}]}catch(o){return Be("[ChatManager] Failed to resolve active web tab:",o),n}}async sendMessage(e,r,n,o=!1,i=!1,a,s){try{B(`[ChatManager] Sending message: "${e}"`);let u=this.plugin.app.workspace.getActiveFile(),l={...r};if(o&&u){let _=r.notes||[],w=_.some(O=>O.path===u.path);l.notes=w?_:[..._,u]}let d=!((l.selectedTextContexts||[]).length>0)&&(i||e.includes(Lee));l.webTabs=this.buildWebTabsWithActiveSnapshot(l.webTabs||[],d);let f=this.getCurrentMessageRepo(),p=f.addMessage(e,e,Ws,l,a);this.onMessageCreatedCallback&&this.onMessageCreatedCallback(p);let m=f.getMessage(p);if(!m)throw new Error(`Failed to retrieve message ${p}`);let{processedPrompt:h,includedFiles:y}=await this.getSystemPromptForMessage(n,this.plugin.app.vault,u),{processedContent:g,contextEnvelope:b}=await this.contextManager.processMessageContext(m,this.fileParserManager,this.plugin.app.vault,n,o,u,f,h,y,s);return f.updateProcessedText(p,g,b),B(`[ChatManager] Successfully sent message ${p}`),p}catch(u){throw B("[ChatManager] Error sending message:",u),u}}async editMessage(e,r,n,o=!1){try{B(`[ChatManager] Editing message ${e}: "${r}"`);let i=this.getCurrentMessageRepo();if(!i.editMessage(e,r))return!1;let s=this.plugin.app.workspace.getActiveFile(),{processedPrompt:u,includedFiles:l}=await this.getSystemPromptForMessage(n,this.plugin.app.vault,s);return await this.contextManager.reprocessMessageContext(e,i,this.fileParserManager,this.plugin.app.vault,n,o,s,u,l),await this.updateChainMemory(),B(`[ChatManager] Successfully edited message ${e}`),!0}catch(i){return B(`[ChatManager] Error editing message ${e}:`,i),!1}}async regenerateMessage(e,r,n,o){try{B(`[ChatManager] Regenerating message ${e}`);let i=this.getCurrentMessageRepo();if(!i.getMessage(e))return B(`[ChatManager] Message not found: ${e}`),!1;let s=i.getDisplayMessages(),u=s.findIndex(f=>f.id===e);if(u<=0)return B("[ChatManager] Cannot regenerate first message or no user message found"),!1;let l=s[u-1];if(l.sender!==Ws)return B("[ChatManager] Previous message is not from user"),!1;if(i.truncateAfter(u-1),o&&o(),await this.updateChainMemory(),!l.id)return B("[ChatManager] User message has no ID for regeneration"),!1;let c=i.getLLMMessage(l.id);if(!c)return B("[ChatManager] LLM message not found for regeneration"),!1;let d=new AbortController;return await this.chainManager.runChain(c,d,r,n,{debug:ae().debug}),B(`[ChatManager] Successfully regenerated message ${e}`),!0}catch(i){return B(`[ChatManager] Error regenerating message ${e}:`,i),!1}}async deleteMessage(e){try{return B(`[ChatManager] Deleting message ${e}`),this.getCurrentMessageRepo().deleteMessage(e)?(await this.updateChainMemory(),B(`[ChatManager] Successfully deleted message ${e}`),!0):!1}catch(r){return B(`[ChatManager] Error deleting message ${e}:`,r),!1}}addMessage(e){return this.getCurrentMessageRepo().addMessage(e)}clearMessages(){this.getCurrentMessageRepo().clear(),this.chainManager.memoryManager.clearChatMemory(),B("[ChatManager] Cleared all messages")}async truncateAfterMessageId(e){this.getCurrentMessageRepo().truncateAfterMessageId(e),await this.updateChainMemory(),B(`[ChatManager] Truncated messages after ${e}`)}getDisplayMessages(){return this.getCurrentMessageRepo().getDisplayMessages()}getLLMMessages(){return this.getCurrentMessageRepo().getLLMMessages()}getMessage(e){return this.getCurrentMessageRepo().getMessage(e)}getLLMMessage(e){return this.getCurrentMessageRepo().getLLMMessage(e)}async updateChainMemory(){try{let r=this.getCurrentMess
To pick up a draggable item, press the space bar.
While dragging, use the arrow keys to move the item.
Press space again to drop the item in its new position, or press escape to cancel.
`},Xhi={onDragStart(t){let{active:e}=t;return"Picked up draggable item "+e.id+"."},onDragOver(t){let{active:e,over:r}=t;return r?"Draggable item "+e.id+" was moved over droppable area "+r.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(t){let{active:e,over:r}=t;return r?"Draggable item "+e.id+" was dropped over droppable area "+r.id:"Draggable item "+e.id+" was dropped."},onDragCancel(t){let{active:e}=t;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function Zhi(t){let{announcements:e=Xhi,container:r,hiddenTextDescribedById:n,screenReaderInstructions:o=Ghi}=t,{announce:i,announcement:a}=vrn(),s=M3("DndLiveRegion"),[u,l]=(0,He.useState)(!1);if((0,He.useEffect)(()=>{l(!0)},[]),Whi((0,He.useMemo)(()=>({onDragStart(d){let{active:f}=d;i(e.onDragStart({active:f}))},onDragMove(d){let{active:f,over:p}=d;e.onDragMove&&i(e.onDragMove({active:f,over:p}))},onDragOver(d){let{active:f,over:p}=d;i(e.onDragOver({active:f,over:p}))},onDragEnd(d){let{active:f,over:p}=d;i(e.onDragEnd({active:f,over:p}))},onDragCancel(d){let{active:f,over:p}=d;i(e.onDragCancel({active:f,over:p}))}}),[i,e])),!u)return null;let c=He.default.createElement(He.default.Fragment,null,He.default.createElement(brn,{id:n,value:o.draggable}),He.default.createElement(_rn,{id:s,announcement:a}));return r?(0,N3.createPortal)(c,r):c}var Wm;(function(t){t.DragStart="dragStart",t.DragMove="dragMove",t.DragEnd="dragEnd",t.DragCancel="dragCancel",t.DragOver="dragOver",t.RegisterDroppable="registerDroppable",t.SetDroppableDisabled="setDroppableDisabled",t.UnregisterDroppable="unregisterDroppable"})(Wm||(Wm={}));function lke(){}function dY(t,e){return(0,He.useMemo)(()=>({sensor:t,options:e??{}}),[t,e])}function dke(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return(0,He.useMemo)(()=>[...e].filter(n=>n!=null),[...e])}var Jx=Object.freeze({x:0,y:0});function jrn(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}function Drn(t,e){let{data:{value:r}}=t,{data:{value:n}}=e;return r-n}function Yhi(t,e){let{data:{value:r}}=t,{data:{value:n}}=e;return n-r}function wrn(t){let{left:e,top:r,height:n,width:o}=t;return[{x:e,y:r},{x:e+o,y:r},{x:e,y:r+n},{x:e+o,y:r+n}]}function Avt(t,e){if(!t||t.length===0)return null;let[r]=t;return e?r[e]:r}function Srn(t,e,r){return e===void 0&&(e=t.left),r===void 0&&(r=t.top),{x:e+t.width*.5,y:r+t.height*.5}}var fY=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=Srn(e,e.left,e.top),i=[];for(let a of n){let{id:s}=a,u=r.get(s);if(u){let l=jrn(Srn(u),o);i.push({id:s,data:{droppableContainer:a,value:l}})}}return i.sort(Drn)},$rn=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=wrn(e),i=[];for(let a of n){let{id:s}=a,u=r.get(s);if(u){let l=wrn(u),c=o.reduce((f,p,m)=>f+jrn(l[m],p),0),d=Number((c/4).toFixed(4));i.push({id:s,data:{droppableContainer:a,value:d}})}}return i.sort(Drn)};function Qhi(t,e){let r=Math.max(e.top,t.top),n=Math.max(e.left,t.left),o=Math.min(e.left+e.width,t.left+t.width),i=Math.min(e.top+e.height,t.top+t.height),a=o-n,s=i-r;if(n<o&&r<i){let u=e.width*e.height,l=t.width*t.height,c=a*s,d=c/(u+l-c);return Number(d.toFixed(4))}return 0}var egi=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=[];for(let i of n){let{id:a}=i,s=r.get(a);if(s){let u=Qhi(s,e);u>0&&o.push({id:a,data:{droppableContainer:i,value:u}})}}return o.sort(Yhi)};function tgi(t,e,r){return{...t,scaleX:e&&r?e.width/r.width:1,scaleY:e&&r?e.height/r.height:1}}function Lrn(t,e){return t&&e?{x:t.left-e.left,y:t.top-e.top}:Jx}function rgi(t){return function(r){for(var n=arguments.length,o=new Array(n>1?n-1:0),i=1;i<n;i++)o[i-1]=arguments[i];return o.reduce((a,s)=>({...a,top:a.top+t*s.y,bottom:a.bottom+t*s.y,left:a.left+t*s.x,right:a.right+t*s.x}),{...r})}}var ngi=rgi(1);function ogi(t){if(t.startsWith("matrix3d(")){let e=t.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(t.startsWith("matrix(")){let e=t.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}funct
If you want to hide the \`${e.titleName}\`, you can wrap it with our VisuallyHidden component.
For more information, see https://radix-ui.com/primitives/docs/components/${e.docsSlug}`;return el.useEffect(()=>{t&&(document.getElementById(t)||console.error(r))},[r,t]),null},Nyi="DialogDescriptionWarning",jyi=({contentRef:t,descriptionId:e})=>{let n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Enn(Nyi).contentName}}.`;return el.useEffect(()=>{let o=t.current?.getAttribute("aria-describedby");e&&o&&(document.getElementById(e)||console.warn(n))},[n,t,e]),null},Pnn=pnn,Mnn=hnn,Inn=ynn,Fvt=bnn,kvt=_nn,qvt=wnn,Uvt=Cnn,Rnn=Onn;Jr();kn();var Oke=Pnn,Ann=Mnn,$yi=Inn;var Nnn=Ug.forwardRef(({className:t,...e},r)=>Ug.createElement(Fvt,{ref:r,className:Te("tw-fixed tw-inset-0 tw-z-modal data-[state=open]:tw-animate-in data-[state=closed]:tw-animate-out data-[state=closed]:tw-fade-out-0 data-[state=open]:tw-fade-in-0","tw-bg-overlay/50",t),...e}));Nnn.displayName=Fvt.displayName;var Cfe=Ug.forwardRef(({className:t,children:e,container:r,...n},o)=>Ug.createElement($yi,{container:r},Ug.createElement(Nnn,null),Ug.createElement(kvt,{ref:o,className:Te("tw-fixed tw-left-1/2 tw-top-1/2 tw-z-modal tw-grid tw-w-full tw-max-w-lg -tw-translate-x-1/2 -tw-translate-y-1/2 tw-gap-4 tw-border tw-bg-primary tw-p-6 tw-shadow-lg tw-duration-200 data-[state=open]:tw-animate-in data-[state=closed]:tw-animate-out data-[state=closed]:tw-fade-out-0 data-[state=open]:tw-fade-in-0 data-[state=closed]:tw-zoom-out-95 data-[state=open]:tw-zoom-in-95 data-[state=closed]:tw-slide-out-to-left-1/2 data-[state=closed]:tw-slide-out-to-top-[48%] data-[state=open]:tw-slide-in-from-left-1/2 data-[state=open]:tw-slide-in-from-top-[48%] sm:tw-rounded-lg",t),...n},e,Ug.createElement(Rnn,{className:"clickable-icon tw-absolute tw-right-4 tw-top-4 tw-border-none tw-bg-transparent tw-text-faint tw-outline-none hover:tw-bg-transparent hover:tw-bg-opacity-100 hover:tw-text-normal focus-visible:tw-text-normal focus-visible:tw-outline-none focus-visible:tw-ring-0"},Ug.createElement($o,{className:"tw-size-4"}),Ug.createElement("span",{className:"tw-sr-only"},"Close")))));Cfe.displayName=kvt.displayName;var xfe=({className:t,...e})=>Ug.createElement("div",{className:Te("tw-flex tw-flex-col tw-space-y-0.5 tw-text-center sm:tw-text-left",t),...e});xfe.displayName="DialogHeader";var Lyi=({className:t,...e})=>Ug.createElement("div",{className:Te("tw-flex tw-flex-col-reverse sm:tw-flex-row sm:tw-justify-end sm:tw-space-x-2",t),...e});Lyi.displayName="DialogFooter";var Ofe=Ug.forwardRef(({className:t,...e},r)=>Ug.createElement(qvt,{ref:r,className:Te("tw-mt-0 tw-text-lg tw-font-semibold tw-leading-none tw-tracking-tight",t),...e}));Ofe.displayName=qvt.displayName;var Tfe=Ug.forwardRef(({className:t,...e},r)=>Ug.createElement(Uvt,{ref:r,className:Te("tw-text-sm tw-text-muted",t),...e}));Tfe.displayName=Uvt.displayName;Zt();function on(t){let{title:e,description:r,className:n,disabled:o}=t,{modalContainer:i}=SB(),a="onChange"in t?t.onChange:void 0,s=(0,Cl.useMemo)(()=>{if(a)return dge(l=>{a(l)},1e3)},[a]),u=()=>{switch(t.type){case"text":case"number":return Cl.default.createElement(Zo,{type:t.type,defaultValue:t.value,onChange:l=>{s?.(l.target.value)},placeholder:t.placeholder,disabled:o,className:"tw-w-full sm:tw-w-[200px]"});case"password":return Cl.default.createElement(jA,{value:t.value!==void 0?String(t.value):void 0,onChange:l=>{s?.(l)},placeholder:t.placeholder,disabled:o,className:"tw-w-full sm:tw-w-[200px]"});case"textarea":return Cl.default.createElement(bw,{defaultValue:t.value,onChange:l=>{s?.(l.target.value)},placeholder:t.placeholder,rows:t.rows||3,disabled:o,className:"tw-min-h-[80px] tw-w-full sm:tw-w-[300px]"});case"switch":return Cl.default.createElement(cx,{checked:t.checked,onCheckedChange:t.onCheckedChange,disabled:o});case"select":return Cl.default.createElement("div",{className:"tw-group tw-relative tw-w-full sm:tw-w-[200px]"},Cl.default.createElement("select",{value:t.value?.toString(),onChange:l=>t.onChange?.(l.target.value),disabled:o,className:Te("tw-w-full tw-appearance-none","tw-flex tw-h-9 tw-rounded-md tw-border tw-border-s
detail: `+f)}return d}finally{clearTimeout(c)}},i;try{i=await o(!1)}catch(u){Be("First fetch attempt failed, trying with safeFetch...");try{i=await o(!0)}catch(l){let c=`
without CORS Error: `+Sn(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("Model verification failed:",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||"Failed to load models"),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("Please select a model first");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("Error adding model:",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:"Add the selected model to your models list. After adding, check the Model Tab."},Fu.default.createElement("div",null,Fu.default.createElement("div",{className:"tw-flex tw-items-center tw-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:"Select Model",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-full tw-whitespace-nowrap"},m?Fu.default.createElement(du,{className:"tw-mr-2 tw-size-4 tw-animate-spin"}):"Add"))),Fu.default.createElement("div",{className:"tw-mt-1 tw-text-xs"},u&&Fu.default.createElement("div",{className:"tw-p-1 tw-text-muted"},"Loading models..."),c&&Fu.default.createElement("div",{className:"tw-p-1 tw-text-error"},"Failed to load models. ",c),a&&a.length===0&&Fu.default.createElement("div",{className:"tw-p-1 tw-text-muted"},"No models available."),a===null&&!u&&!c&&Fu.default.createElement("div",{className:"tw-p-1 tw-text-muted"},"Click to load available models."))))}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}" is not supported for curl generation.`,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();var ion=require("obsidian"),tn=L(X()),aon=()=>{let t=zr(),e=async r=>{if(r!==t.embeddingModelKey){if(t.enableSemanticSearchV3){new Fke(app,async()=>{Ue("embeddingModelKey",r),await(await Promise.resolve().then(()=>(Am(),xg))).default.getInstance().indexVaultToVectorStore(!1)}).open();return}Ue("embeddingModelKey",r),new ion.Notice("Embedding model saved. Enable Semantic Search to build the index.")}};return tn.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=>{new kke(app,async()=>{Ue("enableSemanticSearchV3",r),r&&await(await Promise.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
/*! Bundled license information:
@langchain/core/dist/utils/fast-json-patch/src/helpers.js:
(*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2017-2022 Joachim Wester
* MIT licensed
*)
@langchain/core/dist/utils/sax-js/sax.js:
(*! http://mths.be/fromcodepoint v0.1.0 by @mathias *)
mustache/mustache.mjs:
(*!
* mustache.js - Logic-less {{mustache}} templates with JavaScript
* http://github.com/janl/mustache.js
*)
react/cjs/react.production.min.js:
(**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
moment/moment.js:
(*! moment.js *)
(*! version : 2.29.4 *)
(*! authors : Tim Wood, Iskren Chernev, Moment.js contributors *)
(*! license : MIT *)
(*! momentjs.com *)
ieee754/index.js:
(*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)
buffer/index.js:
(*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*)
scheduler/cjs/scheduler.production.min.js:
(**
* @license React
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
react-dom/cjs/react-dom.production.min.js:
(**
* @license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
react/cjs/react-jsx-runtime.production.min.js:
(**
* @license React
* react-jsx-runtime.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/shared/src/utils.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/defaultAttributes.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/Icon.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/createLucideIcon.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/arrow-big-up.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/arrow-right.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/arrow-up-right.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/bot.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/brain.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/check.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/chevron-down.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/chevron-right.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/chevron-up.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/circle-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/circle-check-big.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/circle-check.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/circle-dashed.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/circle-help.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/circle-plus.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/circle-stop.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/circle-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/circle.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/cog.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/coins.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/command.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/copy.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/corner-down-left.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/cpu.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/database.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/download.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/ellipsis-vertical.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/ellipsis.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/external-link.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/eye-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/eye.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/file-audio.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/file-clock.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/file-image.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/file-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/file-output.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/file-text.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/file-video.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/file.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/folder.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/globe.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/grip-vertical.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/hash.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/history.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/image.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/info.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/key.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/library-big.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/lightbulb.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/loader-circle.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/message-circle-plus.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/message-circle.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/message-square.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/pen-line.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/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/pencil-line.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/pencil.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/plus.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/refresh-ccw.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/refresh-cw.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/rotate-ccw.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/rotate-cw.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/search.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/settings.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/sparkles.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/square-arrow-out-up-right.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/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
* limitations under the License.
*)
*/
/* nosourcemap */