Files

2937 lines
5.0 MiB
JavaScript
Raw Permalink Normal View History

2025-10-25 20:35:10 +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 _sn=Object.create;var cY=Object.defineProperty;var vsn=Object.getOwnPropertyDescriptor;var wsn=Object.getOwnPropertyNames;var Ssn=Object.getPrototypeOf,Csn=Object.prototype.hasOwnProperty;var Wwt=t=>{throw TypeError(t)};var xsn=(t,e,r)=>e in t?cY(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),Xn=(t,e)=>{for(var r in e)cY(t,r,{get:e[r],enumerable:!0})},Gwt=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of wsn(e))!Csn.call(t,o)&&o!==r&&cY(t,o,{get:()=>e[o],enumerable:!(n=vsn(e,o))||n.enumerable});return t};var L=(t,e,r)=>(r=t!=null?_sn(Ssn(t)):{},Gwt(e||!t||!t.__esModule?cY(r,"default",{value:t,enumerable:!0}):r,t)),Nfe=t=>Gwt(cY({},"__esModule",{value:!0}),t);var M=(t,e,r)=>xsn(t,typeof e!="symbol"?e+"":e,r),Osn=(t,e,r)=>e.has(t)||Wwt("Cannot "+r);var dY=(t,e,r)=>e.has(t)?Wwt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r);var Zwt=(t,e,r)=>(Osn(t,e,"access private method"),r);function nke(){if(!jfe&&(jfe=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!jfe))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return jfe(Tsn)}var jfe,Tsn,Xwt=v(()=>{Tsn=new Uint8Array(16)});function Ywt(t,e=0){return Hh[t[e+0]]+Hh[t[e+1]]+Hh[t[e+2]]+Hh[t[e+3]]+"-"+Hh[t[e+4]]+Hh[t[e+5]]+"-"+Hh[t[e+6]]+Hh[t[e+7]]+"-"+Hh[t[e+8]]+Hh[t[e+9]]+"-"+Hh[t[e+10]]+Hh[t[e+11]]+Hh[t[e+12]]+Hh[t[e+13]]+Hh[t[e+14]]+Hh[t[e+15]]}var Hh,Qwt=v(()=>{Hh=[];for(let t=0;t<256;++t)Hh.push((t+256).toString(16).slice(1))});var Esn,oke,eSt=v(()=>{Esn=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),oke={randomUUID:Esn}});function Psn(t,e,r){if(oke.randomUUID&&!e&&!t)return oke.randomUUID();t=t||{};let n=t.random||(t.rng||nke)();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 Ywt(n)}var H0,tSt=v(()=>{eSt();Xwt();Qwt();H0=Psn});var J3=v(()=>{tSt()});var Msn,Et,Do=v(()=>{Msn=Object.defineProperty,Et=(t,e)=>{for(var r in e)Msn(t,r,{get:e[r],enumerable:!0})}});function fY(t,e=UU){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 UU(t){if(typeof t>"u")return null;try{return JSON.parse(t)}catch{}let e="",r=[],n=!1,o=!1;for(let i of t){if(n)i==='"'&&!o?n=!1:i===`
`&&!o?i="\\n":i==="\\"?o=!o:o=!1;else if(i==='"')n=!0,o=!1;else if(i==="{")r.push("}");else if(i==="[")r.push("]");else if(i==="}"||i==="]")if(r&&r[r.length-1]===i)r.pop();else return null;e+=i}n&&(e+='"');for(let i=r.length-1;i>=0;i-=1)e+=r[i];try{return JSON.parse(e)}catch{return null}}var pY=v(()=>{});function H$(t,e){return t.lc_error_code=e,t.message=`${t.message}
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
`,t}var mY=v(()=>{});var nSt=S((mgi,rSt)=>{"use strict";rSt.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 cSt=S((hgi,ike)=>{"use strict";var Rsn=/[\p{Lu}]/u,Asn=/[\p{Ll}]/u,oSt=/^[\p{Lu}](?![\p{Lu}])/gu,sSt=/([\p{Alpha}\p{N}_]|$)/u,uSt=/[_.\- ]+/,Isn=new RegExp("^"+uSt.source),iSt=new RegExp(uSt.source+sSt.source,"gu"),aSt=new RegExp("\\d+"+sSt.source,"gu"),Nsn=(t,e,r)=>{let n=!1,o=!1,i=!1;for(let a=0;a<t.length;a++){let s=t[a];n&&Rsn.test(s)?(t=t.slice(0,a)+"-"+t.slice(a),n=!1,i=o,o=!0,a++):o&&i&&Asn.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},jsn=(t,e)=>(oSt.lastIndex=0,t.replace(oSt,r=>e(r))),Dsn=(t,e)=>(iSt.lastIndex=0,aSt.lastIndex=0,t.replace(iSt,(r,n)=>e(n)).replace(aSt,r=>e(r))),lSt=(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=Nsn(t,r,n)),t=t.replace(Isn,""),e.preserveConsecutiveUppercase?t=jsn(t,r):t=r(t),e.pascalCase&&(t=n(t.charAt(0))+t.slice(1)),Dsn(t,n))};ike.exports=lSt;ike.exports.default=lSt});function fSt(t,e){return e?.[t]||(0,dSt.default)(t)}function pSt(t,e,r){let n={};for(let o in t)Object.hasOwn(t,o)&&(n[e(o,r)]=t[o]);return n}var dSt,$sn,mSt=v(()=>{dSt=L(nSt(),1),$sn=L(cSt(),1)});function hSt(t){return Array.isArray(t)?[...t]:{...t}}function Fsn(t,e){let r=hSt(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]=hSt(s[u]),s=s[u]}s[i]!==void 0&&(s[i]={lc:1,type:"secret",id:[o]})}return r}function Dfe(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 Lsn,Vh,V$=v(()=>{Do();mSt();Lsn={};Et(Lsn,{Serializable:()=>Vh,get_lc_unique_name:()=>Dfe});Vh=class gSt{constructor(e,...r){M(this,"lc_serializable",!1);M(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,Dfe(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 gSt||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let e={},r={},n=Object.keys(this.lc_kwargs).reduce((o,i)=>(o[i]=i in this?this[i]:this.lc_kwargs[i],o),{});for(let o=Object.getPrototypeOf(this);o;o=Object.getPrototypeOf(o))Object.assign(e,Reflect.get(o,"lc_aliases",this)),Object.assign(r,Reflect.get(o,"lc_secrets",this)),Object.assign(n,Reflect.get(o,"lc_attributes",this));return Object.keys(r).forEach(o=>{let i=this,a=n,[s,...u]=o.split(".").reverse();for(let l of u.reverse()){if(!(l in i)||i[l]===void 0)return;(!(l in a)||a[l]===void 0)&&(typeof i[l]=="object"&&i[l]!=null?a[l]={}:Array.isArray(i[l])&&(a[l]=[])),i=i[l],a=a[l]}s in i&&i[s]!==void 0&&(a[s]=a[s]||i[s])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:pSt(Object.keys(r).length?Fsn(n,r):n,fSt,e)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}}});function J$(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="tool_call")}function ySt(t){return!!(t&&typeof t=="object"&&"toolCall"in t&&t.toolCall!=null&&typeof t.toolCall=="object"&&"id"in t.toolCall&&typeof t.toolCall.id=="string")}var K3,$fe=v(()=>{K3=class extends Error{constructor(e,r){super(e);M(this,"ou
Left ${typeof t}
Right ${typeof e}`);if(typeof t=="string"&&typeof e=="string")return t+e;if(Array.isArray(t)&&Array.isArray(e))return HU(t,e);if(typeof t=="object"&&typeof e=="object")return xl(t,e);if(t===e)return t;throw new Error(`Can not merge objects of different types.
Left ${t}
Right ${e}`)}function Hfe(t){return typeof t.role=="string"}function Xm(t){return typeof t?._getType=="function"}function Z3(t){return Xm(t)&&typeof t.concat=="function"}var dke,RSt,Jc,Wb,Vg=v(()=>{V$();yY();ske();uke();lke();cke();dke=Symbol.for("langchain.message");Jc=class extends Vh{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);M(this,"lc_namespace",["langchain_core","messages"]);M(this,"lc_serializable",!0);M(this,RSt,!0);M(this,"id");M(this,"name");M(this,"content");M(this,"additional_kwargs");M(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[OSt,qfe,CSt].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&&dke in e&&e[dke]===!0&&Bfe(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[(RSt=dke,Symbol.toStringTag)](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;let r=Jsn(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${r}`}};Wb=class extends Jc{static isInstance(t){return super.isInstance(t)&&"concat"in t&&typeof t.concat=="function"}}});function bY(t){return t!=null&&typeof t=="object"&&"lc_direct_tool_output"in t&&t.lc_direct_tool_output===!0}function _Y(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 vY(t){return typeof t=="object"&&t!==null&&"getType"in t&&typeof t.getType=="function"&&t.getType()==="tool"}function fke(t){return t._getType()==="tool"}var Ksn,Gb,Aw,X3=v(()=>{Do();Vg();Ksn={};Et(Ksn,{ToolMessage:()=>Gb,ToolMessageChunk:()=>Aw,defaultToolCallParser:()=>_Y,isDirectToolOutput:()=>bY,isToolMessage:()=>vY,isToolMessageChunk:()=>fke});Gb=class extends Jc{constructor(e,r,n){let o=typeof e=="string"||Array.isArray(e)?{content:e,name:n,tool_call_id:r}:e;super(o);M(this,"lc_direct_tool_output",!0);M(this,"type","tool");M(this,"status");M(this,"tool_call_id");M(this,"metadata");M(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}}},Aw=class extends Wb{constructor(e){super(e);M(this,"type","tool");M(this,"tool_call_id");M(this,"status");M(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:Kb(this.content,e.content),additional_kwargs:xl(this.additional_kwargs,e.additional_kwargs),response_metadata:xl(this.response_metadata,e.response_metadata),artifact:zfe(this.a
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]=_Y(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.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);M(this,"type","ai");M(this,"tool_calls",[]);M(this,"invalid_tool_calls",[]);M(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=mke(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=>({...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"}};Ur=class extends Wb{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)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=e.tool_call_chunks.reduce((a,s)=>{let u=a.findIndex(([l])=>"id"in s&&s.id&&"index"in s&&s.index!==void 0?s.id===l.id&&s.index===l.index:"id"in s&&s.id?s.id===l.id:"index"in s&&s.index!==void 0?s.index===l.index:!1);return u!==-1?a[u].push(s):a.push([s]),a},[]),o=[],i=[];for(let a of n){let s=null,u=a[0]?.name??"",l=a.map(f=>f.args||"").join(""),c=l.length?l:"{}",d=a[0]?.id;try{if(s=UU(c),!d||s===null||typeof s!="object"||Array.isArray(s))throw new Error("Malformed tool call chunk args.");o.push({name:u,args:s,id:d,type:"tool_call"})}catch{i.push({name:u,args:c,id:d,error:"Malformed args.",type:"invalid_tool_call"})}}r={...e,tool_calls:o,invalid_tool_calls:i,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(r);M(this,"type","ai");M(this,"tool_calls",[]);M(this,"invalid_tool_calls",[]);M(this,"tool_call_chunks",[]);M(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=mke(this.response_metadata.model_provider);if(r)return r.translateContent(this)}le
Received: ${JSON.stringify(t,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Iw(t){if(typeof t=="string")return new su(t);if(Xm(t))return t;if(Array.isArray(t)){let[e,r]=t;return gke({type:e,content:r})}else if(Hfe(t)){let{role:e,...r}=t;return gke({...r,type:e})}else return gke(t)}function rl(t,e="Human",r="AI"){let n=[];for(let o of t){let i;if(o._getType()==="human")i=e;else if(o._getType()==="ai")i=r;else if(o._getType()==="system")i="System";else if(o._getType()==="tool")i="Tool";else if(o._getType()==="generic")i=o.role;else throw new Error(`Got unsupported message type: ${o._getType()}`);let a=o.name?`${o.name}, `:"",s=typeof o.content=="string"?o.content:JSON.stringify(o.content,null,2);n.push(`${i}: ${a}${s}`)}return n.join(`
`)}function tun(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 xY(t){let e=tun(t);switch(e.type){case"human":return new su(e.data);case"ai":return new li(e.data);case"system":return new Ym(e.data);case"function":if(e.data.name===void 0)throw new Error("Name must be defined for function messages");return new VU(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 Gb(e.data);case"generic":if(e.data.role===void 0)throw new Error("Role must be defined for chat messages");return new cd(e.data);default:throw new Error(`Got unexpected type: ${e.type}`)}}function QSt(t){return t.map(xY)}function e0t(t){return t.map(e=>e.toDict())}function KU(t){let e=t._getType();if(e==="human")return new _v({...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 Ur({...r})}else{if(e==="system")return new Ky({...t});if(e==="function")return new bv({...t});if(cd.isInstance(t))return new yv({...t});throw new Error("Unknown message type.")}}var YSt,iO=v(()=>{Vg();X3();V0();SY();Kfe();G$();CY();mY();$fe();Wfe();YSt=t=>t()});function _ke(){return yke===void 0&&(yke={library:"langchain-js",runtime:bke()}),yke}function gn(t){try{return typeof process<"u"?process.env?.[t]:Gfe()?Deno?.env.get(t):void 0}catch{return}}var run,t0t,r0t,n0t,Gfe,o0t,bke,yke,nl=v(()=>{Do();run={};Et(run,{getEnv:()=>bke,getEnvironmentVariable:()=>gn,getRuntimeEnvironment:()=>_ke,isBrowser:()=>t0t,isDeno:()=>Gfe,isJsDom:()=>n0t,isNode:()=>o0t,isWebWorker:()=>r0t});t0t=()=>typeof window<"u"&&typeof window.document<"u",r0t=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",n0t=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),Gfe=()=>typeof Deno<"u",o0t=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Gfe(),bke=()=>{let t;return t0t()?t="browser":o0t()?t="node":r0t()?t="webworker":n0t()?t="jsdom":Gfe()?t="deno":t="other",t}});var i0t,a0t=v(()=>{i0t=/^(?:[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 nun(t){return typeof t=="string"&&i0t.test(t)}var Y3,s0t=v(()=>{a0t();Y3=nun});function u0t(t,e=0){return(Jh[t[e+0]]+Jh[t[e+1]]+Jh[t[e+2]]+Jh[t[e+3]]+"-"+Jh[t[e+4]]+Jh[t[e+5]]+"-"+Jh[t[e+6]]+Jh[t[e+7]]+"-"+Jh[t[e+8]]+Jh[t[e+9]]+"-"+Jh[t[e+10]]+Jh[t[e+11]]+Jh[t[e+12]]+Jh[t[e+13]]+Jh[t[e+14]]+Jh[t[e+15]]).toLowerCase()}var Jh,Zfe,l0t=v(()=>{Jh=[];for(Zfe=0;Zfe<256;++Zfe)Jh.push((Zfe+256).toString(16).slice(1))});function vke(){if(!Xfe&&(Xfe=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Xfe))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Xfe(oun)}var Xfe,oun,c0t=v(()=>{oun=new Uint8Array(16)});var iun,wke,d0t=v(()=>{iun=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),wke={randomUUID:iun}});function aun(t,e,r){if(wke.randomUUID&&!e&&!t)return wke.randomUUID();t=t||{};var n=t.random||(t.rng||vke)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){r=r||0;for(var o=0;o<16;++o)e[r+o]=n[o];return e}return u0t(n)}var Zb,f0t=v(()=>{d0t();c0t();l0t();Zb=aun});var OY=v(()=>{f0t();s0t()});function TY(t){return"lc_prefer_streaming"in t&&t.lc_prefer_streaming}var uun,lun,WU,Ske,EY=v(()=>{Do();V$();nl();OY();uun={};Et(uun,{BaseCallbackHandler:()=>WU,callbackHandlerPrefersStreaming:()=>TY,isBaseCallbackHandler:()=>Ske});lun=class{};WU=class extends lun{constructor(e){super();M(this,"lc_serializable",!1);M(this,"lc_kwargs");M(this,"ignoreLLM",!1);M(this,"ignoreChain",!1);M(this,"ignoreAgent",!1);M(this,"ignoreRetriever",!1);M(this,"ignoreCustomEvent",!1);M(this,"raiseError",!1);M(this,"awaitHandlers",gn("LANGCHAIN_CALLBA
Context: ${e}`:""}`),Mpe("[Unserializable]");dd("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
Context: ${e}`:""}`),typeof o>"u"&&(o=Kdn()),Mqe(t,"",0,[],void 0,0,o);let a;try{e6.length===0?a=JSON.stringify(t,r,n):a=JSON.stringify(t,Gdn(r),n)}catch{return Mpe("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Rpe.length!==0;){let s=Rpe.pop();s.length===4?Object.defineProperty(s[0],s[1],s[3]):s[0][s[1]]=s[2]}}return Mpe(a)}}function Pqe(t,e,r,n){var o=Object.getOwnPropertyDescriptor(n,r);o.get!==void 0?o.configurable?(Object.defineProperty(n,r,{value:t}),Rpe.push([n,r,e,o])):e6.push([e,r,t]):(n[r]=t,Rpe.push([n,r,e]))}function Mqe(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){Pqe(Vdn,t,e,o);return}if(typeof a.depthLimit<"u"&&i>a.depthLimit){Pqe(wOt,t,e,o);return}if(typeof a.edgesLimit<"u"&&r+1>a.edgesLimit){Pqe(wOt,t,e,o);return}if(n.push(t),Array.isArray(t))for(s=0;s<t.length;s++)Mqe(t[s],s,s,n,t,i,a);else{t=SOt(t);var u=Object.keys(t);for(s=0;s<u.length;s++){var l=u[s];Mqe(t[l],l,s,n,t,i,a)}}n.pop()}}function Gdn(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(e6.length>0)for(var n=0;n<e6.length;n++){var o=e6[n];if(o[1]===e&&o[0]===r){r=o[2],e6.splice(n,1);break}}return t.call(this,e,r)}}var wOt,Vdn,Rpe,e6,Jdn,COt=v(()=>{sN();wOt="[...]",Vdn={result:"[Circular]"},Rpe=[],e6=[],Jdn=new TextEncoder});function xOt(t,e){let r=ope(),n=e??Bke(),o=t.extra??{},i=o.metadata;return t.extra={...o,runtime:{...r,...o?.runtime},metadata:{...n,...n.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??n.revision_id}:{},...i}},t}async function Ydn(t){let e=[];for await(let r of t)e.push(r);return e}function Ape(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}function OOt(t){return typeof t=="number"?Number(t.toFixed(4)):t}function EOt(t){return"dataset_id"in t||"dataset_name"in t}var Zdn,Xdn,Qdn,Rqe,efn,tfn,rfn,TOt,GU,$ke=v(()=>{Pke();lCt();Gke();OCt();TCt();sN();npe();ECt();aqe();bOt();Eqe();jke();COt();Zdn=t=>{let e=t?.toString()??dd("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},Xdn=t=>{let r=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"};Qdn=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};Rqe=class{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(e){let r,n=new Promise(i=>{r=i}),o=Xb(e.item,`Serializing run with id: ${e.item.id}`).length;return this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:r,itemPromise:n,size:o}),this.sizeBytes+=o,n}pop({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})),()=>n.forEach(i=>i.itemPromiseResolve())]}},efn=24*1024*1024,tfn=1e4,rfn=100,TOt="https://api.smith.langchain.com",GU=class t{get _fetch(){return this.fetchImplementation||oCt(this.debug)}constructor(e={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}
=== 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=ape(),r=sCt();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=xOt(i,this.cachedLSEnvVarsForMetadata);r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(n["x-tenant-id"]=r.workspaceId);let s=Xb(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 Fr(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(Xb(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.call(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 Fr(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",a]])for(let p of f){let{inputs:m,outputs:h,events:g,extra:y,err
`])),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=nCt(),a=()=>this._createNodeFetchBody(e,o),s=()=>this._createMultipartStream(e,o),u=async l=>this.batchIngestCaller.call(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 Fr(p,"Failed to send multipart request",!0),p});try{let l,c=!1;!i&&!this.multipartStreamingDisabled&&qke()!=="bun"?(c=!0,l=await u(s)):l=await u(a),(!this.multipartStreamingDisabled||c)&&l.status===422&&(n?.apiUrl??this.apiUrl)!==TOt&&(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){console.warn(`${l.message.trim()}
Context: ${r}`)}}async updateRun(e,r,n){To(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=Xb(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 Fr(s,"update run",!0),s})}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){To(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:dd("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 Ydn(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:g,limit:y,select:b,order:_}=e,w=[];if(r&&(w=Array.isArray(r)?r:[r]),n){let T=Array.isArray(n)?n:[n],R=await Promise.all(T.map(N=>this.readProject({projectName:N}).then(D=>D.id)));w.push(...R)}let x=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],O={session:w.length?w:null,run_type:c,reference_example:a,query:p,filter:m,trace_filter:h,tree_filter:g,execution_order:u,parent_run:o,start_time:s?s.toISOString():null,error:d,id:f,limit:y,trace:i,select:b||x,is_root:l,order:_};O.select.includes("child_run_ids")&&AY("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let E=0;for await(let T of this._getCursorPaginatedList("/runs/query",O))if(y){if(E>=y)break;if(T.length+E>y){yield*T.slice(0,y-E);break}E+=T.length,yield*T}else yield*T}async*listGroupRuns(e){let{projectId:r,projectName:n,groupBy:o,filter:i,startTime:a,endTime:s,limit:u,offset:l}=e,d={session_id:r||(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},g
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 Fr(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 Fr(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)To(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 Fr(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)To(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;To(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 Fr(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;To(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 Fr(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)To(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 Fr(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),To(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 Fr(u,"index dataset"),u})).json()}async similarExamples(e,r,n,{filter:o}={}){let i={limit:n,inputs:e};o!==void 0&&(i.filter=o),To(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 Fr(l,"fetch similar examples"),l})).json()).examples}async createExample(e,r,n){if(EOt(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;EOt(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]??aN())}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 Fr(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]=uN(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 Fr(u,`${r?"like":"unlike"} prompt`),u})).json()}async _getPromptUrl(e){let[r,n,o]=uN(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]=uN(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 Fr(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]=uN(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 Fr(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]=uN(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 Fr(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=Xb(u,`Serializing body for example with id: ${s}`),c=new Blob([l],{type:"application/json"});if(n.append(s,c),a.inputs){let d=Xb(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=Xb(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=Xb(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 Fr(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??aN()).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=Xb(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=Xb(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=Xb(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}=Aqe(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.trace_id=o.id,o.dotted_order=r,o._serialized_start_time=n),this.usesRunTreeMap){let a=Nqe(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){let l=this._getExecutionOrder(o),c=Date.now(),d={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:r,execution_order:l,child_execution_order:l,run_type:s??"chain",child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(d)}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=Iqe(e,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=Iqe(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=Iqe(i.inputs,"input")),await this.onChainError?.(a),await this._endTrace(a),a}_createRunFo
Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function Fpe(t){return typeof t=="function"&&"langsmith:traceable"in t}var Fqe,Lqe,mfn,kqe,hfn,owi,BOt=v(()=>{Fqe=class{getStore(){}run(e,r){return r()}},Lqe=Symbol.for("ls:tracing_async_local_storage"),mfn=new Fqe,kqe=class{getInstance(){return globalThis[Lqe]??mfn}initializeGlobalInstance(e){globalThis[Lqe]===void 0&&(globalThis[Lqe]=e)}},hfn=new kqe;owi=Symbol.for("langsmith:traceable:root")});var qqe=v(()=>{BOt()});var gfn,kY,zOt=v(()=>{Do();QU();$qe();qqe();jpe();$pe();gfn={};Et(gfn,{LangChainTracer:()=>kY});kY=class UOt extends K0{constructor(r={}){super(r);M(this,"name","langchain_tracer");M(this,"projectName");M(this,"exampleId");M(this,"client");M(this,"replicas");M(this,"usesRunTreeMap",!0);let{exampleId:n,projectName:o,client:i,replicas:a}=r;this.projectName=o??PY(),this.replicas=a,this.exampleId=n,this.client=i??Lpe();let s=UOt.getTraceableRunTree();s&&this.updateFromRunTree(s)}async persistRun(r){}async onRunCreate(r){await this.getRunTreeWithTracingConfig(r.id)?.postRun()}async onRunUpdate(r){await this.getRunTreeWithTracingConfig(r.id)?.patchRun()}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 J0({...n,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return qOt(!0)}catch{return}}}});var VOt=S((gwi,qpe)=>{"use strict";var yfn=Yke(),kpe=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},HOt=(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 kpe(a);typeof t.cancel=="function"&&t.cancel(),o(s)},e);yfn(t.then(n,o),()=>{clearTimeout(i)})});qpe.exports=HOt;qpe.exports.default=HOt;qpe.exports.TimeoutError=kpe});var JOt=S(Bqe=>{"use strict";Object.defineProperty(Bqe,"__esModule",{value:!0});function bfn(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}Bqe.default=bfn});var KOt=S(zqe=>{"use strict";Object.defineProperty(zqe,"__esModule",{value:!0});var _fn=JOt(),Uqe=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=_fn.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}};zqe.default=Uqe});var Jqe=S(Vqe=>{"use strict";Object.defineProperty(Vqe,"__esModule",{value:!0});var vfn=Xke(),WOt=VOt(),wfn=KOt(),Bpe=()=>{},Sfn=new WOt.TimeoutError,Hqe=class extends vfn{constructor(e){var r,n,o,i;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=Bpe,this._resolveIdle=Bpe,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:wfn.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=e.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.i
`)}var Nfn,Zpe,Xpe=v(()=>{Nfn=Object.prototype.hasOwnProperty;Zpe=class extends Error{constructor(t,e,r,n,o){super(aTt(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=aTt(t,{name:e,index:r,operation:n,tree:o})}}});function Ype(t,e){if(e=="")return t;var r={op:"_get",path:e};return oz(t,r),r.value}function oz(t,e,r=!1,n=!0,o=!0,i=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):Qpe(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=Ype(t,e.from),e.op==="move"&&(a.removed=t),a;if(e.op==="test"){if(a.test=zY(t,e.value),a.test===!1)throw new Oc("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 Oc("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=Qpe;;){if(f=s[l],f&&f.indexOf("~")!=-1&&(f=Gpe(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&&!Wpe(f))throw new Oc("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);Wpe(f)&&(f=~~f)}if(l>=c){if(r&&e.op==="add"&&f>u.length)throw new Oc("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=Dfn[e.op].call(e,u,f,t);if(m.test===!1)throw new Oc("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return m}}else if(l>=c){let m=r6[e.op].call(e,u,f,t);if(m.test===!1)throw new Oc("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return m}if(u=u[f],r&&l<c&&(!u||typeof u!="object"))throw new Oc("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function eL(t,e,r,n=!0,o=!0){if(r&&!Array.isArray(e))throw new Oc("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]=oz(t,e[a],r,!0,o,a),t=i[a].newDocument;return i.newDocument=t,i}function $fn(t,e,r){let n=oz(t,e);if(n.test===!1)throw new Oc("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function Qpe(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new Oc("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(r6[t.op]){if(typeof t.path!="string")throw new Oc("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new Oc('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 Oc("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 Oc("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")&&Vpe(t.value))throw new Oc("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.split("/").length,i=n.split("/").length;if(o!==i+1&&o!==i)throw new Oc("Cannot pe
`)}var vTt,tQ,s6,vBe=v(()=>{o6();In();vTt=(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,lBe,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},tQ=we("$ZodError",vTt),s6=we("$ZodError",vTt,{Parent:Error})});var ime,pO,ame,uz,sme,wBe,ume,SBe,lme=v(()=>{o6();vBe();In();ime=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 fO;if(a.issues.length){let s=new(o?.Err??t)(a.issues.map(u=>wv(u,i,fd())));throw ome(s,o?.callee),s}return a.value},pO=ime(s6),ame=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=>wv(u,i,fd())));throw ome(s,o?.callee),s}return a.value},uz=ame(s6),sme=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 fO;return i.issues.length?{success:!1,error:new(t??tQ)(i.issues.map(a=>wv(a,o,fd())))}:{success:!0,data:i.value}},wBe=sme(s6),ume=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=>wv(a,o,fd())))}:{success:!0,data:i.value}},SBe=ume(s6)});var cz={};Xn(cz,{_emoji:()=>STt,base64:()=>LBe,base64url:()=>cme,bigint:()=>HBe,boolean:()=>KBe,browserEmail:()=>hpn,cidrv4:()=>DBe,cidrv6:()=>$Be,cuid:()=>CBe,cuid2:()=>xBe,date:()=>qBe,datetime:()=>UBe,domain:()=>gpn,duration:()=>MBe,e164:()=>kBe,email:()=>ABe,emoji:()=>IBe,extendedDuration:()=>upn,guid:()=>RBe,hostname:()=>FBe,html5Email:()=>fpn,integer:()=>VBe,ipv4:()=>NBe,ipv6:()=>jBe,ksuid:()=>EBe,lowercase:()=>ZBe,nanoid:()=>PBe,null:()=>WBe,number:()=>JBe,rfc5322Email:()=>ppn,string:()=>zBe,time:()=>BBe,ulid:()=>OBe,undefined:()=>GBe,unicodeEmail:()=>mpn,uppercase:()=>XBe,uuid:()=>lz,uuid4:()=>lpn,uuid6:()=>cpn,uuid7:()=>dpn,xid:()=>TBe});function IBe(){return new RegExp(STt,"u")}function xTt(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 BBe(t){return new RegExp(`^${xTt(t)}$`)}function UBe(t){let e=xTt({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(`^${CTt}T(?:${n})$`)}var CBe,xBe,OBe,TBe,EBe,PBe,MBe,upn,RBe,lz,lpn,cpn,dpn,ABe,fpn,ppn,mpn,hpn,STt,NBe,jBe,DBe,$Be,LBe,cme,FBe,gpn,kBe,CTt,qBe,zBe,HBe,VBe,JBe,KBe,WBe,GBe,ZBe,XBe,dme=v(()=>{CBe=/^[cC][^\s-]{8,}$/,xBe=/^[0-9a-z]+$/,OBe=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,TBe=/^[0-9a-vA-V]{20}$/,EBe=/^[A-Za-z0-9]{27}$/,PBe=/^[a-zA-Z0-9_-]{21}$/,MBe=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,upn=/^[-+]?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)?)??$/,RBe=/^([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})$/,lz=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)$/,lpn=lz(4),cpn=lz(6),dpn=lz(7),ABe=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,fpn=/^[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])?)*$/,ppn=/^(([^<>()\[\]\\.,;:\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 yUe,bUe=v(()=>{yUe={major:4,minor:0,patch:0}});function kUe(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function kTt(t){if(!cme.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return kUe(r)}function qTt(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 PTt(t,e,r){t.issues.length&&e.issues.push(...Qb(r,t.issues)),e.value[r]=t.value}function hme(t,e,r){t.issues.length&&e.issues.push(...Qb(r,t.issues)),e.value[r]=t.value}function MTt(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(...Qb(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function RTt(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=>wv(i,n,fd())))}),e}function _Ue(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(a6(t)&&a6(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=_Ue(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=_Ue(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 ATt(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),sz(t))return t;let n=_Ue(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 gme(t,e,r){t.issues.length&&e.issues.push(...Qb(r,t.issues)),e.value[r]=t.value}function ITt(t,e,r,n,o,i,a){t.issues.length&&(YY.has(typeof n)?r.issues.push(...Qb(n,t.issues)):r.issues.push({origin:"map",code:"invalid_key",input:o,inst:i,issues:t.issues.map(s=>wv(s,a,fd()))})),e.issues.length&&(YY.has(typeof n)?r.issues.push(...Qb(n,e.issues)):r.issues.push({origin:"map",code:"invalid_element",input:o,inst:i,key:n,issues:e.issues.map(s=>wv(s,a,fd()))})),r.value.set(t.value,e.value)}function NTt(t,e){t.issues.length&&e.issues.push(...t.issues),e.value.add(t.value)}function jTt(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function DTt(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 $Tt(t,e,r){return sz(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function LTt(t){return t.value=Object.freeze(t.value),t}function FTt(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(yBe(o))}}var Yn,dz,Cu,vUe,wUe,SUe,CUe,xUe,OUe,TUe,EUe,PUe,MUe,RUe,AUe,IUe,NUe,jUe,DUe,$Ue,LUe,FUe,qUe,BUe,UUe,zUe,HUe,yme,VUe,iQ,bme,JUe,KUe,WUe,GUe,ZUe,rL,aQ,XUe,YUe,sQ,QUe,_me,eze,tze,fz,rze,nze,oze,ize,aze,sze,uQ,l6,uze,lze,cze,dze,fze,pze,mze,lQ,hze,gze,yze,bze,_ze,cQ=v(()=>{mme();o6();gUe();lme();dme();In();bUe();In();Yn=we("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=yUe;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=sz(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 fO;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 ? [${az(b)}, ...iss.path] : [${az(b)}]
})));`),f.write(`newResult[${az(b)}] = ${_}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let y=f.compile();return(b,_)=>y(d,b,_)},o,i=i6,a=!KY.jitless,u=a&&fBe.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 x=_[w],O=x._zod.run({value:p[w],issues:[]},f),E=x._zod.optin==="optional"&&x._zod.optout==="optional";O instanceof Promise?m.push(O.then(T=>E?MTt(T,d,w,p):hme(T,d,w))):E?MTt(O,d,w,p):hme(O,d,w)}}if(!l)return m.length?Promise.all(m).then(()=>d):d;let h=[],g=c.keySet,y=l._zod,b=y.def.type;for(let _ of Object.keys(p)){if(g.has(_))continue;if(b==="never"){h.push(_);continue}let w=y.run({value:p[_],issues:[]},f);w instanceof Promise?m.push(w.then(x=>hme(x,d,_))):hme(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}});_me=we("$ZodUnion",(t,e)=>{Yn.init(t,e),Ds(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Ds(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Ds(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Ds(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=>XY(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=>RTt(a,r,t,n)):RTt(i,r,t,n)}}),eze=we("$ZodDiscriminatedUnion",(t,e)=>{_me.init(t,e);let r=t._zod.parse;Ds(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=ZY(()=>{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(!i6(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)}}),tze=we("$ZodIntersection",(t,e)=>{Yn.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])=>ATt(r,u,l)):ATt(r,i,a)}});fz=we("$ZodTuple",(t,e)=>{Yn.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=>gme(d,o,u))):gme(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=>gme(f,o,u))):gme(d,o,u)}}return s.length?Promise.all(s).then(()=>o):o}});rze=we("$ZodRecord",(t,e)=>{Yn.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!a6(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 g=this.seen.get(h).schema;g.$ref&&d.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(g)):(Object.assign(p,g),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 mPt={};var hPt=v(()=>{});var gN={};Xn(gN,{$ZodAny:()=>ZUe,$ZodArray:()=>sQ,$ZodAsyncError:()=>fO,$ZodBase64:()=>qUe,$ZodBase64URL:()=>BUe,$ZodBigInt:()=>bme,$ZodBigIntFormat:()=>JUe,$ZodBoolean:()=>iQ,$ZodCIDRv4:()=>LUe,$ZodCIDRv6:()=>FUe,$ZodCUID:()=>TUe,$ZodCUID2:()=>EUe,$ZodCatch:()=>pze,$ZodCheck:()=>Ql,$ZodCheckBigIntFormat:()=>eUe,$ZodCheckEndsWith:()=>fUe,$ZodCheckGreaterThan:()=>pme,$ZodCheckIncludes:()=>cUe,$ZodCheckLengthEquals:()=>aUe,$ZodCheckLessThan:()=>fme,$ZodCheckLowerCase:()=>uUe,$ZodCheckMaxLength:()=>oUe,$ZodCheckMaxSize:()=>tUe,$ZodCheckMimeType:()=>mUe,$ZodCheckMinLength:()=>iUe,$ZodCheckMinSize:()=>rUe,$ZodCheckMultipleOf:()=>YBe,$ZodCheckNumberFormat:()=>QBe,$ZodCheckOverwrite:()=>hUe,$ZodCheckProperty:()=>pUe,$ZodCheckRegex:()=>sUe,$ZodCheckSizeEquals:()=>nUe,$ZodCheckStartsWith:()=>dUe,$ZodCheckStringFormat:()=>u6,$ZodCheckUpperCase:()=>lUe,$ZodCustom:()=>_ze,$ZodCustomStringFormat:()=>HUe,$ZodDate:()=>YUe,$ZodDefault:()=>lze,$ZodDiscriminatedUnion:()=>eze,$ZodE164:()=>UUe,$ZodEmail:()=>SUe,$ZodEmoji:()=>xUe,$ZodEnum:()=>ize,$ZodError:()=>tQ,$ZodFile:()=>sze,$ZodFunction:()=>zme,$ZodGUID:()=>vUe,$ZodIPv4:()=>DUe,$ZodIPv6:()=>$Ue,$ZodISODate:()=>IUe,$ZodISODateTime:()=>AUe,$ZodISODuration:()=>jUe,$ZodISOTime:()=>NUe,$ZodIntersection:()=>tze,$ZodJWT:()=>zUe,$ZodKSUID:()=>RUe,$ZodLazy:()=>bze,$ZodLiteral:()=>aze,$ZodMap:()=>nze,$ZodNaN:()=>mze,$ZodNanoID:()=>OUe,$ZodNever:()=>aQ,$ZodNonOptional:()=>dze,$ZodNull:()=>GUe,$ZodNullable:()=>uze,$ZodNumber:()=>yme,$ZodNumberFormat:()=>VUe,$ZodObject:()=>QUe,$ZodOptional:()=>l6,$ZodPipe:()=>lQ,$ZodPrefault:()=>cze,$ZodPromise:()=>yze,$ZodReadonly:()=>hze,$ZodRealError:()=>s6,$ZodRecord:()=>rze,$ZodRegistry:()=>c6,$ZodSet:()=>oze,$ZodString:()=>dz,$ZodStringFormat:()=>Cu,$ZodSuccess:()=>fze,$ZodSymbol:()=>KUe,$ZodTemplateLiteral:()=>gze,$ZodTransform:()=>uQ,$ZodTuple:()=>fz,$ZodType:()=>Yn,$ZodULID:()=>PUe,$ZodURL:()=>CUe,$ZodUUID:()=>wUe,$ZodUndefined:()=>WUe,$ZodUnion:()=>_me,$ZodUnknown:()=>rL,$ZodVoid:()=>XUe,$ZodXID:()=>MUe,$brand:()=>aBe,$constructor:()=>we,$input:()=>Cze,$output:()=>Sze,Doc:()=>oQ,JSONSchema:()=>mPt,JSONSchemaGenerator:()=>EQ,NEVER:()=>iBe,TimePrecision:()=>Eze,_any:()=>Wze,_array:()=>TQ,_base64:()=>kme,_base64url:()=>qme,_bigint:()=>Bze,_boolean:()=>kze,_catch:()=>vmn,_cidrv4:()=>Lme,_cidrv6:()=>Fme,_coercedBigint:()=>Uze,_coercedBoolean:()=>qze,_coercedDate:()=>Xze,_coercedNumber:()=>Nze,_coercedString:()=>Tze,_cuid:()=>Rme,_cuid2:()=>Ame,_custom:()=>a4e,_date:()=>Zze,_default:()=>ymn,_discriminatedUnion:()=>amn,_e164:()=>Bme,_email:()=>Sme,_emoji:()=>Pme,_endsWith:()=>vQ,_enum:()=>dmn,_fil
`;return e}function TPt(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 p="default",m={[p]:"{0}({1})"};n!==void 0&&(m[n]="{0}([{1}]):::first"),o!==void 0&&(m[o]="{0}([{1}]):::last");for(let[h,g]of Object.entries(t)){let y=g.name.split(":").pop()??"",_=Pmn.some(x=>y.startsWith(x)&&y.endsWith(x))?`<p>${y}</p>`:y;Object.keys(g.metadata??{}).length&&(_+=`<hr/><small><em>${Object.entries(g.metadata??{}).map(([x,O])=>`${x} = ${O}`).join(`
`)}</em></small>`);let w=(m[h]??m[p]).replace("{0}",m4e(h)).replace("{1}",_);l+=` ${w}
`}}let c={};for(let p of e){let m=p.source.split(":"),h=p.target.split(":"),g=m.filter((y,b)=>y===h[b]).join(":");c[g]||(c[g]=[]),c[g].push(p)}let d=new Set;function f(p,m){let h=p.length===1&&p[0].source===p[0].target;if(m&&!h){let g=m.split(":").pop();if(d.has(g))throw new Error(`Found duplicate subgraph '${g}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(g),l+=` subgraph ${g}
`}for(let g of p){let{source:y,target:b,data:_,conditional:w}=g,x="";if(_!==void 0){let O=_,E=O.split(" ");E.length>u&&(O=Array.from({length:Math.ceil(E.length/u)},(T,R)=>E.slice(R*u,(R+1)*u).join(" ")).join("&nbsp;<br>&nbsp;")),x=w?` -. &nbsp;${O}&nbsp; .-> `:` -- &nbsp;${O}&nbsp; --> `}else x=w?" -.-> ":" --> ";l+=` ${m4e(y)}${x}${m4e(b)};
`}for(let g in c)g.startsWith(`${m}:`)&&g!==m&&f(c[g],g);m&&!h&&(l+=` end
`)}f(c[""]??[],"");for(let p in c)!p.includes(":")&&p!==""&&f(c[p],p);return a&&(l+=Mmn(i??{})),l}async function EPt(t,e){let r=e?.backgroundColor??"white",n=e?.imageType??"png",o=btoa(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 Pmn,PPt=v(()=>{Pmn=["*","_","`"]});var RPt,MPt,APt,Kme=v(()=>{RPt=Symbol("Let zodToJsonSchema decide on which parser to use"),MPt={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"},APt=t=>typeof t=="string"?{...MPt,name:t}:{...MPt,...t}});var IPt,h4e=v(()=>{Kme();IPt=t=>{let e=APt(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 Wme,Gme=v(()=>{Wme=(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 Tl(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Wme(e,t.currentPath):e.join("/")}}var Bw=v(()=>{Gme()});function g4e(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function Di(t,e,r,n,o){t[e]=r,g4e(t,e,n,o)}var cL=v(()=>{});var vi,y4e,nr,mO,MQ=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})(vi||(vi={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(y4e||(y4e={}));nr=vi.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),mO=t=>{switch(typeof t){case"undefined":return nr.undefined;case"string":return nr.string;case"number":return Number.isNaN(t)?nr.nan:nr.number;case"boolean":return nr.boolean;case"function":return nr.function;case"bigint":return nr.bigint;case"symbol":return nr.symbol;case"object":return Array.isArray(t)?nr.array:t===null?nr.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?nr.promise:typeof Map<"u"&&t instanceof Map?nr.map:typeof Set<"u"&&t instanceof Set?nr.set:typeof Date<"u"&&t instanceof Date?nr.date:nr.object;default:return nr.unknown}}});var Xe,Rmn,t_,Zme=v(()=>{MQ();Xe=vi.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"]),Rmn=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),t_=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=e}form
]))`;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 N4e,G0,Uhn,ahe=v(()=>{cL();G0={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:()=>(N4e===void 0&&(N4e=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),N4e),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-_]*$/};Uhn=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function she(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]:xn(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Tl(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:xn(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}=ihe(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}=nhe(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var uhe=v(()=>{Bw();ohe();ahe();pd();yO()});function nMt(t,e){if(e.mapStrategy==="record")return she(t,e);let r=xn(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Tl(e),n=xn(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Tl(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var D4e=v(()=>{Bw();uhe();pd()});function oMt(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(De)}let Te=`${s}/$ref`,Ce=Fu(t,qe,r,n,o,i,a,Te,u);if(Ce.valid||Fe.push({instanceLocation:a,keyword:"$ref",keywordLocation:Te,error:"A subschema had errors."},...Ce.errors),r==="4"||r==="7")return{valid:Fe.length===0,errors:Fe}}if(Array.isArray(m)){let gt=m.length,qe=!1;for(let Te=0;Te<gt;Te++)if(c===m[Te]||m[Te]==="integer"&&c==="number"&&t%1===0&&t===t){qe=!0;break}qe||Fe.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)&&Fe.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m}".`}):m!==void 0&&c!==m&&Fe.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m}".`});if(h!==void 0&&(c==="object"||c==="array"?bO(t,h)||Fe.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):t!==h&&Fe.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),g!==void 0&&(c==="object"||c==="array"?g.some(gt=>bO(t,gt))||Fe.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(gt=>t===gt)||Fe.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),b!==void 0){let gt=`${s}/not`;Fu(t,b,r,n,o,i,a,gt).valid&&Fe.push({instanceLocation:a,keyword:"not",keywordLocation:gt,error:'Instance matched "not" schema.'})}let hn=[];if(_!==void 0){let gt=`${s}/anyOf`,qe=Fe.length,Te=!1;for(let Ce=0;Ce<_.length;Ce++){let De=_[Ce],Re=Object.create(u),nt=Fu(t,De,r,n,o,p===!0?i:null,a,`${gt}/${Ce}`,Re);Fe.push(...nt.errors),Te=Te||nt.valid,nt.valid&&hn.push(Re)}Te?Fe.length=qe:Fe.splice(qe,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:gt,error:"Instance does not match any subschemas."})}if(w!==void 0){let gt=`${s}/allOf`,qe=Fe.length,Te=!0;for(let Ce=0;Ce<w.length;Ce++){let De=w[Ce],Re=Object.create(u),nt=Fu(t,De,r,n,o,p===!0?i:null,a,`${gt}/${Ce}`,Re);Fe.push(...nt.errors),Te=Te&&nt.valid,nt.valid&&hn.push(Re)}Te?Fe.length=qe:Fe.splice(qe,0,{instanceLocation:a,keyword:"allOf",keywordLocation:gt,error:"Instance does not match every subschema."})}if(x!==void 0){let gt=`${s}/oneOf`,qe=Fe.length,Te=x.filter((Ce,De)=>{let Re=Object.create(u),nt=Fu(t,Ce,r,n,o,p===!0?i:null,a,`${gt}/${De}`,Re);return Fe.push(...nt.errors),nt.valid&&hn.push(Re),nt.valid}).length;Te===1?Fe.length=qe:Fe.splice(qe,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:gt,error:`Instance does not match exactly one subschema (${Te} matches).`})}if((c==="object"||c==="array")&&Object.assign(u,...hn),O!==void 0){let gt=`${s}/if`;if(Fu(t,O,r,n,o,i,a,gt,u).valid){if(E!==void 0){let Te=Fu(t,E,r,n,o,i,a,`${s}/then`,u);Te.valid||Fe.push({instanceLocation:a,keyword:"if",keywordLocation:gt,error:'Instance does not match "then" schema.'},...Te.errors)}}else if(T!==void 0){let Te=Fu(t,T,r,n,o,i,a,`${s}/else`,u);Te.valid||Fe.push({instanceLocation:a,keyword:"if",keywordLocation:gt,error:'Instance does not match "else" schema.'},...Te.errors)}}if(c==="object"){if(y!==void 0)for(let Ce of y)Ce in t||Fe.push({instanceLocation:a,keyword:"required",keywordLocation:`${s}/required`,error:`Instance does not have required property "${Ce}".`});let gt=Object.keys(t);if(U!==void 0&&gt.length<U&&Fe.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${U} properties.`}),H!==void 0&&gt.length>H&&Fe.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${H} properties.`}),G!==void 0){let Ce=`${s}/propertyNames`;for(let De in t){let Re=`${a}/${Sv(De)}`,nt=Fu(De,G,r,n,o,i,Re,Ce);nt.valid||Fe.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:Ce,error:`Property name "${De}" does not
data: ${JSON.stringify(o)}
`));n.enqueue(e.encode(`event: end
`)),n.close()}});return Qy.fromReadableStream(r)}var jMt=v(()=>{cO()});function n2e(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}function hhe(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function*o2e(t,e){for(;;){let{value:r,done:n}=Qm.runWithConfig(Yy(t),e.next.bind(e),!0);if(n)break;yield r}}async function*ghe(t,e){let r=e[Symbol.asyncIterator]();for(;;){let{value:n,done:o}=await Qm.runWithConfig(Yy(t),r.next.bind(e),!0);if(o)break;yield n}}var DMt,$Mt=v(()=>{tz();rz();uO();DMt=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function"});function md(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function Ign(t){if(Fpe(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}function Cv(t){if(typeof t=="function")return new i_({func:t});if(Lo.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){let e={};for(let[r,n]of Object.entries(t))e[r]=Cv(n);return new hL({steps:e})}else throw new Error(`Expected a Runnable, function or object.
Instead got an unsupported type.`)}function Ngn(t,e){let r=e.name??t.getName(),n=e.description??lL(e.schema);return h6(e.schema)?new yhe({name:r,description:n,schema:Ct.object({input:Ct.string()}).transform(o=>o.input),bound:t}):new yhe({name:r,description:n,schema:e.schema,bound:t})}var i2e,Lo,Vw,FMt,bhe,El,hL,Agn,i_,zMt,a2e,$Q,s2e,yhe,Gh=v(()=>{V$();$fe();tz();rz();uO();UY();cO();dTt();gTt();iz();bTt();oBe();yN();IMt();jMt();$Mt();yO();i2e=L(cpe(),1);OY();qqe();Lo=class extends Vh{constructor(){super(...arguments);M(this,"lc_runnable",!0);M(this,"name")}getName(e){let r=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${r}${e}`:r}withRetry(e){return new bhe({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new Vw({bound:this,config:e,kwargs:{}})}withFallbacks(e){let r=Array.isArray(e)?e:e.fallbacks;return new a2e({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(Jo);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)=>Jo(i===0?e:n))}return Array.from({length:r},()=>Jo(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=Jo(r),o=new Q$({generator:this._streamIterator(e,n),config:n});return await o.setup,Qy.fromAsyncGenerator(o)}_separateRunnableConfigFromCallOptions(e){let r;e===void 0?r=Jo(e):r=Jo({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=Jo(n),a=await(await Gg(o))?.handleChainStart(this.toJSON(),md(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 lO(u,n?.signal)}catch(u){throw await a?.handleChainError(u),u}return await a?.handleChainEnd(md(s,"output")),s}async _batchWithConfig(e,r,n,o){let i=this._getOptionsList(n??{},r.length),a=await Promise.all(i.map(Gg)),s=await Promise.all(a.map(async(l,c)=>{let d=await l?.handleChainStart(this.toJSON(),md(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 lO(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(md(u,"output")))),u}_concatOutputChunks(e,r){return eb(e,r)}async*_transformStreamWithConfig(e,r,n){let o,i=!0,a,s=!0,u=Jo(n),l=await Gg(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 Yqe(r.bind(this),d(),async()=>l?.handleChainStart(this.toJSON(),{input:""},u.runId,u.runType,void 0,void 0,u.runName??this.getName()),n?.signal,u);delete u.runId,f=p.setup;let m=f?.handlers.find(mTt),h=p.output;m!==void 0&&f!==void 0&&(h=m.tapOutputIterable(f.runId,h));let g=f?.handlers.find(rBe);g!==void 0&&f!==void 0&&(h=g.tapOutputIterable(f.runId,h));for await(let y of h)if(yield y,s)if(a===void 0)a=y;else try{a=this._concatOutputChunks(a,y)}catch{a=void 0,s=!1}}catch(p){throw await f?.handleChainError(p,void 0,void 0,void 0,{inputs:md
${a.content}`),e.push(Dgn(s))}}return e}function eRt(t,e){if(Array.isArray(t)){let r=t;if(!e)throw new Error("Options parameter is required when providing messages.");return ZMt(r,e)}else{let r=t;return i_.from(n=>ZMt(n,r)).withConfig({runName:"trim_messages"})}}async function ZMt(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=l2e;if(l&&("splitText"in l?d=l.splitText:d=async f=>l(f)),o==="first")return tRt(t,{maxTokens:r,tokenCounter:c,textSplitter:d,partialStrategy:i?"first":void 0,endOn:a});if(o==="last")return jgn(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 tRt(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_"))),g=u2e(c.getType(),{...h,content:m}),y=[...s.slice(0,u),g];if(await n(y)<=r)s=y,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&&!vhe(s[u-1],l);)u-=1}return s.slice(0,u)}async function jgn(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 u2e(c.getType(),d,Z3(c))});if(o){let c=Array.isArray(o)?o:[o];for(;s.length>0&&!vhe(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 tRt(l,{...a,partialStrategy:r?"last":void 0,endOn:i}),u?[l[0],...l.slice(1).reverse()]:l.reverse()}function u2e(t,e,r){let n,o;switch(t){case"human":r?n=new _v(e):o=new su(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 Ur(i)}else o=new li(e);break;case"system":r?n=new Ky(e):o=new Ym(e);break;case"developer":r?n=new Ky({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}}):o=new Ym({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in e)r?n=new Aw(e):o=new Gb(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 bv(e);else{if(!e.name)throw new Error("FunctionMessage must have a 'name' field");o=new VU(e)}break;case"generic":if("role"in e)r?n=new yv(e):o=new cd(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 Dgn(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 vhe,XMt,rRt=v(()=>{Vg();X3();V0();SY();Kfe();G$();CY();Wfe();iO();Gh();vhe=(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)};XMt={human:{message:su,messageChunk:_v},ai:{message:li,messageChunk:Ur},system:{message:Ym,messageChunk:Ky},developer:{message:Ym,messageChunk:Ky},tool:{message:Gb,messageChunk:Aw},function:{message:VU,messageChunk:bv},generic:{message:cd,messageChunk:yv},remove:{message:JU,messageChunk:JU}}});var nRt,oRt=v(()=>{nRt=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"]});var iRt,aRt=v(()=>{iRt=["image","video","audio","text-plain","file"]});var sRt,uRt=v(()=>{oRt();aRt();sRt=["text","reasoning",...nRt,...iRt]});var $gn,$s=v(()=>{Do();yY();cke();Vg();hke();X3();V0();SY();Kfe();G$();CY();Wfe();iO();rRt();uRt();$gn={};Et($gn,{AIMessage:()=>li,AIMessageChunk:()=>Ur,BaseMessage:()=>Jc,BaseMessageChunk:()=>Wb,ChatMessage:()=>cd,ChatMessageChunk:()=>yv,FunctionMessage:()=>VU,FunctionMessageChunk:()=>bv,HumanMessage:()=>su,HumanMessageChunk:()=>_v,KNOWN_BLOCK_TYPES:()=>sRt,RemoveMessage:()=>JU,SystemMessage:()=>Ym,SystemMessageChunk:()=>Ky,ToolMessage:()=>Gb,ToolMessageChunk:()=>Aw,_isMessageFieldWithRole:()=>Hfe,_mergeDicts:()=>xl,_mergeLists:()=>HU,_mergeObj:()=>zfe,_mergeStatus:()=>Ufe,coerceMessageLikeToMessage:()=>Iw,convertToChunk:()=>KU,convertToOpenAIImageBlock:()=>Ffe,convertToProviderContentBlock:()=>oO,defaultTextSplitter:()=>l2e,defaultToolCallParser:()=>_Y,filterMessages:()=>YMt,getBufferString:()=>rl,iife:()=>YSt,isAIMessage:()=>Us,isAIMessageChunk:()=>wY,isBase64ContentBlock:()=>G3,isBaseMessage:()=>Xm,isBaseMessageChunk:()=>Z3,isChatMessage:()=>HSt,isChatMessageChunk:()=>VSt,isDataContentBlock:()=>Zm,isDirectToolOutput:()=>bY,isFunctionMessage:()=>JSt,isFunctionMessageChunk:()=>KSt,isHumanMessage:()=>WSt,isHumanMessageChunk:()=>GSt,isIDContentBlock:()=>Lfe,isMessage:()=>Bfe,isOpenAIToolCallArray:()=>ASt,isPlainTextContentBlock:()=>vSt,isSystemMessage:()=>ZSt,isSystemMessageChunk:()=>XSt,isToolMessage:()=>vY,isToolMessageChunk:()=>fke,isURLContentBlock:()=>W3,mapChatMessagesToStoredMessages:()=>e0t,mapStoredMessageToChatMessage:()=>xY,mapStoredMessagesToChatMessages:()=>QSt,mergeContent:()=>Kb,mergeMessageRuns:()=>QMt,mergeResponseMetadata:()=>Vfe,mergeUsageMetadata:()=>Jfe,parseBase64DataUrl:()=>Hg,parseMimeType:()=>gY,trimMessages:()=>eRt})});var lRt,cRt=v(()=>{Vg();V0();G$();Gh();$s();_he();lRt=class extends Vw{constructor(e){let r=i_.from((a,s)=>this._enterHistory(a,s??{})).withConfig({runName:"loadHistory"}),n=e.historyMessagesKey??e.inputMessagesKey;n&&(r=xu.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});M(this,"runnable");M(this,"inputMessagesKey");M(this,"outputMessagesKey");M(this,"historyMessagesKey");M(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)&&!Xm(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 su(r)];if(Array.isArray(r))return r;if(Xm(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)&&!Xm(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 li(r)];if(Array.isArray(r))return r;if(Xm(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 Lgn,xv=v(()=>{Do();uO();Gh();_he();VMt();KMt();cRt();Lgn={};Et(Lgn,{RouterRunnable:()=>HMt,Runnable:()=>Lo,RunnableAssign:()=>$Q,RunnableBinding:()=>Vw,RunnableBranch:()=>JMt,RunnableEach:()=>FMt,RunnableLambda:()=>i_,RunnableMap:()=>hL,RunnableParallel:()=>zMt,RunnablePassthrough:()=>xu,RunnablePick:()=>s2e,RunnableRetry:()=>bhe,RunnableSequence:()=>El,RunnableToolLike:()=>yhe,RunnableWithFallbacks:()=>a2e,RunnableWithMessageHistory:()=>lRt,_coerceToRunnable:()=>Cv,ensureConfig:()=>Jo,getCallbackManagerForConfig:()=>Gg,mergeConfigs:()=>nz,patchConfig:()=>zs,pickRunnableConfigKeys:()=>Yy})});var Az,SN,eh,O6=v(()=>{mY();Gh();xv();Az=class extends Lo{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"})}},SN=class extends Az{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")}},eh=class extends Error{constructor(e,r,n,o=!1){super(e);M(this,"llmOutput");M(this,"observation");M(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");H$(this,"OUTPUT_PARSING_FAILURE")}}});var CN,gL,yL=v(()=>{Vg();iO();ym();O6();phe();CN=class extends SN{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"})}},gL=class extends CN{constructor(e){super(e);M(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(Z3(o)){if(typeof o.content!="string")throw new Error("Cannot handle non-string message output.");i=new Hi({message:o,text:o.content})}else if(Xm(o)){if(typeof o.content!="string")throw new Error("Cannot handle non-string message output.");i=new Hi({message:KU(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&&!bO(a,r)&&(this.diff?yield this._diff(r,a):yield a,r=a)}}getFormatInstructions(){return""}}});var dRt,fRt=v(()=>{yL();dRt=class extends CN{constructor(){super(...arguments);M(this,"lc_namespace",["langchain_core","output_parsers","bytes"]);M(this,"lc_serializable",!0);M(this,"textEncoder",new TextEncoder)}static lc_name(){return"BytesOutputParser"}parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return""}}});var T6,pRt,mRt,hRt,gRt,yRt=v(()=>{O6();yL();T6=class extends CN{constructor(){super(...arguments);M(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]}},pRt=class extends T6{constructor(){super(...arguments);M(this,"lc_namespace",["langchain_core","output_parsers","list"]);M(this,"lc_serializable",!0)}static lc_name(){return"CommaSeparatedListOutputParser"}async parse(e){try{return e.trim().split(",").map(r=>r.trim())}catch{throw new eh(`Could not parse output: ${e}`,e)}}getFor
1. foo
2. bar
3. baz`}async parse(e){return[...e.matchAll(this.re)??[]].map(r=>r[1])}},gRt=class extends T6{constructor(){super(...arguments);M(this,"lc_namespace",["langchain_core","output_parsers","list"]);M(this,"lc_serializable",!0);M(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 whe,bRt=v(()=>{yL();whe=class extends CN{constructor(){super(...arguments);M(this,"lc_namespace",["langchain_core","output_parsers","string"]);M(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,c2e,_Rt,vRt=v(()=>{yN();o_();O6();yO();Jw=class extends SN{constructor(e){super(e);M(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(Vi(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 uL(this.schema,JSON.parse(o))}catch(r){throw new eh(`Failed to parse. Text: "${e}". Error: ${r}`,e)}}},c2e=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(Vi(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)}},_Rt=class extends SN{constructor({inputSchema:e}){super(...arguments);M(this,"structuredInputParser");this.structuredInputParser=new c2e(e)}async parse(e){let r;try{r=await this.structuredInputParser.parse(e)}catch(n){throw new eh(`Failed to parse. Text: "${e}". Error: ${n}`,e)}return this.outputProcessor(r)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}}});var Fgn,d2e=v(()=>{Do();HY();VY();eBe();Fgn={};Et(Fgn,{applyPatch:()=>eL,compare:()=>n6})});var Ov,f2e=v(()=>{pY();VY();yL();d2e();Ov=class extends gL{constructor(){super(...arguments);M(this,"lc_namespace",["langchain_core","output_parsers"]);M(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?n6(e,r):[{op:"replace",path:"",value:r}]}async parsePartialResult(e){return fY(e[0].text)}async parse(e){return fY(e,JSON.parse)}getFormatInstructions(){return""}}});var kgn,wRt,SRt=v(()=>{kgn=function(){let t={};t.parser=function(j,A){return new r(j,A)},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(j,A){if(!(this instanceof r))return new r(j,A);var W=this;o(W),W.q=W.c="",W.bufferCheckPosition=t.MAX_BUFFER_LENGTH,W.opt=A||{},W.opt.lowercase=W.opt.lowercase||W.opt.lowercasetags,W.looseCase=W.opt.lowercase?"toLowerCase":"toUpperCase",W.tags=[],W.closed=W.closedRoot=W.sawRoot=!1,W.tag=W.error=null,W.strict=!!j,W.noscript=!!(j||W.opt.noscript),W.state=T.BEGIN,W.strictEntities=W.opt.strictEntities,W.ENTITIES=W.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),W.attribList=[],W.opt.xmlns&&(W.ns=Object.create(m)),W.trackPosition=W.opt.position!==!1,W.trackPosition&&(W.position=W.line=W.column=0),N(W,"onready")}Object.create||(Object.create=function(j){function A(){}A.prototype=j;var W=new A;return W}),Object.keys||(Object.keys=function(j){var A=[];for(var W in j)j.hasOwnProperty(W)&&A.push(W);return A});function n(j){for(var A=Math.max(t.MAX_BUFFER_LENGTH,10),W=0,V=0,se=e.length;V<se;V++){var be=j[e[V]].length;if(be>A)switch(e[V]){case"textNode":F(j);break;case"cdata":D(j,"oncdata",j.cdata),j.cdata="";break;case"script":D(j,"onscript",j.script),j.script="";break;default:U(j,"Max buffer length exceeded: "+e[V])}W=Math.max(W,be)}var Ee=t.MAX_BUFFER_LENGTH-W;j.bufferCheckPosition=Ee+j.position}function o(j){for(var A=0,W=e.length;A<W;A++)j[e[A]]=""}function i(j){F(j),j.cdata!==""&&(D(j,"oncdata",j.cdata),j.cdata=""),j.script!==""&&(D(j,"onscript",j.script),j.script="")}r.prototype={end:function(){H(this)},write:Y,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(j){return j!=="error"&&j!=="end"});function u(j,A){return new l(j,A)}function l(j,A){if(!(this instanceof l))return new l(j,A);a.apply(this),this._parser=new r(j,A),this.writable=!0,this.readable=!0;var W=this;this._parser.onend=function(){W.emit("end")},this._parser.onerror=function(V){W.emit("error",V),W._parser.error=null},this._decoder=null,s.forEach(function(V){Object.defineProperty(W,"on"+V,{get:function(){return W._parser["on"+V]},set:function(se){if(!se)return W.removeAllListeners(V),W._parser["on"+V]=se,se;W.on(V,se)},enumerable:!0,configurable:!1})})}l.prototype=Object.create(a.prototype,{constructor:{value:l}}),l.prototype.write=function(j){return this._parse
`||j==="\r"||j===" "}function w(j){return j==='"'||j==="'"}function x(j){return j===">"||_(j)}function O(j,A){return j.test(A)}function E(j,A){return!O(j,A)}var T=0;t.STATE={BEGIN:T++,BEGIN_WHITESPACE:T++,TEXT:T++,TEXT_ENTITY:T++,OPEN_WAKA:T++,SGML_DECL:T++,SGML_DECL_QUOTED:T++,DOCTYPE:T++,DOCTYPE_QUOTED:T++,DOCTYPE_DTD:T++,DOCTYPE_DTD_QUOTED:T++,COMMENT_STARTING:T++,COMMENT:T++,COMMENT_ENDING:T++,COMMENT_ENDED:T++,CDATA:T++,CDATA_ENDING:T++,CDATA_ENDING_2:T++,PROC_INST:T++,PROC_INST_BODY:T++,PROC_INST_ENDING:T++,OPEN_TAG:T++,OPEN_TAG_SLASH:T++,ATTRIB:T++,ATTRIB_NAME:T++,ATTRIB_NAME_SAW_WHITE:T++,ATTRIB_VALUE:T++,ATTRIB_VALUE_QUOTED:T++,ATTRIB_VALUE_CLOSED:T++,ATTRIB_VALUE_UNQUOTED:T++,ATTRIB_VALUE_ENTITY_Q:T++,ATTRIB_VALUE_ENTITY_U:T++,CLOSE_TAG:T++,CLOSE_TAG_SAW_WHITE:T++,SCRIPT:T++,SCRIPT_ENDING:T++},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(j){var A=t.ENTITIES[j],W=typeof A=="number"?String.fromCharCode(A):A;t.ENTITIES[j]=W});for(var R in t.STATE)t.STATE[t.STATE[R]]=R;T=t.STATE;function N(j,A,W){j[A]&&j[A](W)}function D(j,A,W){j.textNode&&F(j),N(j,A,W)}function F(j){j.textNode=B(j.opt,j.textNode),j.textNode&&N(j,"ontext",j.textNode),j.textNode=""}function B(j,A){return j.trim&&(A=A.trim()),j.normalize&&(A=A.replace(/\s+/g," ")),A}function U(j,A){return F(j),j.trackPosition&&(A+=`
Line: `+j.line+`
Column: `+j.column+`
Char: `+j.c),A=new Error(A),j.error=A,N(j,"onerror",A),j}function H(j){return j.sawRoot&&!j.closedRoot&&G(j,"Unclosed root tag"),j.state!==T.BEGIN&&j.state!==T.BEGIN_WHITESPACE&&j.state!==T.TEXT&&U(j,"Unexpected end"),F(j),j.c="",j.closed=!0,N(j,"onend"),r.call(j,j.strict,j.opt),j}function G(j,A){if(typeof j!="object"||!(j instanceof r))throw new Error("bad call to strictFail");j.strict&&U(j,A)}function ie(j){j.strict||(j.tagName=j.tagName[j.looseCase]());var A=j.tags[j.tags.length-1]||j,W=j.tag={name:j.tagName,attributes:{}};j.opt.xmlns&&(W.ns=A.ns),j.attribList.length=0,D(j,"onopentagstart",W)}function oe(j,A){var W=j.indexOf(":"),V=W<0?["",j]:j.split(":"),se=V[0],be=V[1];return A&&j==="xmlns"&&(se="xmlns",be=""),{prefix:se,local:be}}function z(j){if(j.strict||(j.attribName=j.attribName[j.looseCase]()),j.attribList.indexOf(j.attribName)!==-1||j.tag.attributes.hasOwnProperty(j.attribName)){j.attribName=j.attribValue="";return}if(j.opt.xmlns){var A=oe(j.attribName,!0),W=A.prefix,V=A.local;if(W==="xmlns")if(V==="xml"&&j.attribValue!==f)G(j,"xml: prefix must be bound to "+f+`
Actual: `+j.attribValue);else if(V==="xmlns"&&j.attribValue!==p)G(j,"xmlns: prefix must be bound to "+p+`
Actual: `+j.attribValue);else{var se=j.tag,be=j.tags[j.tags.length-1]||j;se.ns===be.ns&&(se.ns=Object.create(be.ns)),se.ns[V]=j.attribValue}j.attribList.push([j.attribName,j.attribValue])}else j.tag.attributes[j.attribName]=j.attribValue,D(j,"onattribute",{name:j.attribName,value:j.attribValue});j.attribName=j.attribValue=""}function Q(j,A){if(j.opt.xmlns){var W=j.tag,V=oe(j.tagName);W.prefix=V.prefix,W.local=V.local,W.uri=W.ns[V.prefix]||"",W.prefix&&!W.uri&&(G(j,"Unbound namespace prefix: "+JSON.stringify(j.tagName)),W.uri=V.prefix);var se=j.tags[j.tags.length-1]||j;W.ns&&se.ns!==W.ns&&Object.keys(W.ns).forEach(function(hn){D(j,"onopennamespace",{prefix:hn,uri:W.ns[hn]})});for(var be=0,Ee=j.attribList.length;be<Ee;be++){var Ae=j.attribList[be],ht=Ae[0],Rt=Ae[1],Ze=oe(ht,!0),Dr=Ze.prefix,Vt=Ze.local,jt=Dr===""?"":W.ns[Dr]||"",Fe={name:ht,value:Rt,prefix:Dr,local:Vt,uri:jt};Dr&&Dr!=="xmlns"&&!jt&&(G(j,"Unbound namespace prefix: "+JSON.stringify(Dr)),Fe.uri=Dr),j.tag.attributes[ht]=Fe,D(j,"onattribute",Fe)}j.attribList.length=0}j.tag.isSelfClosing=!!A,j.sawRoot=!0,j.tags.push(j.tag),D(j,"onopentag",j.tag),A||(!j.noscript&&j.tagName.toLowerCase()==="script"?j.state=T.SCRIPT:j.state=T.TEXT,j.tag=null,j.tagName=""),j.attribName=j.attribValue="",j.attribList.length=0}function re(j){if(!j.tagName){G(j,"Weird empty close tag."),j.textNode+="</>",j.state=T.TEXT;return}if(j.script){if(j.tagName!=="script"){j.script+="</"+j.tagName+">",j.tagName="",j.state=T.SCRIPT;return}D(j,"onscript",j.script),j.script=""}var A=j.tags.length,W=j.tagName;j.strict||(W=W[j.looseCase]());for(var V=W;A--;){var se=j.tags[A];if(se.name!==V)G(j,"Unexpected close tag");else break}if(A<0){G(j,"Unmatched closing tag: "+j.tagName),j.textNode+="</"+j.tagName+">",j.state=T.TEXT;return}j.tagName=W;for(var be=j.tags.length;be-- >A;){var Ee=j.tag=j.tags.pop();j.tagName=j.tag.name,D(j,"onclosetag",j.tagName);var Ae={};for(var ht in Ee.ns)Ae[ht]=Ee.ns[ht];var Rt=j.tags[j.tags.length-1]||j;j.opt.xmlns&&Ee.ns!==Rt.ns&&Object.keys(Ee.ns).forEach(function(Ze){var Dr=Ee.ns[Ze];D(j,"onclosenamespace",{prefix:Ze,uri:Dr})})}A===0&&(j.closedRoot=!0),j.tagName=j.attribValue=j.attribName="",j.attribList.length=0,j.state=T.TEXT}function Z(j){var A=j.entity,W=A.toLowerCase(),V,se="";return j.ENTITIES[A]?j.ENTITIES[A]:j.ENTITIES[W]?j.ENTITIES[W]:(A=W,A.charAt(0)==="#"&&(A.charAt(1)==="x"?(A=A.slice(2),V=parseInt(A,16),se=V.toString(16)):(A=A.slice(1),V=parseInt(A,10),se=V.toString(10))),A=A.replace(/^0+/,""),isNaN(V)||se.toLowerCase()!==A?(G(j,"Invalid character entity"),"&"+j.entity+";"):String.fromCodePoint(V))}function $(j,A){A==="<"?(j.state=T.OPEN_WAKA,j.startTagPosition=j.position):_(A)||(G(j,"Non-whitespace before first tag."),j.textNode=A,j.state=T.TEXT)}function q(j,A){var W="";return A<j.length&&(W=j.charAt(A)),W}function Y(j){var A=this;if(this.error)throw this.error;if(A.closed)return U(A,"Cannot write after close. Assign an onready handler.");if(j===null)return H(A);typeof j=="object"&&(j=j.toString());for(var W=0,V="";V=q(j,W++),A.c=V,!!V;)switch(A.trackPosition&&(A.position++,V===`
`?(A.line++,A.column=0):A.column++),A.state){case T.BEGIN:if(A.state=T.BEGIN_WHITESPACE,V==="\uFEFF")continue;$(A,V);continue;case T.BEGIN_WHITESPACE:$(A,V);continue;case T.TEXT:if(A.sawRoot&&!A.closedRoot){for(var se=W-1;V&&V!=="<"&&V!=="&";)V=q(j,W++),V&&A.trackPosition&&(A.position++,V===`
`?(A.line++,A.column=0):A.column++);A.textNode+=j.substring(se,W-1)}V==="<"&&!(A.sawRoot&&A.closedRoot&&!A.strict)?(A.state=T.OPEN_WAKA,A.startTagPosition=A.position):(!_(V)&&(!A.sawRoot||A.closedRoot)&&G(A,"Text data outside of root node."),V==="&"?A.state=T.TEXT_ENTITY:A.textNode+=V);continue;case T.SCRIPT:V==="<"?A.state=T.SCRIPT_ENDING:A.script+=V;continue;case T.SCRIPT_ENDING:V==="/"?A.state=T.CLOSE_TAG:(A.script+="<"+V,A.state=T.SCRIPT);continue;case T.OPEN_WAKA:if(V==="!")A.state=T.SGML_DECL,A.sgmlDecl="";else if(!_(V))if(O(h,V))A.state=T.OPEN_TAG,A.tagName=V;else if(V==="/")A.state=T.CLOSE_TAG,A.tagName="";else if(V==="?")A.state=T.PROC_INST,A.procInstName=A.procInstBody="";else{if(G(A,"Unencoded <"),A.startTagPosition+1<A.position){var be=A.position-A.startTagPosition;V=new Array(be).join(" ")+V}A.textNode+="<"+V,A.state=T.TEXT}continue;case T.SGML_DECL:(A.sgmlDecl+V).toUpperCase()===c?(D(A,"onopencdata"),A.state=T.CDATA,A.sgmlDecl="",A.cdata=""):A.sgmlDecl+V==="--"?(A.state=T.COMMENT,A.comment="",A.sgmlDecl=""):(A.sgmlDecl+V).toUpperCase()===d?(A.state=T.DOCTYPE,(A.doctype||A.sawRoot)&&G(A,"Inappropriately located doctype declaration"),A.doctype="",A.sgmlDecl=""):V===">"?(D(A,"onsgmldeclaration",A.sgmlDecl),A.sgmlDecl="",A.state=T.TEXT):(w(V)&&(A.state=T.SGML_DECL_QUOTED),A.sgmlDecl+=V);continue;case T.SGML_DECL_QUOTED:V===A.q&&(A.state=T.SGML_DECL,A.q=""),A.sgmlDecl+=V;continue;case T.DOCTYPE:V===">"?(A.state=T.TEXT,D(A,"ondoctype",A.doctype),A.doctype=!0):(A.doctype+=V,V==="["?A.state=T.DOCTYPE_DTD:w(V)&&(A.state=T.DOCTYPE_QUOTED,A.q=V));continue;case T.DOCTYPE_QUOTED:A.doctype+=V,V===A.q&&(A.q="",A.state=T.DOCTYPE);continue;case T.DOCTYPE_DTD:A.doctype+=V,V==="]"?A.state=T.DOCTYPE:w(V)&&(A.state=T.DOCTYPE_DTD_QUOTED,A.q=V);continue;case T.DOCTYPE_DTD_QUOTED:A.doctype+=V,V===A.q&&(A.state=T.DOCTYPE_DTD,A.q="");continue;case T.COMMENT:V==="-"?A.state=T.COMMENT_ENDING:A.comment+=V;continue;case T.COMMENT_ENDING:V==="-"?(A.state=T.COMMENT_ENDED,A.comment=B(A.opt,A.comment),A.comment&&D(A,"oncomment",A.comment),A.comment=""):(A.comment+="-"+V,A.state=T.COMMENT);continue;case T.COMMENT_ENDED:V!==">"?(G(A,"Malformed comment"),A.comment+="--"+V,A.state=T.COMMENT):A.state=T.TEXT;continue;case T.CDATA:V==="]"?A.state=T.CDATA_ENDING:A.cdata+=V;continue;case T.CDATA_ENDING:V==="]"?A.state=T.CDATA_ENDING_2:(A.cdata+="]"+V,A.state=T.CDATA);continue;case T.CDATA_ENDING_2:V===">"?(A.cdata&&D(A,"oncdata",A.cdata),D(A,"onclosecdata"),A.cdata="",A.state=T.TEXT):V==="]"?A.cdata+="]":(A.cdata+="]]"+V,A.state=T.CDATA);continue;case T.PROC_INST:V==="?"?A.state=T.PROC_INST_ENDING:_(V)?A.state=T.PROC_INST_BODY:A.procInstName+=V;continue;case T.PROC_INST_BODY:if(!A.procInstBody&&_(V))continue;V==="?"?A.state=T.PROC_INST_ENDING:A.procInstBody+=V;continue;case T.PROC_INST_ENDING:V===">"?(D(A,"onprocessinginstruction",{name:A.procInstName,body:A.procInstBody}),A.procInstName=A.procInstBody="",A.state=T.TEXT):(A.procInstBody+="?"+V,A.state=T.PROC_INST_BODY);continue;case T.OPEN_TAG:O(g,V)?A.tagName+=V:(ie(A),V===">"?Q(A):V==="/"?A.state=T.OPEN_TAG_SLASH:(_(V)||G(A,"Invalid character in tag name"),A.state=T.ATTRIB));continue;case T.OPEN_TAG_SLASH:V===">"?(Q(A,!0),re(A)):(G(A,"Forward-slash in opening tag not followed by >"),A.state=T.ATTRIB);continue;case T.ATTRIB:if(_(V))continue;V===">"?Q(A):V==="/"?A.state=T.OPEN_TAG_SLASH:O(h,V)?(A.attribName=V,A.attribValue="",A.state=T.ATTRIB_NAME):G(A,"Invalid attribute name");continue;case T.ATTRIB_NAME:V==="="?A.state=T.ATTRIB_VALUE:V===">"?(G(A,"Attribute without value"),A.attribValue=A.attribName,z(A),Q(A)):_(V)?A.state=T.ATTRIB_NAME_SAW_WHITE:O(g,V)?A.attribName+=V:G(A,"Invalid attribute name");continue;case T.ATTRIB_NAME_SAW_WHITE:if(V==="=")A.state=T.ATTRIB_VALUE;else{if(_(V))continue;G(A,"Attribute without value"),A.tag.attributes[A.attribName]="",A.attribValue="",D(A,"onattribute",{name:A.attribName,value:""}),A.attribName="",V===">"?Q(A):O(h,V)?(A.attribName=V,A.state=T.ATTRIB_NAME):(G(A,"Invalid attribute name"),A.state=T.ATTRIB)}continue;case T.ATTRIB_VALUE:if(_(V))continue;w(V)?(A.q=V
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}
\`\`\``,CRt=class extends gL{constructor(e){super(e);M(this,"tags");M(this,"lc_namespace",["langchain_core","output_parsers"]);M(this,"lc_serializable",!0);this.tags=e?.tags}static lc_name(){return"XMLOutputParser"}_diff(e,r){if(r)return e?n6(e,r):[{op:"replace",path:"",value:r}]}async parsePartialResult(e){return Che(e[0].text)}async parse(e){return Che(e)}getFormatInstructions(){return!!(this.tags&&this.tags.length>0)?She.replace("{tags}",this.tags?.join(", ")??""):She}},qgn=t=>t.split(`
`).map(e=>e.replace(/^\s+/,"")).join(`
`).trim(),xRt=t=>{if(Object.keys(t).length===0)return{};let e={};return t.children.length>0?(e[t.name]=t.children.map(xRt),e):(e[t.name]=t.text??void 0,e)}});var Bgn,_O=v(()=>{Do();pY();O6();yL();fRt();yRt();bRt();vRt();f2e();ORt();Bgn={};Et(Bgn,{AsymmetricStructuredOutputParser:()=>_Rt,BaseCumulativeTransformOutputParser:()=>gL,BaseLLMOutputParser:()=>Az,BaseOutputParser:()=>SN,BaseTransformOutputParser:()=>CN,BytesOutputParser:()=>dRt,CommaSeparatedListOutputParser:()=>pRt,CustomListOutputParser:()=>mRt,JsonMarkdownStructuredOutputParser:()=>c2e,JsonOutputParser:()=>Ov,ListOutputParser:()=>T6,MarkdownListOutputParser:()=>gRt,NumberedListOutputParser:()=>hRt,OutputParserException:()=>eh,StringOutputParser:()=>whe,StructuredOutputParser:()=>Jw,XMLOutputParser:()=>CRt,XML_FORMAT_INSTRUCTIONS:()=>She,parseJsonMarkdown:()=>fY,parsePartialJson:()=>UU,parseXMLMarkdown:()=>Che})});var Kw,E6=v(()=>{Gh();Kw=class extends Lo{constructor(e){super(e);M(this,"lc_serializable",!0);M(this,"lc_namespace",["langchain_core","prompts",this._getPromptType()]);M(this,"inputVariables");M(this,"outputParser");M(this,"partialVariables");M(this,"metadata");M(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 Ugn,xhe,LQ,FQ,p2e,kQ=v(()=>{Do();V$();G$();iO();Ugn={};Et(Ugn,{BasePromptValue:()=>xhe,ChatPromptValue:()=>FQ,ImagePromptValue:()=>p2e,StringPromptValue:()=>LQ});xhe=class extends Vh{},LQ=class extends xhe{constructor(e){super({value:e});M(this,"lc_namespace",["langchain_core","prompt_values"]);M(this,"lc_serializable",!0);M(this,"value");this.value=e}static lc_name(){return"StringPromptValue"}toString(){return this.value}toChatMessages(){return[new su(this.value)]}},FQ=class extends xhe{constructor(e){Array.isArray(e)&&(e={messages:e});super(e);M(this,"lc_namespace",["langchain_core","prompt_values"]);M(this,"lc_serializable",!0);M(this,"messages");this.messages=e.messages}static lc_name(){return"ChatPromptValue"}toString(){return rl(this.messages)}toChatMessages(){return this.messages}},p2e=class extends xhe{constructor(e){"imageUrl"in e||(e={imageUrl:e});super(e);M(this,"lc_namespace",["langchain_core","prompt_values"]);M(this,"lc_serializable",!0);M(this,"imageUrl");M(this,"value");this.imageUrl=e.imageUrl}static lc_name(){return"ImagePromptValue"}toString(){return this.imageUrl.url}toChatMessages(){return[new su({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}}});var xN,qQ=v(()=>{kQ();E6();xN=class extends Kw{async formatPromptValue(t){let e=await this.format(t);return new LQ(e)}}});function h2e(t){return typeof t=="function"}function Hgn(t){return M6(t)?"array":typeof t}function m2e(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function TRt(t,e){return t!=null&&typeof t=="object"&&e in t}function Vgn(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}function Kgn(t,e){return Jgn.call(t,e)}function Ggn(t){return!Kgn(Wgn,t)}function Xgn(t){return String(t).replace(/[&<>"'`=\/]/g,function(r){return Zgn[r]})}function ryn(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(T){if(typeof T=="string"&&(T=T.split(Qgn,2)),!M6(T)||T.length!==2)throw new Error("Invalid tags: "+T);d=new RegExp(m2e(T[0])+"\\s*"),f=new RegExp("\\s*"+m2e(T[1])),p=new RegExp("\\s*"+m2e("}"+T[1]))}m(e||Ww.tags);for(var h=new UQ(t),g,y,b,_,w,x;!h.eos();){if(g=h.pos,b=h.scanUntil(d),b)for(var O=0,E=b.length;O<E;++O)_=b.charAt(O),Ggn(
`&&(c(),u="",l=0,r=!1);if(!h.scan(d))break;if(a=!0,y=h.scan(tyn)||"name",h.scan(Ygn),y==="="?(b=h.scanUntil(ERt),h.scan(ERt),h.scanUntil(f)):y==="{"?(b=h.scanUntil(p),h.scan(eyn),h.scanUntil(f),y="&"):b=h.scanUntil(f),!h.scan(f))throw new Error("Unclosed tag at "+h.pos);if(y==">"?w=[y,b,g,h.pos,u,l,r]:w=[y,b,g,h.pos],l++,o.push(w),y==="#"||y==="^")n.push(w);else if(y==="/"){if(x=n.pop(),!x)throw new Error('Unopened section "'+b+'" at '+g);if(x[1]!==b)throw new Error('Unclosed section "'+x[1]+'" at '+g)}else y==="name"||y==="{"||y==="&"?s=!0:y==="="&&m(b)}if(c(),x=n.pop(),x)throw new Error('Unclosed section "'+x[1]+'" at '+h.pos);return oyn(nyn(o))}function nyn(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 oyn(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 UQ(t){this.string=t,this.tail=t,this.pos=0}function P6(t,e){this.view=t,this.cache={".":this.view},this.parent=e}function nb(){this.templateCache={_cache:{},set:function(e,r){this._cache[e]=r},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}var zgn,M6,Jgn,Wgn,Zgn,Ygn,Qgn,ERt,eyn,tyn,Ww,BQ,Ohe,PRt=v(()=>{zgn=Object.prototype.toString,M6=Array.isArray||function(e){return zgn.call(e)==="[object Array]"};Jgn=RegExp.prototype.test;Wgn=/\S/;Zgn={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};Ygn=/\s*/,Qgn=/\s+/,ERt=/\s*=/,eyn=/\s*\}/,tyn=/#|\^|\/|>|\{|&|=|!/;UQ.prototype.eos=function(){return this.tail===""};UQ.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};UQ.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};P6.prototype.push=function(e){return new P6(e,this)};P6.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=TRt(i,a[s])||Vgn(i,a[s])),i=i[a[s++]];else i=o.view[e],u=TRt(o.view,e);if(u){n=i;break}o=o.parent}r[e]=n}return h2e(n)&&(n=n.call(this.view)),n};nb.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};nb.prototype.parse=function(e,r){var n=this.templateCache,o=e+":"+(r||Ww.tags).join(":"),i=typeof n<"u",a=i?n.get(o):void 0;return a==null&&(a=ryn(e,r),i&&n.set(o,a)),a};nb.prototype.render=function(e,r,n,o){var i=this.getConfigTags(o),a=this.parse(e,i),s=r instanceof P6?r:new P6(r,void 0);return this.renderTokens(a,s,n,e,o)};nb.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};nb.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(M6(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(h2e(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}};nb.prototype.renderInverted=function(e,r,n,o,i){var a=r.lookup(e[1]);if(!a||M6(a)&&a.length===0)return this.renderTokens(e[4],r,n,o,i)};nb.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(`
`)};nb.prototype.renderPartial=function(e,r,n,o){if(n){var i=this.getConfigTags(o),a=h2e(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)}}};nb.prototype.unescapedValue=function(e,r){var n=r.lookup(e[1]);if(n!=null)return n};nb.prototype.escapedValue=function(e,r,n){var o=this.getConfigEscape(n)||Ww.escape,i=r.lookup(e[1]);if(i!=null)return typeof i=="number"&&o===Ww.escape?String(i):o(i)};nb.prototype.rawValue=function(e){return e[1]};nb.prototype.getConfigTags=function(e){return M6(e)?e:e&&typeof e=="object"?e.tags:void 0};nb.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!M6(e))return e.escape};Ww={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){BQ.templateCache=t},get templateCache(){return BQ.templateCache}},BQ=new nb;Ww.clearCache=function(){return BQ.clearCache()};Ww.parse=function(e,r){return BQ.parse(e,r)};Ww.render=function(e,r,n,o){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+Hgn(e)+'" was given as the first argument for mustache#render(template, view, partials)');return BQ.render(e,r,n,o)};Ww.escape=Xgn;Ww.Scanner=UQ;Ww.Context=P6;Ww.Writer=nb;Ohe=Ww});function MRt(){Ohe.escape=t=>t}var Iz,RRt,R6,g2e,y2e,zQ,b2e,Yg,Nz,ON,jz=v(()=>{mY();PRt();Iz=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},RRt=(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=RRt(n[4],o);r.push(...i)}}else r.push({type:"literal",text:n[1]});return r},R6=t=>{MRt();let e=Ohe.parse(t);return RRt(e)},g2e=(t,e)=>Iz(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},""),y2e=(t,e)=>(MRt(),Ohe.render(t,e)),zQ={"f-string":g2e,mustache:y2e},b2e={"f-string":Iz,mustache:R6},Yg=(t,e,r)=>{try{return zQ[e](t,r)}catch(n){throw H$(n,"INVALID_PROMPT_INPUT")}},Nz=(t,e)=>b2e[e](t),ON=(t,e,r)=>{if(!(e in zQ)){let n=Object.keys(zQ);throw new Error(`Invalid template format. Got \`${e}\`;
should be one of ${n}`)}try{let n=r.reduce((o,i)=>(o[i]="foo",o),{});Array.isArray(t)?t.forEach(o=>{if(o.type==="text"&&"text"in o&&typeof o.text=="string")Yg(o.text,e,n);else if(o.type==="image_url"){if(typeof o.image_url=="string")Yg(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;Yg(i,e,n)}}else throw new Error(`Invalid message template received. ${JSON.stringify(o,null,2)}`)}):Yg(t,e,n)}catch(n){throw new Error(`Invalid prompt schema: ${n.message}`)}}});var uu,The=v(()=>{qQ();jz();uu=class HQ extends xN{constructor(r){super(r);M(this,"template");M(this,"templateFormat","f-string");M(this,"validateTemplate",!0);M(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))),ON(this.template,this.templateFormat,n)}}static lc_name(){return"PromptTemplate"}_getPromptType(){return"prompt"}async format(r){let n=await this.mergePartialAndUserVariables(r);return Yg(this.template,this.templateFormat,n)}static fromExamples(r,n,o,i=`
`,a=""){let s=[a,...r,n].join(i);return new HQ({inputVariables:o,template:s})}static fromTemplate(r,n){let{templateFormat:o="f-string",...i}=n??{},a=new Set;return Nz(r,o).forEach(s=>{s.type==="variable"&&a.add(s.name)}),new HQ({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 HQ(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 HQ({inputVariables:r.input_variables,template:r.template,templateFormat:r.template_format})}}});var A6,_2e=v(()=>{kQ();E6();jz();A6=class ARt extends Kw{constructor(r){super(r);M(this,"lc_namespace",["langchain_core","prompts","image"]);M(this,"template");M(this,"templateFormat","f-string");M(this,"validateTemplate",!0);M(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))),ON([{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 ARt(i)}async format(r){let n={};for(let[s,u]of Object.entries(this.template))typeof u=="string"?n[s]=Yg(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 p2e(n)}}});function v2e(t,e){let r=[];for(let n of Object.values(t))if(typeof n=="string")Nz(n,e).forEach(o=>{o.type==="variable"&&r.push(o.name)});else if(Array.isArray(n))for(let o of n)typeof o=="string"?Nz(o,e).forEach(i=>{i.type==="variable"&&r.push(i.name)}):typeof o=="object"&&r.push(...v2e(o,e));else typeof n=="object"&&n!==null&&r.push(...v2e(n,e));return Array.from(new Set(r))}function w2e(t,e,r){let n={};for(let[o,i]of Object.entries(t))if(typeof i=="string")n[o]=Yg(i,r,e);else if(Array.isArray(i)){let a=[];for(let s of i)typeof s=="string"?a.push(Yg(s,r,e)):typeof s=="object"&&a.push(w2e(s,e,r));n[o]=a}else typeof i=="object"&&i!==null?n[o]=w2e(i,e,r):n[o]=i;return n}var VQ,S2e=v(()=>{Gh();jz();VQ=class extends Lo{constructor(e){let r=e.templateFormat??"f-string",n=v2e(e.template,r);super({inputVariables:n,...e});M(this,"lc_namespace",["langchain_core","prompts","dict"]);M(this,"lc_serializable",!0);M(this,"template");M(this,"templateFormat");M(this,"inputVariables");this.template=e.template,this.templateFormat=r,this.inputVariables=n}static lc_name(){return"DictPromptTemplate"}async format(e){return w2e(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:"prompt"})}}});function iyn(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function ayn(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 syn(t){return typeof t.formatMessages=="function"}function uyn(t,e){if(syn(t)||Xm(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)==="}}"){let
`));throw a.name="InputFormatError",a.lc_error_code=o.lc_error_code,a}return n}},C2e=class extends JQ{constructor(e){"prompt"in e||(e={prompt:e});super(e);M(this,"prompt");this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}},KQ=class extends Kw{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){let e=await this.formatMessages(t);return new FQ(e)}},x2e=class extends C2e{constructor(e,r){"prompt"in e||(e={prompt:e,role:r});super(e);M(this,"role");this.role=e.role}static lc_name(){return"ChatMessagePromptTemplate"}async format(e){return new cd(await this.prompt.format(e),this.role)}static fromTemplate(e,r,n){return new this(uu.fromTemplate(e,{templateFormat:n?.templateFormat}),r)}};O2e=class extends JQ{constructor(e,r){"prompt"in e||(e={prompt:e});super(e);M(this,"lc_namespace",["langchain_core","prompts","chat"]);M(this,"lc_serializable",!0);M(this,"inputVariables",[]);M(this,"additionalOptions",{});M(this,"prompt");M(this,"messageClass");M(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(uu.fromTemplate(e,r));let n=[];for(let o of e)if(typeof o=="string")n.push(uu.fromTemplate(o,r));else if(o!==null)if(iyn(o)){let i="";typeof o.text=="string"&&(i=o.text??"");let a={...r,additionalContentFields:o};n.push(uu.fromTemplate(i,a))}else if(ayn(o)){let i=o.image_url??"",a,s=[];if(typeof i=="string"){let u;r?.templateFormat==="mustache"?u=R6(i):u=Iz(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 A6({template:i,inputVariables:s,templateFormat:r?.templateFormat,additionalContentFields:o})}else if(typeof i=="object"){if("url"in i){let u;r?.templateFormat==="mustache"?u=R6(i.url):u=Iz(i.url),s=u.flatMap(l=>l.type==="variable"?[l.name]:[])}else s=[];a=new A6({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 VQ({template:o,templateFormat:r?.templateFormat}));return new this({prompt:n,additionalOptions:r})}async format(e){if(this.prompt instanceof xN){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 xN){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 A6){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 VQ){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)]}},a_=class extends O2e{static _messageClass(){return su}static lc_name(){return"HumanMessagePromptTemplate"}},Phe=class extends O2e{static _messageClass(){return li}static lc_name(){return"AIMessagePromptTemplate"}},Gw=class extends O2e{static _messageClass(){return Ym}static lc_name(){return"SystemMessagePromptTemplate"}};hd=class Ehe extends KQ{constructor(r){super(r);M(this,"promptMessages");M(this,"validateTemplate",!0);M(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 Jc))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 uu.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 Jc)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)&&!(lyn(i)&&i.optional))throw H$(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 Ehe(i)}static fromTemplate(r,n){let o=uu.fromTemplate(r,n),i=new a_({prompt:o});return this.fromMessages([i])}static fromMessages(r,n){let o=r.reduce((s,u)=>s.concat(u instanceof Ehe?u.promptMessages:[uyn(u,n)]),[]),i=r.reduce((s,u)=>u ins
`);M(this,"prefix","");M(this,"templateFormat","f-string");M(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))),ON(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 T2e(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 Yg(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 uu.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 T2e({inputVariables:r.input_variables,examplePrompt:o,examples:i,exampleSeparator:r.example_separator,prefix:r.prefix,suffix:r.suffix,templateFormat:r.template_format})}},NRt=class jRt extends KQ{constructor(r){super(r);M(this,"lc_serializable",!0);M(this,"examples");M(this,"exampleSelector");M(this,"examplePrompt");M(this,"suffix","");M(this,"exampleSeparator",`
`);M(this,"prefix","");M(this,"templateFormat","f-string");M(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))),ON(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 Yg(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 jRt(i)}}});var $Rt,LRt=v(()=>{E6();WQ();$Rt=class Mhe extends Kw{constructor(r){super({...r,inputVariables:[]});M(this,"pipelinePrompts");M(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=Mhe.extractRequiredInputValues(n,i.inputVariables);i instanceof hd?n[o]=await i.formatMessages(a):n[o]=await i.format(a)}return Mhe.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 Mhe(n)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}}});function FRt(t){return typeof t=="object"&&t!=null&&"withStructuredOutput"in t&&typeof t.withStructuredOutput=="function"}function cyn(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 kRt,BRt=v(()=>{Gh();WQ();kRt=class qRt extends hd{constructor(r){super(r);M(this,"schema");M(this,"method");M(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(FRt(r))return super.pipe(r.withStructuredOutput(this.schema));if(cyn(r)&&FRt(r.bound))return super.pipe(new Vw({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 qRt.fromMessages(r,{schema:n,method:o})}}});var dyn
`)});function th(t,e){let r=`atom${++myn}`,n={toString(){return(Pl.env?Pl.env.MODE:void 0)!=="production"&&this.debugLabel?r+":"+this.debugLabel:r}};return typeof t=="function"?n.read=t:(n.init=t,n.read=hyn,n.write=gyn),e&&(n.write=e),n}function hyn(t){return t(this)}function gyn(t,e,r){return e(this,typeof r=="function"?r(t(this)):r)}var Pl,myn,URt,P2e,M2e,Ihe,A2e,yyn,byn,I2e,zRt,Ahe,JRt,HRt,N6,R2e,_yn,vyn,VRt,bL,KRt,j6,ZQ,WRt,N2e=v(()=>{Pl={},myn=0;URt=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,P2e=t=>"init"in t,M2e=t=>!!t.write,Ihe=new WeakMap,A2e=t=>{var e;return I2e(t)&&!((e=Ihe.get(t))!=null&&e[1])},yyn=(t,e)=>{let r=Ihe.get(t);if(r)r[1]=!0,r[0].forEach(n=>n(e));else if((Pl.env?Pl.env.MODE:void 0)!=="production")throw new Error("[Bug] cancelable promise not found")},byn=t=>{if(Ihe.has(t))return;let e=[new Set,!1];Ihe.set(t,e);let r=()=>{e[1]=!0};t.then(r,r),t.onCancel=n=>{e[0].add(n)}},I2e=t=>typeof t?.then=="function",zRt=t=>"v"in t||"e"in t,Ahe=t=>{if("e"in t)throw t.e;if((Pl.env?Pl.env.MODE:void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},JRt=(t,e,r)=>{r.p.has(t)||(r.p.add(t),e.then(()=>{r.p.delete(t)},()=>{r.p.delete(t)}))},HRt=(t,e,r,n,o)=>{var i;if((Pl.env?Pl.env.MODE:void 0)!=="production"&&n===e)throw new Error("[Bug] atom cannot depend on itself");r.d.set(n,o.n),A2e(r.v)&&JRt(e,r.v,o),(i=o.m)==null||i.t.add(e),t&&_yn(t,n,e)},N6=()=>[new Map,new Map,new Set],R2e=(t,e,r)=>{t[0].has(e)||t[0].set(e,new Set),t[1].set(e,r)},_yn=(t,e,r)=>{let n=t[0].get(e);n&&n.add(r)},vyn=(t,e)=>t[0].get(e),VRt=(t,e)=>{t[2].add(e)},bL=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},KRt=(...[t,e,r,n])=>{let o;(Pl.env?Pl.env.MODE:void 0)!=="production"&&(o=new Set);let i=(_,w,x)=>{let O="v"in w,E=w.v,T=A2e(w.v)?w.v:null;if(I2e(x)){byn(x);for(let R of w.d.keys())JRt(_,x,t(R));w.v=x,delete w.e}else w.v=x,delete w.e;(!O||!Object.is(E,w.v))&&(++w.n,T&&yyn(T,x))},a=(_,w,x)=>{var O;let E=t(w);if(zRt(E)&&(E.m&&!x?.has(w)||Array.from(E.d).every(([B,U])=>a(_,B,x).n===U)))return E;E.d.clear();let T=!0,R=B=>{if(URt(w,B)){let H=t(B);if(!zRt(H))if(P2e(B))i(B,H,B.init);else throw new Error("no atom init");return Ahe(H)}let U=a(_,B,x);try{return Ahe(U)}finally{if(T)HRt(_,w,E,B,U);else{let H=N6();HRt(H,w,E,B,U),p(H,w,E),bL(H)}}},N,D,F={get signal(){return N||(N=new AbortController),N.signal},get setSelf(){return(Pl.env?Pl.env.MODE:void 0)!=="production"&&!M2e(w)&&console.warn("setSelf function cannot be used with read-only atom"),!D&&M2e(w)&&(D=(...B)=>{if((Pl.env?Pl.env.MODE:void 0)!=="production"&&T&&console.warn("setSelf function cannot be called in sync"),!T)return f(w,...B)}),D}};try{let B=e(w,R,F);if(i(w,E,B),I2e(B)){(O=B.onCancel)==null||O.call(B,()=>N?.abort());let U=()=>{if(E.m){let H=N6();p(H,w,E),bL(H)}};B.then(U,U)}return E}catch(B){return delete E.v,E.e=B,++E.n,E}finally{T=!1}},s=_=>Ahe(a(void 0,_)),u=(_,w,x)=>{var O,E;let T=new Map;for(let R of((O=x.m)==null?void 0:O.t)||[])T.set(R,t(R));for(let R of x.p)T.set(R,t(R));return(E=vyn(_,w))==null||E.forEach(R=>{T.set(R,t(R))}),T};function l(_,w,x){let O=[],E=new Set,T=new Set,R=[[w,x]];for(;R.length>0;){let[N,D]=R[R.length-1];if(T.has(N)){R.pop();continue}if(E.has(N)){O.push([N,D,D.n]),T.add(N),R.pop();continue}E.add(N);for(let[F,B]of u(_,N,D))N!==F&&!E.has(F)&&R.push([F,B])}return[O,T]}let c=(_,w,x)=>{let[O,E]=l(_,w,x),T=new Set([w]);for(let R=O.length-1;R>=0;--R){let[N,D,F]=O[R],B=!1;for(let U of D.d.keys())if(U!==N&&T.has(U)){B=!0;break}B&&(a(_,N,E),p(_,N,D),F!==D.n&&(R2e(_,N,D),T.add(N))),E.delete(N)}},d=(_,w,...x)=>{let O=!0,E=R=>Ahe(a(_,R)),T=(R,...N)=>{let D=t(R);try{if(URt(w,R)){if(!P2e(R))throw new Error("atom not writable");let F=D.n,B=N[0];i(R,D,B),p(_,R,D),F!==D.n&&(R2e(_,R,D),c(_,R,D));return}else return d(_,R,...N)}finally{O||bL(_)}};try{return r(w,E,T,...x)}finally{O=!1}},f=(_,...w)=>{let x=N6();try{return d(
<user_custom_instructions>
${t}
</user_custom_instructions>`:e}async function PN(t){let e=Y0();if(!t)return J("No UserMemoryManager provided to getSystemPromptWithMemory"),e;let r=await t.getUserMemoryPrompt();return r?`${r}
${e}`:e}function kyn(t){return t.activeModels=dAt(t.activeModels,SO),t.activeEmbeddingModels=dAt(t.activeEmbeddingModels,Dz),t}function Qn(t){return`${t.name}|${t.provider}`}function dAt(t,e){let r=new Map;return e.filter(n=>n.core).forEach(n=>{r.set(Qn(n),{...n})}),t.forEach(n=>{let o=Qn(n),i=r.get(o);if(i){let a=e.find(s=>s.name===n.name&&s.provider===n.provider);a?r.set(o,{...a,...n,isBuiltIn:!0,believerExclusive:a.believerExclusive}):r.set(o,{...n,isBuiltIn:i.isBuiltIn})}else r.set(o,n)}),Array.from(r.values())}var ei,_L,Pt=v(()=>{TN();J3();zr();Dt();ei=j6(),_L=th(Ls)});function Eo(t,e=!1){try{if(t instanceof Error){let n=t?.cause instanceof Error?t.cause.message:t?.cause?String(t.cause):"",o=e&&t.stack?t.stack:"",i=[t.message];return n&&i.push(`more message: ${n}`),o&&i.push(o),i.join(`
`)}return JSON.stringify(t)??String(t)}catch{return String(t)}}var H2e=v(()=>{});var V2e,ey,L6=v(()=>{H2e();wr();V2e=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(){if(!this.initialized)try{if(!this.hasVault()){this.initialized=!0;return}let e=this.getLogPath();if(await app.vault.adapter.exists(e)){let o=(await app.vault.adapter.read(e)).split(/\r?\n/).filter(i=>i.length>0);o.length>this.maxLines?this.buffer=o.slice(o.length-this.maxLines):this.buffer=o}}catch{this.buffer=[]}finally{this.initialized=!0}}hasVault(){try{return typeof app<"u"&&!!app.vault?.adapter}catch{return!1}}sanitizeForSingleLine(e){if(e instanceof Error){let r=Eo(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{}}async openLogFile(){if(await this.flush(),!this.hasVault())return;let e=this.getLogPath(),r=app.vault.getAbstractFileByPath(e);try{if(!r){let o=e.includes("/")?e.split("/").slice(0,-1).join("/"):"";o&&await ty(o),r=await app.vault.create(e,this.buffer.join(`
`)+(this.buffer.length?`
`:""))}await app.workspace.getLeaf(!0).openFile(r)}catch{}}},ey=V2e.getInstance()});function J(...t){ce().debug&&console.log(...t),ey.append("INFO",...t)}function ue(...t){ce().debug&&console.error(...t),ey.append("ERROR",...t)}function Ot(...t){ce().debug&&console.warn(...t),ey.append("WARN",...t)}function Lhe(t){ey.appendMarkdownBlock(t)}function mAt(t,e){if(ce().debug)try{if(typeof console.table=="function"){Array.isArray(e)&&e.length>0?console.table(t,e):console.table(t);return}}catch{}J("Table:",JSON.stringify(t))}var Dt=v(()=>{Pt();L6()});var hAt=S((J2e,F6)=>{(function(t,e){typeof J2e=="object"&&typeof F6<"u"?F6.exports=e():typeof define=="function"&&define.amd?define(e):t.moment=e()})(J2e,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,P){return Object.prototype.hasOwnProperty.call(C,P)}function a(C){if(Object.getOwnPropertyNames)return Object.getOwnPropertyNames(C).length===0;var P;for(P in C)if(i(C,P))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,P){var I=[],k,K=C.length;for(k=0;k<K;++k)I.push(P(C[k],k));return I}function d(C,P){for(var I in P)i(P,I)&&(C[I]=P[I]);return i(P,"toString")&&(C.toString=P.toString),i(P,"valueOf")&&(C.valueOf=P.valueOf),C}function f(C,P,I,k){return Twt(C,P,I,k,!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 P=Object(this),I=P.length>>>0,k;for(k=0;k<I;k++)if(k in P&&C.call(this,P[k],k,P))return!0;return!1};function g(C){if(C._isValid==null){var P=m(C),I=h.call(P.parsedDateParts,function(K){return K!=null}),k=!isNaN(C._d.getTime())&&P.overflow<0&&!P.empty&&!P.invalidEra&&!P.invalidMonth&&!P.invalidWeekday&&!P.weekdayMismatch&&!P.nullInput&&!P.invalidFormat&&!P.userInvalidated&&(!P.meridiem||P.meridiem&&I);if(C._strict&&(k=k&&P.charsLeftOver===0&&P.unusedTokens.length===0&&P.bigHour===void 0),Object.isFrozen==null||!Object.isFrozen(C))C._isValid=k;else return k}return C._isValid}function y(C){var P=f(NaN);return C!=null?d(m(P),C):m(P).userInvalidated=!0,P}var b=e.momentProperties=[],_=!1;function w(C,P){var I,k,K,le=b.length;if(s(P._isAMomentObject)||(C._isAMomentObject=P._isAMomentObject),s(P._i)||(C._i=P._i),s(P._f)||(C._f=P._f),s(P._l)||(C._l=P._l),s(P._strict)||(C._strict=P._strict),s(P._tzm)||(C._tzm=P._tzm),s(P._isUTC)||(C._isUTC=P._isUTC),s(P._offset)||(C._offset=P._offset),s(P._pf)||(C._pf=m(P)),s(P._locale)||(C._locale=P._locale),le>0)for(I=0;I<le;I++)k=b[I],K=P[k],s(K)||(C[k]=K);return C}function x(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 O(C){return C instanceof x||C!=null&&C._isAMomentObject!=null}function E(C){e.suppressDeprecationWarnings===!1&&typeof console<"u"&&console.warn&&console.warn("Deprecation warning: "+C)}function T(C,P){var I=!0;return d(function(){if(e.deprecationHandler!=null&&e.deprecationHandler(null,C),I){var k=[],K,le,je,en=arguments.length;for(le=0;le<en;le++){if(K="",typeof arguments[le]=="object"){K+=`
[`+le+"] ";for(je in arguments[0])i(arguments[0],je)&&(K+=je+": "+arguments[0][je]+", ");K=K.slice(0,-2)}else K=arguments[le];k.push(K)}E(C+`
Arguments: `+Array.prototype.slice.call(k).join("")+`
`+new Error().stack),I=!1}return P.apply(this,arguments)},P)}var R={};function N(C,P){e.deprecationHandler!=null&&e.deprecationHandler(C,P),R[C]||(E(P),R[C]=!0)}e.suppressDeprecationWarnings=!1,e.deprecationHandler=null;function D(C){return typeof Function<"u"&&C instanceof Function||Object.prototype.toString.call(C)==="[object Function]"}function F(C){var P,I;for(I in C)i(C,I)&&(P=C[I],D(P)?this[I]=P:this["_"+I]=P);this._config=C,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)}function B(C,P){var I=d({},C),k;for(k in P)i(P,k)&&(o(C[k])&&o(P[k])?(I[k]={},d(I[k],C[k]),d(I[k],P[k])):P[k]!=null?I[k]=P[k]:delete I[k]);for(k in C)i(C,k)&&!i(P,k)&&o(C[k])&&(I[k]=d({},I[k]));return I}function U(C){C!=null&&this.set(C)}var H;Object.keys?H=Object.keys:H=function(C){var P,I=[];for(P in C)i(C,P)&&I.push(P);return I};var G={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"};function ie(C,P,I){var k=this._calendar[C]||this._calendar.sameElse;return D(k)?k.call(P,I):k}function oe(C,P,I){var k=""+Math.abs(C),K=P-k.length,le=C>=0;return(le?I?"+":"":"-")+Math.pow(10,Math.max(0,K)).toString().substr(1)+k}var z=/(\[[^\[]*\])|(\\)?([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,Q=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,re={},Z={};function $(C,P,I,k){var K=k;typeof k=="string"&&(K=function(){return this[k]()}),C&&(Z[C]=K),P&&(Z[P[0]]=function(){return oe(K.apply(this,arguments),P[1],P[2])}),I&&(Z[I]=function(){return this.localeData().ordinal(K.apply(this,arguments),C)})}function q(C){return C.match(/\[[\s\S]/)?C.replace(/^\[|\]$/g,""):C.replace(/\\/g,"")}function Y(C){var P=C.match(z),I,k;for(I=0,k=P.length;I<k;I++)Z[P[I]]?P[I]=Z[P[I]]:P[I]=q(P[I]);return function(K){var le="",je;for(je=0;je<k;je++)le+=D(P[je])?P[je].call(K,C):P[je];return le}}function j(C,P){return C.isValid()?(P=A(P,C.localeData()),re[P]=re[P]||Y(P),re[P](C)):C.localeData().invalidDate()}function A(C,P){var I=5;function k(K){return P.longDateFormat(K)||K}for(Q.lastIndex=0;I>=0&&Q.test(C);)C=C.replace(Q,k),Q.lastIndex=0,I-=1;return C}var W={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 V(C){var P=this._longDateFormat[C],I=this._longDateFormat[C.toUpperCase()];return P||!I?P:(this._longDateFormat[C]=I.match(z).map(function(k){return k==="MMMM"||k==="MM"||k==="DD"||k==="dddd"?k.slice(1):k}).join(""),this._longDateFormat[C])}var se="Invalid date";function be(){return this._invalidDate}var Ee="%d",Ae=/\d{1,2}/;function ht(C){return this._ordinal.replace("%d",C)}var Rt={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 Ze(C,P,I,k){var K=this._relativeTime[I];return D(K)?K(C,P,I,k):K.replace(/%d/i,C)}function Dr(C,P){var I=this._relativeTime[C>0?"future":"past"];return D(I)?I(P):I.replace(/%s/i,P)}var Vt={};function jt(C,P){var I=C.toLowerCase();Vt[I]=Vt[I+"s"]=Vt[P]=C}function Fe(C){return typeof C=="string"?Vt[C]||Vt[C.toLowerCase()]:void 0}function hn(C){var P={},I,k;for(k in C)i(C,k)&&(I=Fe(k),I&&(P[I]=C[k]));return P}var gt={};function qe(C,P){gt[C]=P}function Te(C){var P=[],I;for(I in C)i(C,I)&&P.push({unit:I,priority:gt[I]});return P.sort(function(k,K){return k.priority-K.priority}),P}function Ce(C){return C%4===0&&C%100!==0||C%400===0}function De(C){return C<0?Math.ceil(C)||0:Math.floor(C)}function Re(C){var P=+C,I=0;return P!==0&&isFinite(P)&&(I=De(P)),I}function nt(C,P){return function(I){return I!=null?(He(this,C,I),e.updateOffset(this,P),this):_n(this,C)}}function _n(C,P){return C.isValid()?C._d["get"+(C._isUTC?"UTC":"")+P]():NaN}function He(C,P,I){C.isValid()&&!isNaN(I)&&(P==="FullYear"&&Ce(C
`),e=e.trim(),e}async function $z(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=Bhe(t);e?n.replaceRange(a,o,i):n.replaceRange(a,i),new ry.Notice("Message inserted into the active note.")}function Uhe(t,e){let r;return(...n)=>{clearTimeout(r),r=setTimeout(()=>t(...n),e)}}function zhe(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 EAt(){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 ree(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 Kyn(t){return typeof t=="string"?t.startsWith("gpt-5"):(t.modelName||t.model||"").startsWith("gpt-5")}function z6(t){let e=typeof t=="string"?t:t.modelName||t.model||"",r=ree(e),n=Kyn(e),o=e.startsWith("claude-3-7-sonnet")||e.startsWith("claude-sonnet-4");return{isOSeries:r,isGPT5:n,isThinkingEnabled:o}}function wL(t,e="system"){return ree(t)?"human":e}function X2e(){let t=["3rd party (openai-format)","ollama","lm-studio","azure openai","copilot-plus","copilot-plus-jina"];return Object.entries(J6).filter(([e])=>!t.includes(e)).map(([e])=>e)}function H6(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."};let r=!!X2e().find(i=>i===t.provider),n=AN[t.provider],o=!t.apiKey&&!e[n];return r&&o?{hasApiKey:!1,errorNotice:`Please configure API Key for ${t.name} in settings first.
Path: Settings > copilot plugin > Basic Tab > Set Keys`}:{hasApiKey:!0}}function Hhe(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>e.text).join(""):String(t||"")}function Lz(t){let r=Hhe(t).replace(/<think>[\s\S]*?<\/think>/g,"");return r=r.replace(/<think>[\s\S]*$/g,""),r.trim()}function V6(t){return Hhe(t).replace(/<errorChunk>[\s\S]*?<\/errorChunk>/g,"").trim()}function PAt(){return crypto.randomUUID()}async function Xh(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 Vhe(t,e,r="Operation"){let{TimeoutError:n}=await Promise.resolve().then(()=>(MN(),gAt)),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 Y2e(){let t=app.workspace.getActiveViewOfType(ry.MarkdownView);return t?t.getState().source===!0:!0}function nee(t){return new TextEncoder().encode(t).length}function Q2e(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}var yAt,ry,K2e,eee,Byn,Uyn,vAt,Zh,Hyn,wr=v(()=>{gd();zr();Dt();yAt=L(hAt()),ry=require("obsidian");H2e();K2e={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})};Byn=t=>t.last?.modelName||t.last?.model,Uyn=t=>t.last?.retriever!==void 0,vAt=t=>Byn(t)||Uyn(t),Zh=(t,e="local")=>{let r=(0,yAt.default)(t);return e==="utc"&&r.utc(),{fileName:r.format("YYYYMMDD_HHmmss"),display:r.format("YYYY/MM/DD HH:mm:ss"),epoch:r.valueOf()}};Hyn=/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|shorts\/)|youtu\.be\/)([^\s&]+)/});var K6,eHe,oee,gd=v(()=>{_O();Tv();xv();E2e();wr();K6=class K6{static createNewLLMChain(e){let{llm:r,memory:n,prompt:o,abortController:i}=e,a=r.withConfig({signal:i?.signal}),s=El.from([{input:u=>u.input,memory:()=>n.loadMemoryVariables({})},{input:u=>u.input,history:u=>u.memory.history},o,a]);return K6.instances.set("llm_chain",s),console.log("New LLM chain created."),s}static getLLMChainFromMap(e){let r=K6.instances.get("llm_chain");return r||(r=K6.createNewLLMChain(e)),r}static createConversationalRetrievalChain(e,r,n){let{llm:o,retriever:i,systemMessage:a}=e,u=uu.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=uu.fromTemplate(`{system_message}
Answer the question with as detailed as possible based only on the following context:
{context}
Question: {question}
`),d=g=>g.map(b=>`Human: ${b[0]}
Assistant: ${b[1]}`).join(`
`),f=El.from([{question:g=>(n&&console.log("Input Question: ",g.question),g.question),chat_history:g=>{let y=d(g.chat_history);return n&&console.log("Formatted Chat History: ",y),y}},u,o,new whe,g=>{let y=Lz(g),b=V6(y);return n&&console.log("Standalone Question: ",b),b}]),p=async g=>(r(g),GQ(g)),m=El.from([{context:i.pipe(p),question:new xu,system_message:()=>a},c,o]);return f.pipe(m)}};K6.instances=new Map;eHe=K6,oee=eHe});var iee=v(()=>{});var tHe,Fz,Tc,Xs,TO,wO,Wyn,Gyn,Zyn,z2e,pAt,RAt,aee,u_,see,kz,uee,lee,rHe,qz,nHe,oHe,W6,EO,IN,ny,OO,SL,SO,vL,Dz,W2e,J6,AN,AAt,Nn,Jhe,Xw,G6,Ls,Yw,zr=v(()=>{J3();gd();iee();tHe="https://api.brevilabs.com/v1",Fz="https://models.brevilabs.com/v1",Tc="copilot-chat-view",Xs="user",TO="ai",wO="copilot",Wyn=`${wO}/copilot-conversations`,Gyn=`${wO}/copilot-custom-prompts`,Zyn=`${wO}/memory`,z2e=wO,pAt=`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.`,RAt=`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.
`,aee="note_context",u_="selected_text",see="variable",kz="variable_note",uee="embedded_pdf",lee="dataview_block",rHe="retrieved_document",qz=6e3,nHe=.4,oHe=448e3,W6=3e4,EO={DEFAULT:"",READING_FILES:"Reading files",SEARCHING_WEB:"Searching the web",READING_FILE_TREE:"Reading file tree"},IN={SETTINGS:"settings",EXPIRED_MODAL:"expired_modal",CHAT_MODE_SELECT:"chat_mode_select",MODE_SELECT_TOOLTIP:"mode_select_tooltip"},ny={MAX_TOKENS:6e3,TEMPERATURE:.1,REASONING_EFFORT:"low",VERBOSITY:"medium"},OO=(h=>(h.OPENAI="openai",h.OPENAI_FORMAT="3rd party (openai-format)",h.AZURE_OPENAI="azure openai",h.ANTHROPIC="anthropic",h.COHEREAI="cohereai",h.GOOGLE="google",h.XAI="xai",h.OPENROUTERAI="openrouterai",h.GROQ="groq",h.OLLAMA="ollama",h.LM_STUDIO="lm-studio",h.COPILOT_PLUS="copilot-plus",h.MISTRAL="mistralai",h.DEEPSEEK="deepseek",h.AMAZON_BEDROCK="amazon-bedrock",h))(OO||{}),SL={reasoning:"This model supports general reasoning tasks.",vision:"This model supports image inputs.",websearch:"This model can access the internet."},SO=[{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:"x-ai/grok-4-fast",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!1,projectEnabled:!0},{name:"gpt-5",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"gpt-5-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"gpt-5-nano",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"gpt-4.1",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-4.1-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-4.1-nano",provider:"openai",enabled:!0,isBuiltIn:!0,capabilities:["vision"]},{name:"claude-sonnet-4-20250514",provider:"anthropic",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"claude-3-7-sonnet-latest",provider:"anthropic",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"grok-3-beta",provider:"xai",enabled:!0,isBuiltIn:!0},{name:"grok-3-mini-beta",provider:"xai",enabled:!0,isBuiltIn:!0},{name:"gemini-2.5-flash",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gemini-2.5-flash-lite",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gemini-2.5-pro",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"azure-openai",provider:"azure openai",enabled:!0,isBuiltIn:!0},{name:"deepseek-chat",provider:"deepseek",enabled:!0,isBuiltIn:!0},{name:"deepseek-reasoner",provider:"deepseek",enabled:!0,isBuiltIn:!0,capabilities:["reasoning"]}],vL=(l=>(l.OPENAI="openai",l.COHEREAI="cohereai",l.GOOGLE="google",l.AZURE_OPENAI="azure openai",l.OLLAMA="ollama",l.LM_STUDIO="lm-studio",l.OPENAI_FORMAT="3rd party (openai-format)",l.COPILOT_PLUS="copilot-plus",l.COPILOT_PLUS_JINA="copilot-plus-jina",l))(vL||{}),Dz=[{name:"copilot-plus-small",provider:"copilot-plus",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,plusExclusive:!0},{name:"copilot-plus-large",provider:"copilot-plus-jina",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,plusExclusive:!0,believerExclusive:!0,dimensions:1024},{name:"copilot-plus-multilingual",provider:"copilot-plus-jina",enabled:!0,isBuiltIn:!0,isEmbeddingModel:
`+NHe+t}var jHe=!1;function DHe(t,e){if(!t||jHe)return"";jHe=!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{jHe=!1,Error.prepareStackTrace=r}return(t=t?t.displayName||t.name:"")?xee(t):""}function Lbn(t){switch(t.tag){case 5:return xee(t.type);case 16:return xee("Lazy");case 13:return xee("Suspense");case 19:return xee("SuspenseList");case 0:case 2:case 15:return t=DHe(t.type,!1),t;case 11:return t=DHe(t.type.render,!1),t;case 1:return t=DHe(t.type,!0),t;default:return""}}function iVe(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 iK:return"Fragment";case oK:return"Portal";case rVe:return"Profiler";case ZVe:return"StrictMode";case nVe:return"Suspense";case oVe:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case NNt:return(t.displayName||"Context")+".Consumer";case INt:return(t._context.displayName||"Context")+".Provider";case XVe:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case YVe:return e=t.displayName||null,e!==null?e:iVe(t.type)||"Memo";case EL:e=t._payload,t=t._init;try{return iVe(t(e))}catch{}}return null}function Fbn(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 iVe(e);case 8:return e===ZVe?"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 BL(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function DNt(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function kbn(t){var e=DNt(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 cge(t){t._valueTracker||(t._valueTracker=kbn(t))}function $Nt(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var r=e.getValue(),n="";return t&&(n=DNt(t)?t.checked?"true":"false":t.value),t=n,t!==r?(e.setValue(t),!0):!1}function Fge(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 aVe(t,e){var r=e.checked;return oc({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??t._wrapperState.initialChecked})}function EIt(t,e){var r=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;r=BL(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 LNt(t,e){e=e.checked,e!=null&&GVe(t,"checked",e,!1)}function sVe(t,e){LNt(t,e);var r=BL(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")?uVe(t,e.type,r):e.hasOwnProperty("defaultValue")&&uVe(t,e.type,BL(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}fun
`).replace(K_n,"")}function Sge(t,e,r){if(e=YIt(e),YIt(t)!==e&&r)throw Error(tt(425))}function Jge(){}var SVe=null,CVe=null;function xVe(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 OVe=typeof setTimeout=="function"?setTimeout:void 0,W_n=typeof clearTimeout=="function"?clearTimeout:void 0,QIt=typeof Promise=="function"?Promise:void 0,G_n=typeof queueMicrotask=="function"?queueMicrotask:typeof QIt<"u"?function(t){return QIt.resolve(null).then(t).catch(Z_n)}:OVe;function Z_n(t){setTimeout(function(){throw t})}function VHe(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),Uee(e);return}n--}else r!=="$"&&r!=="$?"&&r!=="$!"||n++;r=o}while(r);Uee(e)}function $L(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 eNt(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 RK=Math.random().toString(36).slice(2),DO="__reactFiber$"+RK,Kee="__reactProps$"+RK,BN="__reactContainer$"+RK,TVe="__reactEvents$"+RK,X_n="__reactListeners$"+RK,Y_n="__reactHandles$"+RK;function Xz(t){var e=t[DO];if(e)return e;for(var r=t.parentNode;r;){if(e=r[BN]||r[DO]){if(r=e.alternate,e.child!==null||r!==null&&r.child!==null)for(t=eNt(t);t!==null;){if(r=t[DO])return r;t=eNt(t)}return e}t=r,r=t.parentNode}return null}function rte(t){return t=t[DO]||t[BN],!t||t.tag!==5&&t.tag!==6&&t.tag!==13&&t.tag!==3?null:t}function lK(t){if(t.tag===5||t.tag===6)return t.stateNode;throw Error(tt(33))}function fye(t){return t[Kee]||null}var EVe=[],cK=-1;function HL(t){return{current:t}}function sl(t){0>cK||(t.current=EVe[cK],EVe[cK]=null,cK--)}function qu(t,e){cK++,EVe[cK]=t.current,t.current=e}var UL={},uy=HL(UL),f_=HL(!1),r4=UL;function CK(t,e){var r=t.type.contextTypes;if(!r)return UL;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 p_(t){return t=t.childContextTypes,t!=null}function Kge(){sl(f_),sl(uy)}function tNt(t,e,r){if(uy.current!==UL)throw Error(tt(168));qu(uy,e),qu(f_,r)}function O1t(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(tt(108,Fbn(t)||"Unknown",o));return oc({},r,n)}function Wge(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||UL,r4=uy.current,qu(uy,t),qu(f_,f_.current),!0}function rNt(t,e,r){var n=t.stateNode;if(!n)throw Error(tt(169));r?(t=O1t(t,e,r4),n.__reactInternalMemoizedMergedChildContext=t,sl(f_),sl(uy),qu(uy,t)):sl(f_),qu(f_,r)}var $N=null,pye=!1,JHe=!1;function T1t(t){$N===null?$N=[t]:$N.push(t)}function Q_n(t){pye=!0,T1t(t)}function VL(){if(!JHe&&$N!==null){JHe=!0;var t=0,e=Ys;try{var r=$N;for(Ys=1;t<r.length;t++){var n=r[t];do n=n(!0);while(n!==null)}$N=null,pye=!1}catch(o){throw $N!==null&&($N=$N.slice(t+1)),XNt(eJe,VL),o}finally{Ys=e,JHe=!1}}return null}var dK=[],fK=0,Gge=null,Zge=0,rS=[],nS=0,n4=null,LN=1,FN="";function Gz(t,e){dK[fK++]=Zge,dK[fK++]=Gge,Gge=t,Zge=e}function E1t(t,e,r){rS[nS++]=LN,rS[nS++]=FN,rS[nS++]=n4,n4=t;var n=LN;t=FN;var o=32-oC(n)-1;n&=~(1<<o),r+=1;var i=32-oC(e)+o;if(30<i){var a=o-o%5;i=(n&(1<<a)-1).toString(32),n>>=a,o-=a,LN=1<<32-oC(e)+o|r<<o|n,FN=i+t}else LN=1<<i|r<<o|n,FN=t}function lJe(t){t.return!==null&&(Gz(t,1),E1t(t,1,0))}function cJe(t){for(;t===Gge;)Gge=dK[--fK],dK[fK]=null,Zge=dK[--fK],dK[fK]=null;for(;t===n4;)n4=rS[--nS],rS[nS]=null,FN=rS[--nS],rS[nS]=null,LN=rS[--nS],rS[nS]=null}var Rv=null,Mv=null,Ml=!1,nC=null;function P1t(t,e){var r=oS(5,n
Error generating stack: `+i.message+`
`+i.stack}return{value:t,source:e,stack:o,digest:null}}function XHe(t,e,r){return{value:t,source:null,stack:r??null,digest:e??null}}function NVe(t,e){try{console.error(e.value)}catch(r){setTimeout(function(){throw r})}}var uvn=typeof WeakMap=="function"?WeakMap:Map;function rjt(t,e,r){r=kN(-1,r),r.tag=3,r.payload={element:null};var n=e.value;return r.callback=function(){oye||(oye=!0,zVe=n),NVe(t,e)},r}function njt(t,e,r){r=kN(-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(){NVe(t,e)}}var i=t.stateNode;return i!==null&&typeof i.componentDidCatch=="function"&&(r.callback=function(){NVe(t,e),typeof n!="function"&&(FL===null?FL=new Set([this]):FL.add(this));var a=e.stack;this.componentDidCatch(e.value,{componentStack:a!==null?a:""})}),r}function fNt(t,e,r){var n=t.pingCache;if(n===null){n=t.pingCache=new uvn;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=Svn.bind(null,t,e,r),e.then(t,t))}function pNt(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 mNt(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=kN(-1,1),e.tag=2,LL(r,e,1))),r.lanes|=1),t):(t.flags|=65536,t.lanes=o,t)}var lvn=HN.ReactCurrentOwner,d_=!1;function ab(t,e,r,n){e.child=t===null?D1t(e,null,r,n):OK(e,t.child,r,n)}function hNt(t,e,r,n,o){r=r.render;var i=e.ref;return vK(e,o),n=wJe(t,e,r,n,i,o),r=SJe(),t!==null&&!d_?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,zN(t,e,o)):(Ml&&r&&lJe(e),e.flags|=1,ab(t,e,n,o),e.child)}function gNt(t,e,r,n,o){if(t===null){var i=r.type;return typeof i=="function"&&!IJe(i)&&i.defaultProps===void 0&&r.compare===null&&r.defaultProps===void 0?(e.tag=15,e.type=i,ojt(t,e,i,n,o)):(t=Lge(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:Hee,r(a,n)&&t.ref===e.ref)return zN(t,e,o)}return e.flags|=1,t=qL(i,n),t.ref=e.ref,t.return=e,e.child=t}function ojt(t,e,r,n,o){if(t!==null){var i=t.memoizedProps;if(Hee(i,n)&&t.ref===e.ref)if(d_=!1,e.pendingProps=n=i,(t.lanes&o)!==0)(t.flags&131072)!==0&&(d_=!0);else return e.lanes=t.lanes,zN(t,e,o)}return jVe(t,e,r,n,o)}function ijt(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},qu(hK,Pv),Pv|=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,qu(hK,Pv),Pv|=t,null;e.memoizedState={baseLanes:0,cachePool:null,transitions:null},n=i!==null?i.baseLanes:r,qu(hK,Pv),Pv|=n}else i!==null?(n=i.baseLanes|r,e.memoizedState=null):n=r,qu(hK,Pv),Pv|=n;return ab(t,e,o,r),e.child}function ajt(t,e){var r=e.ref;(t===null&&r!==null||t!==null&&t.ref!==r)&&(e.flags|=512,e.flags|=2097152)}function jVe(t,e,r,n,o){var i=p_(r)?r4:uy.current;return i=CK(e,i),vK(e,o),r=wJe(t,e,r,n,i,o),n=SJe(),t!==null&&!d_?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,zN(t,e,o)):(Ml&&n&&lJe(e),e.flags|=1,ab(t,e,r,o),e.child)}function yNt(t,e,r,n,o){if(p_(r)){var i=!0;Wge(e)}else i=!1;if(vK(e,o),e.stateNode===null)jge(t,e),N1t(e,r,n),IVe(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=aS(l):(l=p_(r)?r4:uy.current,l=CK(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)&&uNt(e,a,n,l),PL=!1;var f=e.memoizedState;a.state=f,Qge(e,n,a,o),u=e.memoizedState,s!==n||f!==u||f_.current||PL?(typeof c=="function"&&(AVe(e,r,c,n),u=e.memoizedState),(s=PL||sNt(e,r,s,n,f,u,l))?(d||typeof a.UNSAFE_componentWillMount
`)}});var L4t=S(Cbe=>{"use strict";Object.defineProperty(Cbe,"__esModule",{value:!0});Cbe.CohereTimeoutError=void 0;var t3e=class t extends Error{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};Cbe.CohereTimeoutError=t3e});var Pc=S(UK=>{"use strict";Object.defineProperty(UK,"__esModule",{value:!0});UK.CohereTimeoutError=UK.CohereError=void 0;var sSn=$4t();Object.defineProperty(UK,"CohereError",{enumerable:!0,get:function(){return sSn.CohereError}});var uSn=L4t();Object.defineProperty(UK,"CohereTimeoutError",{enumerable:!0,get:function(){return uSn.CohereTimeoutError}})});var F4t=S(zO=>{"use strict";var lSn=zO&&zO.__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]}),cSn=zO&&zO.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),dSn=zO&&zO.__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"&&lSn(r,e,n[o]);return cSn(r,e),r}}();Object.defineProperty(zO,"__esModule",{value:!0});zO.BadRequestError=void 0;var fSn=dSn(Pc()),r3e=class t extends fSn.CohereError{constructor(e,r){super({message:"BadRequestError",statusCode:400,body:e,rawResponse:r}),Object.setPrototypeOf(this,t.prototype)}};zO.BadRequestError=r3e});var k4t=S(HO=>{"use strict";var pSn=HO&&HO.__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]}),mSn=HO&&HO.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),hSn=HO&&HO.__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"&&pSn(r,e,n[o]);return mSn(r,e),r}}();Object.defineProperty(HO,"__esModule",{value:!0});HO.UnauthorizedError=void 0;var gSn=hSn(Pc()),n3e=class t extends gSn.CohereError{constructor(e,r){super({message:"UnauthorizedError",statusCode:401,body:e,rawResponse:r}),Object.setPrototypeOf(this,t.prototype)}};HO.UnauthorizedError=n3e});var q4t=S(VO=>{"use strict";var ySn=VO&&VO.__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]}),bSn=VO&&VO.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),_Sn=VO&&VO.__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"&&ySn(r,e,n[o]);return bSn(r,e),r}}();Object.defineProperty(VO,"__esModule",{value:!0});VO.ForbiddenError=void 0;var vSn=_Sn(Pc()),o3e=class t extends vSn.CohereError{constructor(e,r){super({message:"ForbiddenError",statusCode:403,body:e,rawResponse:r}),Object.setPrototypeOf(this,t.prototype)}};VO.ForbiddenError=o3e});var B4t=S(JO=>{"use strict";var wSn=JO&&JO.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(
`));return r(o)}});var h3t,vCn,wCn,SCn,CCn,xCn,g3t=v(()=>{h3t=async t=>{let e=t?.Bucket||"";if(typeof t.Bucket=="string"&&(t.Bucket=e.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),xCn(e)){if(t.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!CCn(e)||e.indexOf(".")!==-1&&!String(t.Endpoint).startsWith("http:")||e.toLowerCase()!==e||e.length<3)&&(t.ForcePathStyle=!0);return t.DisableMultiRegionAccessPoints&&(t.disableMultiRegionAccessPoints=!0,t.DisableMRAP=!0),t},vCn=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,wCn=/(\d+\.){3}\d+/,SCn=/\.\./,CCn=t=>vCn.test(t)&&!wCn.test(t)&&!SCn.test(t),xCn=t=>{let[e,r,n,,,o]=t.split(":"),i=e==="arn"&&t.split(":").length>=6,a=!!(i&&r&&n&&o);if(i&&!a)throw new Error(`Invalid ARN: ${t} was an invalid ARN.`);return a}});var y3t=v(()=>{g3t()});var b3t,_3t=v(()=>{b3t=(t,e,r)=>{let n=async()=>{let o=r[t]??r[e];return typeof o=="function"?o():o};return t==="credentialScope"||e==="CredentialScope"?async()=>{let o=typeof r.credentials=="function"?await r.credentials():r.credentials;return o?.credentialScope??o?.CredentialScope}:t==="accountId"||e==="AccountId"?async()=>{let o=typeof r.credentials=="function"?await r.credentials():r.credentials;return o?.accountId??o?.AccountId}:t==="endpoint"||e==="endpoint"?async()=>{let o=await n();if(o&&typeof o=="object"){if("url"in o)return o.url.href;if("hostname"in o){let{protocol:i,hostname:a,port:s,path:u}=o;return`${i}//${a}${s?":"+s:""}${u}`}}return o}:n}});var v3t,w3t=v(()=>{v3t=async t=>{}});function S3t(t){let e={};if(t=t.replace(/^\?/,""),t)for(let r of t.split("&")){let[n,o=null]=r.split("=");n=decodeURIComponent(n),o&&(o=decodeURIComponent(o)),n in e?Array.isArray(e[n])?e[n].push(o):e[n]=[e[n],o]:e[n]=o}return e}var C3t=v(()=>{});var sF,d_e=v(()=>{C3t();sF=t=>{if(typeof t=="string")return sF(new URL(t));let{hostname:e,pathname:r,port:n,protocol:o,search:i}=t,a;return i&&(a=S3t(i)),{hostname:e,port:n?parseInt(n):void 0,protocol:o,path:r,query:a}}});var f_e,p_e=v(()=>{d_e();f_e=t=>typeof t=="object"?"url"in t?sF(t.url):t:sF(t)});var x3t,OCn,X3e=v(()=>{y3t();_3t();w3t();p_e();x3t=async(t,e,r,n)=>{if(!r.endpoint){let a=await v3t(r.serviceId||"");a&&(r.endpoint=()=>Promise.resolve(f_e(a)))}let o=await OCn(t,e,r);if(typeof r.endpointProvider!="function")throw new Error("config.endpointProvider is not set.");return r.endpointProvider(o,n)},OCn=async(t,e,r)=>{let n={},o=e?.getEndpointParameterInstructions?.()||{};for(let[i,a]of Object.entries(o))switch(a.type){case"staticContextParams":n[i]=a.value;break;case"contextParams":n[i]=t[a.name];break;case"clientContextParams":case"builtInParams":n[i]=await b3t(a.name,i,r)();break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(a))}return Object.keys(o).length===0&&Object.assign(n,r),String(r.serviceId).toLowerCase()==="s3"&&await h3t(n),n}});var O3t=v(()=>{X3e();p_e()});var T3t,Y3e=v(()=>{pC();X3e();T3t=({config:t,instructions:e})=>(r,n)=>async o=>{let i=await x3t(o.input,{getEndpointParameterInstructions(){return e}},{...t},n);n.endpointV2=i,n.authSchemes=i.properties?.authSchemes;let a=n.authSchemes?.[0];if(a){n.signing_region=a.signingRegion,n.signing_service=a.signingName;let u=nT(n)?.selectedHttpAuthScheme?.httpAuthOption;u&&(u.signingProperties=Object.assign(u.signingProperties||{},{signing_region:a.signingRegion,signingRegion:a.signingRegion,signing_service:a.signingName,signingName:a.signingName,signingRegionSet:a.signingRegionSet},a.properties))}return r({...o})}});var E3t,Q3e=v(()=>{E3t=(t,e)=>r=>async n=>{let{response:o}=await r(n);try{let i=await e(o,t);return{response:o,output:i}}catch(i){if(Object.defineProperty(i,"$response",{value:o}),!("$metadata"in i)){let a="Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";i.message+=`
`+a,typeof i.$responseBodyText<"u"&&i.$response&&(i.$response.body=i.$responseBodyText)}throw i}}});var P3t,e6e=v(()=>{P3t=(t,e)=>(r,n)=>async o=>{let i=n.endpointV2?.url&&t.urlParser?async()=>t.urlParser(n.endpointV2.url):t.endpoint;if(!i)throw new Error("No valid endpoint provider available.");let a=await e(o.input,{...t,endpoint:i});return r({...o,request:a})}});function Tr(t,e,r){return{applyToStack:n=>{n.add(E3t(t,r),TCn),n.add(P3t(t,e),Hte)}}}var TCn,Hte,M3t=v(()=>{Q3e();e6e();TCn={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},Hte={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});var Ki=v(()=>{Q3e();M3t();e6e()});var t6e,Er,R3t=v(()=>{Ki();Y3e();t6e={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:Hte.name},Er=(t,e)=>({applyToStack:r=>{r.addRelativeTo(T3t({config:t,instructions:e}),t6e)}})});var m_e,A3t=v(()=>{pC();p_e();m_e=t=>{let e=t.tls??!0,{endpoint:r}=t,n=r!=null?async()=>f_e(await dy(r)()):void 0;return{...t,endpoint:n,tls:e,isCustomEndpoint:!!r,useDualstackEndpoint:dy(t.useDualstackEndpoint??!1),useFipsEndpoint:dy(t.useFipsEndpoint??!1)}}});var I3t=v(()=>{});var Li=v(()=>{O3t();Y3e();R3t();A3t();I3t()});var ECn,h_e,N3t=v(()=>{Li();c_e();ECn={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:t6e.name},h_e=(t,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:r})=>({applyToStack:n=>{n.addRelativeTo(Z3e(t,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:r}),ECn)}})});var MKi,j3t=v(()=>{Ki();c_e();MKi={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:Hte.name}});var D3t=v(()=>{c_e();N3t();j3t()});var $3t=v(()=>{});var L3t=v(()=>{$3t()});var F3t=v(()=>{bd()});var k3t=v(()=>{});var q3t=v(()=>{});function PCn(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return{...e,[r]:Array.isArray(n)?[...n]:n}},{})}var x4,B3t=v(()=>{x4=class t{constructor(e){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=PCn(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 U3t=v(()=>{});var z3t=v(()=>{});var H3t=v(()=>{});var Vte=v(()=>{L3t();F3t();k3t();q3t();B3t();U3t();z3t();H3t()});var MCn,RCn,V3t,r6e=v(()=>{Vte();bd();pC();MCn=t=>e=>{throw e},RCn=(t,e)=>{},V3t=t=>(e,r)=>async n=>{if(!x4.isInstance(n.request))return e(n);let i=nT(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||MCn)(a));return(u.successHandler||RCn)(l.response,a),l}});var mC,oT,Jte,g_e=v(()=>{(function(t){t.STANDARD="standard",t.ADAPTIVE="adaptive"})(mC||(mC={}));oT=3,Jte=mC.STANDARD});var J3t,K3t,W3t,G3t,Z3t=v(()=>{J3t=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],K3t=["TimeoutError","RequestTimeout","RequestTimeoutException"],W3t=[500,502,503,504],G3t=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"]});var ACn,WK,y_e,X3t,Kte=v(()=>{Z3t();ACn=t=>t.$metadata?.clockSkewCorrected,WK=t=>t.$m
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 fF(i);if(o==="hex")return rKt(i);if(o===void 0||o==="utf8"||o==="utf-8")return O_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(oKt);if(e=!0,iKt(t))return n(t);if(w6e(t))return t;throw new Error(`Cannot transform payload to web stream, got ${t}`)}})},iKt=t=>typeof Blob=="function"&&t instanceof Blob});var uKt=v(()=>{});var lKt=v(()=>{});var C6e=v(()=>{b6e();L6t();sKt();uKt();lKt();S6e()});var mF,cKt=v(()=>{C6e();mF=async(t=new Uint8Array,e)=>{if(t instanceof Uint8Array)return o1.mutate(t);if(!t)return o1.mutate(new Uint8Array);let r=e.streamCollector(t);return o1.mutate(await r)}});var yr,x6e,dKt=v(()=>{d6e();bd();yr=class{constructor(){this.middlewareStack=YK()}static classBuilder(){return new x6e}resolveMiddlewareWithContext(e,r,n,{middlewareFn:o,clientName:i,commandName:a,inputFilterSensitiveLog:s,outputFilterSensitiveLog:u,smithyContext:l,additionalContext:c,CommandCtor:d}){for(let g of o.bind(this)(d,e,r,n))this.middlewareStack.use(g);let f=e.concat(this.middlewareStack),{logger:p}=r,m={logger:p,clientName:i,commandName:a,inputFilterSensitiveLog:s,outputFilterSensitiveLog:u,[JK]:{commandInstance:this,...l},...c},{requestHandler:h}=r;return f.resolve(g=>h.handle(g.request,n||{}),m)}},x6e=class{constructor(){this._init=()=>{},this._ep={},this._middlewareFn=()=>[],this._commandName="",this._clientName="",this._additionalContext={},this._smithyContext={},this._inputFilterSensitiveLog=e=>e,this._outputFilterSensitiveLog=e=>e,this._serializer=null,this._deserializer=null}init(e){this._init=e}ep(e){return this._ep=e,this}m(e){return this._middlewareFn=e,this}s(e,r,n={}){return this._smithyContext={service:e,operation:r,...n},this}c(e={}){return this._additionalContext=e,this}n(e,r){return this._clientName=e,this._commandName=r,this}f(e=n=>n,r=n=>n){return this._inputFilterSensitiveLog=e,this._outputFilterSensitiveLog=r,this}ser(e){return this._serializer=e,this}de(e){return this._deserializer=e,this}build(){let e=this,r;return r=class extends yr{static getEndpointParameterInstructions(){return e._ep}constructor(...[n]){super(),this.serialize=e._serializer,this.deserialize=e._deserializer,this.input=n??{},e._init(this)}resolveMiddleware(n,o,i){return this.resolveMiddlewareWithContext(n,o,i,{CommandCtor:r,middlewareFn:e._middlewareFn,clientName:e._clientName,commandName:e._commandName,inputFilterSensitiveLog:e._inputFilterSensitiveLog,outputFilterSensitiveLog:e._outputFilterSensitiveLog,smithyContext:e._smithyContext,additionalContext:e._additionalContext})}}}}});var E_e,fKt=v(()=>{E_e="***SensitiveInformation***"});var P_e,pKt=v(()=>{P_e=(t,e)=>{for(let r of Object.keys(t)){let n=t[r],o=async function(a,s,u){let l=new n(a);if(typeof s=="function")this.send(l,s);else if(typeof u=="function"){if(typeof s!="object")throw new Error(`Expected http options but got ${typeof s}`);this.send(l,s||{},u)}else return this.send(l,s)},i=(r[0].toLowerCase()+r.slice(1)).replace(/Command$/,"");e.prototype[i]=o}}});var R4,FCn,mKt,kCn,hKt,gKt,yKt,O6e,qCn,t5,ti,bKt,_Kt,BCn,Yte,Qte,T6e,vKt,wKt,SKt,E6e=v(()=>{R4=t=>{if(t!=null){if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return String(e)!==String(t)&&SKt.warn(wKt(`Expected number but observed string: ${t}`)),e}if(typeof t=="number")return t;throw new TypeError(`Expected number, got ${typeof t}: ${t}`)}},FCn=Math.ceil(34028234663852886e22),mKt=t=>{let e=R4(t);if(e!==void 0&&!Number.isNaN(e)&&e!==1/0&&e!==-1/0&&Math.abs(e)>FCn)throw new TypeError(`Expected 32-bit float, got ${t}`);return e},kCn=t=>{if(t!=null){if(Number.isInteger(t)&&!Number.isNaN(t))return t;throw new TypeError(`Expected integer, got ${typeof t}: ${t}`)}},hKt=t=>O6e(t,32),gKt=t=>O6e(
`).slice(0,5).filter(e=>!e.includes("stackTraceWarning")).join(`
`),SKt={warn:console.warn}});var UCn,zCn,CKt,HCn,xKt,CGi,xGi,OGi,M_e,OKt,TGi,VCn,JCn,KCn,A4,WCn,GCn,P6e,TKt=v(()=>{E6e();UCn=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],zCn=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),CKt=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=zCn.exec(t);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");let[r,n,o,i,a,s,u,l]=e,c=T6e(P6e(n)),d=A4(o,"month",1,12),f=A4(i,"day",1,31);return OKt(c,d,f,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l})},HCn=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),xKt=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=HCn.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=T6e(P6e(n)),f=A4(o,"month",1,12),p=A4(i,"day",1,31),m=OKt(d,f,p,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l});return c.toUpperCase()!="Z"&&m.setTime(m.getTime()-GCn(c)),m},CGi=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$/),xGi=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$/),OGi=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})$/),M_e=t=>{if(t==null)return;let e;if(typeof t=="number")e=t;else if(typeof t=="string")e=bKt(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))},OKt=(t,e,r,n)=>{let o=e-1;return JCn(t,o,r),new Date(Date.UTC(t,o,r,A4(n.hours,"hour",0,23),A4(n.minutes,"minute",0,59),A4(n.seconds,"seconds",0,60),WCn(n.fractionalMilliseconds)))},TGi=50*365*24*60*60*1e3,VCn=[31,28,31,30,31,30,31,31,30,31,30,31],JCn=(t,e,r)=>{let n=VCn[e];if(e===1&&KCn(t)&&(n=29),r>n)throw new TypeError(`Invalid day for ${UCn[e]} in ${t}: ${r}`)},KCn=t=>t%4===0&&(t%100!==0||t%400===0),A4=(t,e,r,n)=>{let o=vKt(P6e(t));if(o<r||o>n)throw new TypeError(`${e} must be between ${r} and ${n}, inclusive`);return o},WCn=t=>t==null?0:_Kt("0."+t)*1e3,GCn=t=>{let e=t[0],r=1;if(e=="+")r=1;else if(e=="-")r=-1;else throw new TypeError(`Offset direction, ${e}, must be "+" or "-"`);let n=Number(t.substring(1,3)),o=Number(t.substring(4,6));return r*(n*60+o)*60*1e3},P6e=t=>{let e=0;for(;e<t.length-1&&t.charAt(e)==="0";)e++;return e===0?t:t.slice(e)}});var r5,ac,M6e=v(()=>{r5=class t extends Error{constructor(e){super(e.message),Object.setPrototypeOf(this,t.prototype),this.name=e.name,this.$fault=e.$fault,this.$metadata=e.$metadata}},ac=(t,e={})=>{Object.entries(e).filter(([,n])=>n!==void 0).forEach(([n,o])=>{(t[n]==null||t[n]==="")&&(t[n]=o)});let r=t.message||t.Message||"UnknownError";return t.message=r,delete t.Message,t}});var ZCn,R_e,XCn,EKt=v(()=>{M6e();ZCn=({output:t,parsedBody:e,exceptionCtor:r,errorCode:n})=>{let o=XCn(t),i=o.httpStatusCode?o.httpStatusCode+"":void 0,a=new r({name:e?.code||e?.Code||n||i||"UnknownError",$fault:"client",$metadata:o});throw ac(a,e)},R_e=t=>({output:e,parsedBody:r,errorCode:n})=>{ZCn({output:e,parsedBody:r,exceptionCtor:t,errorCode:n})},XCn=t=>({httpStatusCode:t.statusCode,requestId:t.headers["x-amzn-requestid"]??t.headers["x-amzn-request-id"]??t.headers["x-amz-request-id"],extendedRequestId:t.headers["x-amz-id-2"],cfId:t.headers["x-amz-cf-id"]})});var A_e,PKt=v(()=>{A_e=t=>{switch(t){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region
`);return this.signString(m,{signingDate:n,signingRegion:s,signingService:a})}async signMessage(e,{signingDate:r=new Date,signingRegion:n,signingService:o}){return this.signEvent({headers:this.headerFormatter.format(e.message.headers),payload:e.message.body},{signingDate:r,signingRegion:n,signingService:o,priorSignature:e.priorSignature}).then(a=>({message:e.message,signature:a}))}async signString(e,{signingDate:r=new Date,signingRegion:n,signingService:o}={}){let i=await this.credentialProvider();this.validateResolvedCredentials(i);let a=n??await this.regionProvider(),{shortDate:s}=W_e(r),u=new this.sha256(await this.getSigningKey(i,a,s,o));return u.update(yF(e)),hC(await u.digest())}async signRequest(e,{signingDate:r=new Date,signableHeaders:n,unsignableHeaders:o,signingRegion:i,signingService:a}={}){let s=await this.credentialProvider();this.validateResolvedCredentials(s);let u=i??await this.regionProvider(),l=K_e(e),{longDate:c,shortDate:d}=W_e(r),f=H_e(d,u,a??this.service);l.headers[J6e]=c,s.sessionToken&&(l.headers[Z5t]=s.sessionToken);let p=await sre(l,this.sha256);!dWt(are,l.headers)&&this.applyChecksum&&(l.headers[are]=p);let m=V_e(l,o,n),h=await this.getSignature(c,f,this.getSigningKey(s,u,d,a),this.createCanonicalRequest(l,m,p));return l.headers[V6e]=`${U_e} Credential=${s.accessKeyId}/${f}, SignedHeaders=${hWt(m)}, Signature=${h}`,l}createCanonicalRequest(e,r,n){let o=Object.keys(r).sort();return`${e.method}
${this.getCanonicalPath(e)}
${X6e(e)}
${o.map(i=>`${i}:${r[i]}`).join(`
`)}
${o.join(";")}
${n}`}async createStringToSign(e,r,n){let o=new this.sha256;o.update(yF(n));let i=await o.digest();return`${U_e}
${e}
${r}
${hC(i)}`}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 mS(n).replace(/%2F/g,"/")}return e}async getSignature(e,r,n,o){let i=await this.createStringToSign(e,r,o),a=new this.sha256(await n);return a.update(yF(i)),hC(await a.digest())}getSigningKey(e,r,n,o){return iWt(this.sha256,e,n,r,o||this.service)}validateResolvedCredentials(e){if(typeof e!="object"||typeof e.accessKeyId!="string"||typeof e.secretAccessKey!="string")throw new Error("Resolved credential object is not valid")}},W_e=t=>{let e=pWt(t).replace(/[\-:]/g,"");return{longDate:e,shortDate:e.slice(0,8)}},hWt=t=>Object.keys(t).sort().join(";")});var yWt=v(()=>{gWt();Z6e();Y6e();Q6e();rKe();nKe();G6e()});var G_e,bWt=v(()=>{hF();yWt();G_e=t=>{let e;t.credentials&&(e=n5t(t.credentials,r5t,j6e)),e||(t.credentialDefaultProvider?e=i5(t.credentialDefaultProvider(Object.assign({},t,{parentClientConfig:t}))):e=async()=>{throw new Error("`credentials` is missing")});let{signingEscapePath:r=!0,systemClockOffset:n=t.systemClockOffset||0,sha256:o}=t,i;return t.signer?i=i5(t.signer):t.regionInfoProvider?i=()=>i5(t.region)().then(async a=>[await t.regionInfoProvider(a,{useFipsEndpoint:await t.useFipsEndpoint(),useDualstackEndpoint:await t.useDualstackEndpoint()})||{},a]).then(([a,s])=>{let{signingRegion:u,signingService:l}=a;t.signingRegion=t.signingRegion||u||s,t.signingName=t.signingName||l||t.serviceId;let c={...t,credentials:e,region:t.signingRegion,service:t.signingName,sha256:o,uriEscapePath:r},d=t.signerConstructor||ure;return new d(c)}):i=async a=>{a=Object.assign({},{name:"sigv4",signingName:t.signingName||t.defaultSigningName,signingRegion:await i5(t.region)(),properties:{}},a);let s=a.signingRegion,u=a.signingName;t.signingRegion=t.signingRegion||s,t.signingName=t.signingName||u||t.serviceId;let l={...t,credentials:e,region:t.signingRegion,service:t.signingName,sha256:o,uriEscapePath:r},c=t.signerConstructor||ure;return new c(l)},{...t,systemClockOffset:n,signingEscapePath:r,credentials:e,signer:i}}});var _Wt=v(()=>{F5t();k5t();bWt()});var vWt=v(()=>{_Wt()});var wWt=v(()=>{});var SWt=v(()=>{an()});var Z_e,oKe=v(()=>{an();Z_e=(t,e)=>mF(t,e).then(r=>e.utf8Encoder(r))});var Xc,CWt,xWt,OWt=v(()=>{oKe();Xc=(t,e)=>Z_e(t,e).then(r=>{if(r.length)try{return JSON.parse(r)}catch(n){throw n?.name==="SyntaxError"&&Object.defineProperty(n,"$responseBodyText",{value:r}),n}return{}}),CWt=async(t,e)=>{let r=await Xc(t,e);return r.message=r.message??r.Message,r},xWt=(t,e)=>{let r=(i,a)=>Object.keys(i).find(s=>s.toLowerCase()===a.toLowerCase()),n=i=>{let a=i;return typeof a=="number"&&(a=a.toString()),a.indexOf(",")>=0&&(a=a.split(",")[0]),a.indexOf(":")>=0&&(a=a.split(":")[0]),a.indexOf("#")>=0&&(a=a.split("#")[1]),a},o=r(t.headers,"x-amzn-errortype");if(o!==void 0)return n(t.headers[o]);if(e.code!==void 0)return n(e.code);if(e.__type!==void 0)return n(e.__type)}});var X_e=S(i1=>{"use strict";var TWt=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",yxn=TWt+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",EWt="["+TWt+"]["+yxn+"]*",bxn=new RegExp("^"+EWt+"$"),_xn=function(t,e){let r=[],n=e.exec(t);for(;n;){let o=[];o.startIndex=e.lastIndex-n[0].length;let i=n.length;for(let a=0;a<i;a++)o.push(n[a]);r.push(o),n=e.exec(t)}return r},vxn=function(t){let e=bxn.exec(t);return!(e===null||typeof e>"u")};i1.isExist=function(t){return typeof t<"u"};i1.isEmptyObject=function(t){return Object.keys(t).length===0};i1.merge=function(t,e,r){if(e){let n=Object.keys(e),o=n.length;for(let i=0;i<o;i++)r==="strict"?t[n[i]]=[e[n[i]]]:t[n[i]]=e[n[i]]}};i1.getValue=function(t){return i1.isExist(t)?t:""};i1.isName=vxn;i1.getAllMatches=_xn;i1.nameRegexp=EWt});var aKe=S(IWt=>{"use strict";var iKe=X_e(),wxn={allowBooleanAttributes:!1,unpairedTags:[]};IWt.validate=function(t,e){e=Object.assign({},wxn,e);let
`&&t[i]!=="\r";i++)u+=t[i];if(u=u.trim(),u[u.length-1]==="/"&&(u=u.substring(0,u.length-1),i--),!Mxn(u)){let d;return u.trim().length===0?d="Invalid space after '<'.":d="Tag '"+u+"' is an invalid name.",Yc("InvalidTag",d,cb(t,i))}let l=xxn(t,i);if(l===!1)return Yc("InvalidAttr","Attributes for '"+u+"' have open quote.",cb(t,i));let c=l.value;if(i=l.index,c[c.length-1]==="/"){let d=i-c.length;c=c.substring(0,c.length-1);let f=AWt(c,e);if(f===!0)n=!0;else return Yc(f.err.code,f.err.msg,cb(t,d+f.err.line))}else if(s)if(l.tagClosed){if(c.trim().length>0)return Yc("InvalidTag","Closing tag '"+u+"' can't have attributes or invalid starting.",cb(t,a));if(r.length===0)return Yc("InvalidTag","Closing tag '"+u+"' has not been opened.",cb(t,a));{let d=r.pop();if(u!==d.tagName){let f=cb(t,d.tagStartPos);return Yc("InvalidTag","Expected closing tag '"+d.tagName+"' (opened in line "+f.line+", col "+f.col+") instead of closing tag '"+u+"'.",cb(t,a))}r.length==0&&(o=!0)}}else return Yc("InvalidTag","Closing tag '"+u+"' doesn't have proper closing.",cb(t,i));else{let d=AWt(c,e);if(d!==!0)return Yc(d.err.code,d.err.msg,cb(t,i-c.length+d.err.line));if(o===!0)return Yc("InvalidXml","Multiple possible root nodes found.",cb(t,i));e.unpairedTags.indexOf(u)!==-1||r.push({tagName:u,tagStartPos:a}),n=!0}for(i++;i<t.length;i++)if(t[i]==="<")if(t[i+1]==="!"){i++,i=RWt(t,i);continue}else if(t[i+1]==="?"){if(i=MWt(t,++i),i.err)return i}else break;else if(t[i]==="&"){let d=Exn(t,i);if(d==-1)return Yc("InvalidChar","char '&' is not expected.",cb(t,i));i=d}else if(o===!0&&!PWt(t[i]))return Yc("InvalidXml","Extra text at the end",cb(t,i));t[i]==="<"&&i--}}else{if(PWt(t[i]))continue;return Yc("InvalidChar","char '"+t[i]+"' is not expected.",cb(t,i))}if(n){if(r.length==1)return Yc("InvalidTag","Unclosed tag '"+r[0].tagName+"'.",cb(t,r[0].tagStartPos));if(r.length>0)return Yc("InvalidXml","Invalid '"+JSON.stringify(r.map(i=>i.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return Yc("InvalidXml","Start tag expected.",1);return!0};function PWt(t){return t===" "||t===" "||t===`
`||t==="\r"}function MWt(t,e){let r=e;for(;e<t.length;e++)if(t[e]=="?"||t[e]==" "){let n=t.substr(r,e-r);if(e>5&&n==="xml")return Yc("InvalidXml","XML declaration allowed only at the start of the document.",cb(t,e));if(t[e]=="?"&&t[e+1]==">"){e++;break}else continue}return e}function RWt(t,e){if(t.length>e+5&&t[e+1]==="-"&&t[e+2]==="-"){for(e+=3;e<t.length;e++)if(t[e]==="-"&&t[e+1]==="-"&&t[e+2]===">"){e+=2;break}}else if(t.length>e+8&&t[e+1]==="D"&&t[e+2]==="O"&&t[e+3]==="C"&&t[e+4]==="T"&&t[e+5]==="Y"&&t[e+6]==="P"&&t[e+7]==="E"){let r=1;for(e+=8;e<t.length;e++)if(t[e]==="<")r++;else if(t[e]===">"&&(r--,r===0))break}else if(t.length>e+9&&t[e+1]==="["&&t[e+2]==="C"&&t[e+3]==="D"&&t[e+4]==="A"&&t[e+5]==="T"&&t[e+6]==="A"&&t[e+7]==="["){for(e+=8;e<t.length;e++)if(t[e]==="]"&&t[e+1]==="]"&&t[e+2]===">"){e+=2;break}}return e}var Sxn='"',Cxn="'";function xxn(t,e){let r="",n="",o=!1;for(;e<t.length;e++){if(t[e]===Sxn||t[e]===Cxn)n===""?n=t[e]:n!==t[e]||(n="");else if(t[e]===">"&&n===""){o=!0;break}r+=t[e]}return n!==""?!1:{value:r,index:e,tagClosed:o}}var Oxn=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function AWt(t,e){let r=iKe.getAllMatches(t,Oxn),n={};for(let o=0;o<r.length;o++){if(r[o][1].length===0)return Yc("InvalidAttr","Attribute '"+r[o][2]+"' has no space in starting.",lre(r[o]));if(r[o][3]!==void 0&&r[o][4]===void 0)return Yc("InvalidAttr","Attribute '"+r[o][2]+"' is without value.",lre(r[o]));if(r[o][3]===void 0&&!e.allowBooleanAttributes)return Yc("InvalidAttr","boolean attribute '"+r[o][2]+"' is not allowed.",lre(r[o]));let i=r[o][2];if(!Pxn(i))return Yc("InvalidAttr","Attribute '"+i+"' is an invalid name.",lre(r[o]));if(!n.hasOwnProperty(i))n[i]=1;else return Yc("InvalidAttr","Attribute '"+i+"' is repeated.",lre(r[o]))}return!0}function Txn(t,e){let r=/\d/;for(t[e]==="x"&&(e++,r=/[\da-fA-F]/);e<t.length;e++){if(t[e]===";")return e;if(!t[e].match(r))break}return-1}function Exn(t,e){if(e++,t[e]===";")return-1;if(t[e]==="#")return e++,Txn(t,e);let r=0;for(;e<t.length;e++,r++)if(!(t[e].match(/\w/)&&r<20)){if(t[e]===";")break;return-1}return e}function Yc(t,e,r){return{err:{code:t,msg:e,line:r.line||r,col:r.col}}}function Pxn(t){return iKe.isName(t)}function Mxn(t){return iKe.isName(t)}function cb(t,e){let r=t.substring(0,e).split(/\r?\n/);return{line:r.length,col:r[r.length-1].length+1}}function lre(t){return t.startIndex+t[1].length}});var jWt=S(sKe=>{var NWt={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,r){return t}},Rxn=function(t){return Object.assign({},NWt,t)};sKe.buildOptions=Rxn;sKe.defaultOptions=NWt});var $Wt=S((ZXi,DWt)=>{"use strict";var uKe=class{constructor(e){this.tagname=e,this.child=[],this[":@"]={}}add(e,r){e==="__proto__"&&(e="#__proto__"),this.child.push({[e]:r})}addChild(e){e.tagname==="__proto__"&&(e.tagname="#__proto__"),e[":@"]&&Object.keys(e[":@"]).length>0?this.child.push({[e.tagname]:e.child,":@":e[":@"]}):this.child.push({[e.tagname]:e.child})}};DWt.exports=uKe});var FWt=S((XXi,LWt)=>{var Axn=X_e();function Ixn(t,e){let r={};if(t[e+3]==="O"&&t[e+4]==="C"&&t[e+5]==="T"&&t[e+6]==="Y"&&t[e+7]==="P"&&t[e+8]==="E"){e=e+9;let n=1,o=!1,i=!1,a="";for(;e<t.length;e++)if(t[e]==="<"&&!i){if(o&&Dxn(t,e))e+=7,[entityName,val,e]=Nxn(t,e+1),val.indexOf("&")===-1&&(r[kxn(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(o&&$xn(t,e))e+=8;else if(o&&Lxn(t,e))e+=8;else if(o&&Fxn(t,e))e+=9;else if(jxn)i=!0;else throw new Error("Invalid DOCTYPE");n++,a=""}else if(t[e]===">"){if(i?t[e-1]==="-"&&t[e-2]==="-"&&(i=!1,n--):n--,n==
`);let e=new cre("!xml"),r=e,n="",o="";for(let i=0;i<t.length;i++)if(t[i]==="<")if(t[i+1]==="/"){let s=j4(t,">",i,"Closing Tag is not closed."),u=t.substring(i+2,s).trim();if(this.options.removeNSPrefix){let d=u.indexOf(":");d!==-1&&(u=u.substr(d+1))}this.options.transformTagName&&(u=this.options.transformTagName(u)),r&&(n=this.saveTextToParentTag(n,r,o));let l=o.substring(o.lastIndexOf(".")+1);if(u&&this.options.unpairedTags.indexOf(u)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${u}>`);let c=0;l&&this.options.unpairedTags.indexOf(l)!==-1?(c=o.lastIndexOf(".",o.lastIndexOf(".")-1),this.tagsNodeStack.pop()):c=o.lastIndexOf("."),o=o.substring(0,c),r=this.tagsNodeStack.pop(),n="",i=s}else if(t[i+1]==="?"){let s=cKe(t,i,!1,"?>");if(!s)throw new Error("Pi Tag is not closed.");if(n=this.saveTextToParentTag(n,r,o),!(this.options.ignoreDeclaration&&s.tagName==="?xml"||this.options.ignorePiTags)){let u=new cre(s.tagName);u.add(this.options.textNodeName,""),s.tagName!==s.tagExp&&s.attrExpPresent&&(u[":@"]=this.buildAttributesMap(s.tagExp,o,s.tagName)),this.addChild(r,u,o)}i=s.closeIndex+1}else if(t.substr(i+1,3)==="!--"){let s=j4(t,"-->",i+4,"Comment is not closed.");if(this.options.commentPropName){let u=t.substring(i+4,s-2);n=this.saveTextToParentTag(n,r,o),r.add(this.options.commentPropName,[{[this.options.textNodeName]:u}])}i=s}else if(t.substr(i+1,2)==="!D"){let s=Vxn(t,i);this.docTypeEntities=s.entities,i=s.i}else if(t.substr(i+1,2)==="!["){let s=j4(t,"]]>",i,"CDATA is not closed.")-2,u=t.substring(i+9,s);n=this.saveTextToParentTag(n,r,o);let l=this.parseTextData(u,r.tagname,o,!0,!1,!0,!0);l==null&&(l=""),this.options.cdataPropName?r.add(this.options.cdataPropName,[{[this.options.textNodeName]:u}]):r.add(this.options.textNodeName,l),i=s+2}else{let s=cKe(t,i,this.options.removeNSPrefix),u=s.tagName,l=s.rawTagName,c=s.tagExp,d=s.attrExpPresent,f=s.closeIndex;this.options.transformTagName&&(u=this.options.transformTagName(u)),r&&n&&r.tagname!=="!xml"&&(n=this.saveTextToParentTag(n,r,o,!1));let p=r;if(p&&this.options.unpairedTags.indexOf(p.tagname)!==-1&&(r=this.tagsNodeStack.pop(),o=o.substring(0,o.lastIndexOf("."))),u!==e.tagname&&(o+=o?"."+u:u),this.isItStopNode(this.options.stopNodes,o,u)){let m="";if(c.length>0&&c.lastIndexOf("/")===c.length-1)u[u.length-1]==="/"?(u=u.substr(0,u.length-1),o=o.substr(0,o.length-1),c=u):c=c.substr(0,c.length-1),i=s.closeIndex;else if(this.options.unpairedTags.indexOf(u)!==-1)i=s.closeIndex;else{let g=this.readStopNodeData(t,l,f+1);if(!g)throw new Error(`Unexpected end of ${l}`);i=g.i,m=g.tagContent}let h=new cre(u);u!==c&&d&&(h[":@"]=this.buildAttributesMap(c,o,u)),m&&(m=this.parseTextData(m,u,o,!0,d,!0,!0)),o=o.substr(0,o.lastIndexOf(".")),h.add(this.options.textNodeName,m),this.addChild(r,h,o)}else{if(c.length>0&&c.lastIndexOf("/")===c.length-1){u[u.length-1]==="/"?(u=u.substr(0,u.length-1),o=o.substr(0,o.length-1),c=u):c=c.substr(0,c.length-1),this.options.transformTagName&&(u=this.options.transformTagName(u));let m=new cre(u);u!==c&&d&&(m[":@"]=this.buildAttributesMap(c,o,u)),this.addChild(r,m,o),o=o.substr(0,o.lastIndexOf("."))}else{let m=new cre(u);this.tagsNodeStack.push(r),u!==c&&d&&(m[":@"]=this.buildAttributesMap(c,o,u)),this.addChild(r,m,o),r=m}n="",i=f}}else n+=t[i];return e.child};function Qxn(t,e,r){let n=this.options.updateTag(e.tagname,r,e[":@"]);n===!1||(typeof n=="string"&&(e.tagname=n),t.addChild(e))}var eOn=function(t){if(this.options.processEntities){for(let e in this.docTypeEntities){let r=this.docTypeEntities[e];t=t.replace(r.regx,r.val)}for(let e in this.lastEntities){let r=this.lastEntities[e];t=t.replace(r.regex,r.val)}if(this.options.htmlEntities)for(let e in this.htmlEntities){let r=this.htmlEntities[e];t=t.replace(r.regex,r.val)}t=t.replace(this.ampEntity.regex,this.ampEntity.val)}return t};function tOn(t,e,r,n){return t&&(n===void 0&&(n=Object.keys(e.child).length===0),t=this.parseTextData(t,e.tagname,r,!1,e[":@"]?Object.keys(e[":@"]).length!==0:!1,n),t!==void 0&&t!==""&&e.add(this.options.textNodeName,t),t=""),t}function rOn(t,e,r){let
`;function mOn(t,e){let r="";return e.format&&e.indentBy.length>0&&(r=pOn),ZWt(t,e,"",r)}function ZWt(t,e,r,n){let o="",i=!1;for(let a=0;a<t.length;a++){let s=t[a],u=hOn(s);if(u===void 0)continue;let l="";if(r.length===0?l=u:l=`${r}.${u}`,u===e.textNodeName){let m=s[u];gOn(l,e)||(m=e.tagValueProcessor(u,m),m=XWt(m,e)),i&&(o+=n),o+=m,i=!1;continue}else if(u===e.cdataPropName){i&&(o+=n),o+=`<![CDATA[${s[u][0][e.textNodeName]}]]>`,i=!1;continue}else if(u===e.commentPropName){o+=n+`<!--${s[u][0][e.textNodeName]}-->`,i=!0;continue}else if(u[0]==="?"){let m=GWt(s[":@"],e),h=u==="?xml"?"":n,g=s[u][0][e.textNodeName];g=g.length!==0?" "+g:"",o+=h+`<${u}${g}${m}?>`,i=!0;continue}let c=n;c!==""&&(c+=e.indentBy);let d=GWt(s[":@"],e),f=n+`<${u}${d}`,p=ZWt(s[u],e,l,c);e.unpairedTags.indexOf(u)!==-1?e.suppressUnpairedNode?o+=f+">":o+=f+"/>":(!p||p.length===0)&&e.suppressEmptyNode?o+=f+"/>":p&&p.endsWith(">")?o+=f+`>${p}${n}</${u}>`:(o+=f+">",p&&n!==""&&(p.includes("/>")||p.includes("</"))?o+=n+e.indentBy+p+n:o+=p,o+=`</${u}>`),i=!0}return o}function hOn(t){let e=Object.keys(t);for(let r=0;r<e.length;r++){let n=e[r];if(t.hasOwnProperty(n)&&n!==":@")return n}}function GWt(t,e){let r="";if(t&&!e.ignoreAttributes)for(let n in t){if(!t.hasOwnProperty(n))continue;let o=e.attributeValueProcessor(n,t[n]);o=XWt(o,e),o===!0&&e.suppressBooleanAttributes?r+=` ${n.substr(e.attributeNamePrefix.length)}`:r+=` ${n.substr(e.attributeNamePrefix.length)}="${o}"`}return r}function gOn(t,e){t=t.substr(0,t.length-e.textNodeName.length-1);let r=t.substr(t.lastIndexOf(".")+1);for(let n in e.stopNodes)if(e.stopNodes[n]===t||e.stopNodes[n]==="*."+r)return!0;return!1}function XWt(t,e){if(t&&t.length>0&&e.processEntities)for(let r=0;r<e.entities.length;r++){let n=e.entities[r];t=t.replace(n.regex,n.val)}return t}YWt.exports=mOn});var t8t=S((nYi,e8t)=>{"use strict";var yOn=QWt(),bOn={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function bF(t){this.options=Object.assign({},bOn,t),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=wOn),this.processTextOrObjNode=_On,this.options.format?(this.indentate=vOn,this.tagEndChar=`>
`,this.newLine=`
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}bF.prototype.build=function(t){return this.options.preserveOrder?yOn(t,this.options):(Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t}),this.j2x(t,0).val)};bF.prototype.j2x=function(t,e){let r="",n="";for(let o in t)if(Object.prototype.hasOwnProperty.call(t,o))if(typeof t[o]>"u")this.isAttribute(o)&&(n+="");else if(t[o]===null)this.isAttribute(o)?n+="":o[0]==="?"?n+=this.indentate(e)+"<"+o+"?"+this.tagEndChar:n+=this.indentate(e)+"<"+o+"/"+this.tagEndChar;else if(t[o]instanceof Date)n+=this.buildTextValNode(t[o],o,"",e);else if(typeof t[o]!="object"){let i=this.isAttribute(o);if(i)r+=this.buildAttrPairStr(i,""+t[o]);else if(o===this.options.textNodeName){let a=this.options.tagValueProcessor(o,""+t[o]);n+=this.replaceEntitiesValue(a)}else n+=this.buildTextValNode(t[o],o,"",e)}else if(Array.isArray(t[o])){let i=t[o].length,a="",s="";for(let u=0;u<i;u++){let l=t[o][u];if(!(typeof l>"u"))if(l===null)o[0]==="?"?n+=this.indentate(e)+"<"+o+"?"+this.tagEndChar:n+=this.indentate(e)+"<"+o+"/"+this.tagEndChar;else if(typeof l=="object")if(this.options.oneListGroup){let c=this.j2x(l,e+1);a+=c.val,this.options.attributesGroupName&&l.hasOwnProperty(this.options.attributesGroupName)&&(s+=c.attrStr)}else a+=this.processTextOrObjNode(l,o,e);else if(this.options.oneListGroup){let c=this.options.tagValueProcessor(o,l);c=this.replaceEntitiesValue(c),a+=c}else a+=this.buildTextValNode(l,o,"",e)}this.options.oneListGroup&&(a=this.buildObjectNode(a,o,s,e)),n+=a}else if(this.options.attributesGroupName&&o===this.options.attributesGroupName){let i=Object.keys(t[o]),a=i.length;for(let s=0;s<a;s++)r+=this.buildAttrPairStr(i[s],""+t[o][i[s]])}else n+=this.processTextOrObjNode(t[o],o,e);return{attrStr:r,val:n}};bF.prototype.buildAttrPairStr=function(t,e){return e=this.options.attributeValueProcessor(t,""+e),e=this.replaceEntitiesValue(e),this.options.suppressBooleanAttributes&&e==="true"?" "+t:" "+t+'="'+e+'"'};function _On(t,e,r){let n=this.j2x(t,r+1);return t[this.options.textNodeName]!==void 0&&Object.keys(t).length===1?this.buildTextValNode(t[this.options.textNodeName],e,n.attrStr,r):this.buildObjectNode(n.val,e,n.attrStr,r)}bF.prototype.buildObjectNode=function(t,e,r,n){if(t==="")return e[0]==="?"?this.indentate(n)+"<"+e+r+"?"+this.tagEndChar:this.indentate(n)+"<"+e+r+this.closeTag(e)+this.tagEndChar;{let o="</"+e+this.tagEndChar,i="";return e[0]==="?"&&(i="?",o=""),(r||r==="")&&t.indexOf("<")===-1?this.indentate(n)+"<"+e+r+i+">"+t+o:this.options.commentPropName!==!1&&e===this.options.commentPropName&&i.length===0?this.indentate(n)+`<!--${t}-->`+this.newLine:this.indentate(n)+"<"+e+r+i+this.tagEndChar+t+this.indentate(n)+o}};bF.prototype.closeTag=function(t){let e="";return this.options.unpairedTags.indexOf(t)!==-1?this.options.suppressUnpairedNode||(e="/"):this.options.suppressEmptyNode?e="/":e=`></${t}`,e};bF.prototype.buildTextValNode=function(t,e,r,n){if(this.options.cdataPropName!==!1&&e===this.options.cdataPropName)return this.indentate(n)+`<![CDATA[${t}]]>`+this.newLine;if(this.options.commentPropName!==!1&&e===this.options.commentPropName)return this.indentate(n)+`<!--${t}-->`+this.newLine;if(e[0]==="?")return this.indentate(n)+"<"+e+r+"?"+this.tagEndChar;{let o=this.options.tagValueProcessor(e,t);return o=this.replaceEntitiesValue(o),o===""?this.indentate(n)+"<"+e+r+this.closeTag(e)+this.tagEndChar:this.indentate(n)+"<"+e+r+">"+o+"</"+e+this.tagEndChar}};bF.prototype.replaceEntitiesValue=function(t){if(t&&t.length>0&&this.options.processEntities)for(let e=0;e<this.options.entities.length;e++){let r=this.options.entities[e];t=t.replace(r.regex,r.val)}return t};function vOn(t){return this.options.indentBy.repeat(t)}function wOn(t){return t.startsWith(this.options.attributeNamePrefix)&&t!==this.options.textNodeName?t.substr(this.attrPrefixLen):!1}e8t.exports=bF});var n8t=S((oYi,r8t)=>{"use strict";var SOn=aKe(),COn=WWt(),xOn=t8t();r8t.exports={XMLParser:COn,XMLValidator:SOn,XMLBuilder:xOn}});v
`)?"":void 0});n.addEntity("#xD","\r"),n.addEntity("#10",`
`);let o;try{o=n.parse(r,!0)}catch(u){throw u&&typeof u=="object"&&Object.defineProperty(u,"$responseBodyText",{value:r}),u}let i="#text",a=Object.keys(o)[0],s=o[a];return s[i]&&(s[a]=s[i],delete s[i]),A6e(s)}return{}}),i8t=async(t,e)=>{let r=await aT(t,e);return r.Error&&(r.Error.message=r.Error.message??r.Error.Message),r}});var s8t=v(()=>{wWt();SWt();OWt();a8t()});var D4=v(()=>{S5t();vWt();s8t()});function OOn(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"cognito-identity",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function Y_e(t){return{schemeId:"smithy.api#noAuth"}}var u8t,l8t,c8t,pKe=v(()=>{D4();pC();u8t=async(t,e,r)=>({operation:nT(e).operation,region:await dy(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});l8t=t=>{let e=[];switch(t.operation){case"GetCredentialsForIdentity":{e.push(Y_e(t));break}case"GetId":{e.push(Y_e(t));break}case"GetOpenIdToken":{e.push(Y_e(t));break}case"UnlinkIdentity":{e.push(Y_e(t));break}default:e.push(OOn(t))}return e},c8t=t=>({...G_e(t)})});var d8t,eo,ll=v(()=>{d8t=t=>({...t,useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"cognito-identity"}),eo={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}});var p8t,f8t=v(()=>{p8t={name:"@aws-sdk/client-cognito-identity",description:"AWS SDK for JavaScript Cognito Identity Client for Node.js, Browser and React Native",version:"3.645.0",scripts:{build:"concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'","build:cjs":"node ../../scripts/compilation/inline client-cognito-identity","build:es":"tsc -p tsconfig.es.json","build:include:deps":"lerna run --scope $npm_package_name --include-dependencies build","build:types":"tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4",clean:"rimraf ./dist-* && rimraf *.tsbuildinfo","extract:docs":"api-extractor run --local","generate:client":"node ../../scripts/generate-clients/single-service --solo cognito-identity","test:e2e":"ts-mocha test/**/*.ispec.ts && karma start karma.conf.js"},main:"./dist-cjs/index.js",types:"./dist-types/index.d.ts",module:"./dist-es/index.js",sideEffects:!1,dependencies:{"@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/client-sso-oidc":"3.645.0","@aws-sdk/client-sts":"3.645.0","@aws-sdk/core":"3.635.0","@aws-sdk/credential-provider-node":"3.645.0","@aws-sdk/middleware-host-header":"3.620.0","@aws-sdk/middleware-logger":"3.609.0","@aws-sdk/middleware-recursion-detection":"3.620.0","@aws-sdk/middleware-user-agent":"3.645.0","@aws-sdk/region-config-resolver":"3.614.0","@aws-sdk/types":"3.609.0","@aws-sdk/util-endpoints":"3.645.0","@aws-sdk/util-user-agent-browser":"3.609.0","@aws-sdk/util-user-agent-node":"3.614.0","@smithy/config-resolver":"^3.0.5","@smithy/core":"^2.4.0","@smithy/fetch-http-handler":"^3.2.4","@smithy/hash-node":"^3.0.3","@smithy/invalid-dependency":"^3.0.3","@smithy/middleware-content-length":"^3.0.5","@smithy/middleware-endpoint":"^3.1.0","@smithy/middleware-retry":"^3.0.15","@smithy/middleware-serde":"^3.0.3","@smithy/middleware-stack":"^3.0.3","@smithy/node-config-provider":"^3.1.4","@smithy/node-http-handler":"^3.1.4","@smithy/protocol-http":"^4.1.0","@smithy/smithy-client":"^3.2.0","@smithy/types":"^3.3.0","@smithy/url-parser":"^3.0.3","@smithy/util-base64":"^3.0.0","@smithy/util-body-length-browser":"^3.0.0","@smithy/util-body-length-node":"^3.0.0","@smithy/util-defaults-mode-browser":"^3.0.15","@smithy/util-defaults-mode-node":"^3.0.15","@smithy/util-endpoints":"^2.0.5","@smithy/util-middleware":"^3.0.3","@smithy/util-retry":"^3.0.3","@smithy/util-utf8":"^3.0.0",tslib:"^2.6.2"},devDependencies:{"@aws-sdk/client-iam":"3.645.0","@tsconfig/node16":"16.1.3","@types/chai":"^4.2.11","@types/mocha":"^8.0.4","@types/node":"^16.18.96",concurrently:"7.0.0","downl
- 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 I9t=v(()=>{});var N9t=v(()=>{I9t()});var j9t=v(()=>{bd()});var D9t=v(()=>{});var $9t=v(()=>{});function lTn(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return{...e,[r]:Array.isArray(n)?[...n]:n}},{})}var Hve,L9t=v(()=>{Hve=class t{constructor(e){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=lTn(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 F9t=v(()=>{});var k9t=v(()=>{});var q9t=v(()=>{});var B9t=v(()=>{N9t();j9t();D9t();$9t();L9t();F9t();k9t();q9t()});function U9t(t){return new Hve({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 z9t(t,e){let n=await aKt(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 Cm("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:CKt(o.Expiration)}}if(t.statusCode>=400&&t.statusCode<500){let o={};try{o=JSON.parse(n)}catch{}throw Object.assign(new Cm(`Server responded with status: ${t.statusCode}`,{logger:e}),{Code:o.Code,Message:o.Message})}throw new Cm(`Server responded with status: ${t.statusCode}`,{logger:e})}var H9t=v(()=>{e1();B9t();an();C6e()});var V9t,J9t=v(()=>{V9t=(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 u5e,K9t=v(()=>{Xte();e1();A9t();H9t();J9t();u5e=(t={})=>{t.logger?.debug("@aws-sdk/credential-provider-http - fromHttp");let e,r=t.credentialsFullUri;if(r)e=r;else throw new Cm("No HTTP credential provider host provided.",{logger:t.logger});let n=new URL(e);R9t(n,t.logger);let o=new pF;return V9t(async()=>{let i=U9t(n);t.authorizationToken&&(i.headers.Authorization=t.authorizationToken);let a=await o.handle(i);return z9t(a.response)},t.maxRetries??3,t.timeout??1e3)}});var W9t=v(()=>{K9t()});function cTn(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sts",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function G9t(t){return{schemeId:"smithy.api#noAuth"}}var Z9t,X9t,dTn,Y9t,l5e=v(()=>{D4();pC();mre();Z9t=async(t,e,r)=>({operation:nT(e).operation,region:await dy(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});X9t=t=>{let e=[];switch(t.operation){case"AssumeRoleWithSAML":{e.push(G9t(t));break}case"AssumeRoleWithWebIdentity":{e.push(G9t(t));break}default:e.push(cTn(t))}return e},dTn=t=>({...t,stsClientCtor:hS}),Y9t=t=>{let e=dTn(t);return{...G_e(e)}}});var Q9t,py,cT=v(()=>{Q9t=t=>({...t,useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,useGlobalEndpoint:t.useGlobalEndpoint??!1,defaultSigningName:"sts"}),py={UseGlobalEndpoint:{type:"builtInParams",name:"useGlobalEndpoint"},UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}});var t7t,e7t=v(()=>{t7t={name:"@aws-sdk/client-sts",description:"AWS SDK for JavaScript Sts Client for Node.js,
${this.getCanonicalPath(e)}
${yXt(e)}
${o.map(i=>`${i}:${r[i]}`).join(`
`)}
${o.join(";")}
${n}`}async createStringToSign(e,r,n,o){let i=new this.sha256;i.update(L4.toUint8Array(n));let a=await i.digest();return`${o}
${e}
${r}
${AF.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 Qve.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=UEn(e).replace(/[\-:]/g,"");return{longDate:r,shortDate:r.slice(0,8)}}getCanonicalHeaderList(e){return Object.keys(e).sort().join(";")}},wWe=class extends iwe{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});M(this,"headerFormatter",new bWe)}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>pXt)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");let g=rwe(h,p,d??this.service),y=gXt(vWe(r),{unhoistableHeaders:s,hoistableHeaders:l});f.sessionToken&&(y.query[xWe]=f.sessionToken),y.query[QZt]=ewe,y.query[eXt]=`${f.accessKeyId}/${g}`,y.query[SWe]=m,y.query[rXt]=i.toString(10);let b=yWe(y,a,u);return y.query[tXt]=this.getCanonicalHeaderList(b),y.query[CWe]=await this.getSignature(m,g,this.getSigningKey(f,p,h,d),this.createCanonicalRequest(y,b,await nwe(r,this.sha256))),y}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=rwe(l,u,s??this.service),f=await nwe({headers:{},body:n},this.sha256),p=new this.sha256;p.update(r);let m=AF.toHex(await p.digest()),h=[cXt,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(L4.toUint8Array(r)),AF.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=vWe(r),{longDate:d,shortDate:f}=this.formatDate(n),p=rwe(f,l,s??this.service);c.headers[TWe]=d,u.sessionToken&&(c.headers[aXt]=u.sessionToken);let m=await nwe(c,this.sha256);!hXt(owe,c.headers)&&this.applyChecksum&&(c.headers[owe]=m);let h=yWe(c,i,o),g=await this.getSignature(d,p,this.getSigningKey(u,l,f,s),this.createCanonicalRequest(c,h,m));return c.headers[OWe]=`${ewe} Credential=${u.accessKeyId}/${p}, SignedHeaders=${this.getCanonicalHeaderList(h)}, Signature=${g}`,c}async getSignature(r,n,o,i){let a=await this.createStringToSign(r,n,i,ewe),s=new this.sha256(await o);return s.update(L4.toUint8Array(a)),AF.toHex(await s.digest())}getSigningKey(r,n,o,i){return mXt(this.sha256,r,o,n,i||this.service)}},HEn={SignatureV4a:null};ri.ALGORITHM_IDENTIFIER=ewe;ri.ALGORITHM_IDENTIFIER_V4A=kEn;ri.ALGORITHM_QUERY_PARAM=QZt;ri.ALWAYS_UNSIGNABLE_HEADERS=sXt;ri.AMZ_DATE_HEADER=TWe;ri.AMZ_DATE_QUERY_PARAM=SWe;ri.AUTH_HEADER=OWe;ri.CREDENTIAL_QUERY_PARAM=eXt;ri.DATE_HEADER=nXt;ri.EVENT_ALGORITHM_IDENTIFIER=cXt;ri.EXPIRES_QUERY_PARAM=rXt;ri.GENERATED_HEADERS=oXt;ri.HOST_HEADER=LEn;ri.KEY_TYPE_IDENTIFIER=EWe;ri.MAX_CACHE_SIZE=fXt;ri.MAX_PRESIGNED_TTL=pXt;ri.PROXY_HEADER_PATTERN=uXt;ri.REGION_SET_PARAM=$En;ri.SEC_HEADER_PATTERN=lXt;ri.SHA256_HEADER=owe;ri.SIGNATURE_HEADER=iXt;ri.SIGNATURE_QUERY_PARAM=CWe;ri.SIGNED_HEADERS_QUERY_PARAM=tXt;ri.SignatureV4=wWe;ri.SignatureV4Base=iwe;ri.TOKEN_HEADER=aXt;ri.TOKEN_QUERY_PARAM=xWe;ri.UNSIGNABLE_PATTERNS=FEn;ri.UNSIGNED_PAYLOAD=dXt;ri.clearCredentialCache=qEn;ri.createScope=rwe;ri.getCanonicalHeaders=yWe;ri.getCanonicalQuery=yXt;ri.getPayloadHash=nwe;ri.getSigningKey=mXt;ri.hasHeader=hXt;ri.moveHeadersToQuery=gXt;ri.prepareRequest=vWe;ri.signatureV4aContainer=HEn});var cc=S((wla,_Xt)=>{"use strict";_Xt.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}};RWe.exports={AggregateError:MWe,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 nPn},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:oPn,deprecate(t,e){return t},addAbortListener:Rre().addAbortListener||function(e,r){if(e===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);IXt(e,"signal"),iPn(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[QEn]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[ePn](){var o;(o=n)===null||o===void 0||o()}}},AbortSignalAny:tPn.any||function(e){if(e.length===1)return e[0];let r=new rPn,n=()=>r.abort();return e.forEach(o=>{IXt(o,"signals"),o.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{e.forEach(o=>o.removeEventListener("abort",n))},{once:!0}),r.signal}};RWe.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var mb=S((Ola,DXt)=>{"use strict";var{format:aPn,inspect:lwe,AggregateError:sPn}=gy(),uPn=globalThis.AggregateError||sPn,lPn=Symbol("kIsNodeError"),cPn=["string","function","number","object","Function","Object","boolean","bigint","symbol"],dPn=/^([A-Z][a-z0-9]*)+$/,fPn="__node_internal_",cwe={};function F4(t,e){if(!t)throw new cwe.ERR_INTERNAL_ASSERTION(e)}function NXt(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 pPn(t,e,r){if(typeof e=="function")return F4(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 F4(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:aPn(e,...r)}function ag(t,e,r){r||(r=Error);class n extends r{constructor(...i){super(pPn(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[lPn]=!0,cwe[t]=n}function jXt(t){let e=fPn+t.name;return Object.defineProperty(t,"name",{value:e}),t}function mPn(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new uPn([e,t],e.message);return r.code=e.code,r}return t||e}var AWe=class extends Error{constructor(e="The operation was aborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new cwe.ERR_INVALID_ARG_TYPE("options","Object",r);super(e,r),this.code="ABORT_ERR",this.name="AbortError"}};ag("ERR_ASSERTION","%s",Error);ag("ERR_INVALID_ARG_TYPE",(t,e,r)=>{F4(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)F4(typeof u=="string","All expected entries have to be of type string"),cPn.includes(u)?o.push(u.toLowerCase()):dPn.test(u)?i.push(u):(F4(u!=="object",'The value "object" should be written as "Object"'),a.push(u));if(i.length>
`)>=0)return!1;return!0}function zNn(t,e){var r;if(t.indent===" ")r=" ";else if(typeof t.indent=="number"&&t.indent>0)r=vT.call(Array(t.indent+1)," ");else return null;return{base:r,prev:vT.call(Array(e+1),r)}}function X8e(t,e){if(t.length===0)return"";var r=`
`+e.prev+e.base;return r+vT.call(t,","+r)+`
`+e.prev}function qwe(t,e){var r=Z8e(t),n=[];if(r){n.length=t.length;for(var o=0;o<t.length;o++)n[o]=b1(t,o)?e(t[o],t):""}var i=typeof V8e=="function"?V8e(t):[],a;if(F5){a={};for(var s=0;s<i.length;s++)a["$"+i[s]]=i[s]}for(var u in t)b1(t,u)&&(r&&String(Number(u))===u&&u<t.length||F5&&a["$"+u]instanceof Symbol||(Ver.call(/[^\w$]/,u)?n.push(e(u,t)+": "+e(t[u],t)):n.push(u+": "+e(t[u],t))));if(typeof V8e=="function")for(var l=0;l<i.length;l++)Jer.call(t,i[l])&&n.push("["+e(i[l])+"]: "+e(t[i[l]],t));return n}});var etr=S((rca,Qer)=>{"use strict";var HNn=Wre(),VNn=X4(),zwe=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},JNn=function(t,e){if(t){var r=zwe(t,e);return r&&r.value}},KNn=function(t,e,r){var n=zwe(t,e);n?n.value=r:t.next={key:e,next:t.next,value:r}},WNn=function(t,e){return t?!!zwe(t,e):!1},GNn=function(t,e){if(t)return zwe(t,e,!0)};Qer.exports=function(){var e,r={assert:function(n){if(!r.has(n))throw new VNn("Side channel does not contain "+HNn(n))},delete:function(n){var o=e&&e.next,i=GNn(e,n);return i&&o&&o===i&&(e=void 0),!!i},get:function(n){return JNn(e,n)},has:function(n){return WNn(e,n)},set:function(n,o){e||(e={next:void 0}),KNn(e,n,o)}};return r}});var tGe=S((nca,ttr)=>{"use strict";ttr.exports=Object});var ntr=S((oca,rtr)=>{"use strict";rtr.exports=Error});var itr=S((ica,otr)=>{"use strict";otr.exports=EvalError});var str=S((aca,atr)=>{"use strict";atr.exports=RangeError});var ltr=S((sca,utr)=>{"use strict";utr.exports=ReferenceError});var dtr=S((uca,ctr)=>{"use strict";ctr.exports=SyntaxError});var ptr=S((lca,ftr)=>{"use strict";ftr.exports=URIError});var htr=S((cca,mtr)=>{"use strict";mtr.exports=Math.abs});var ytr=S((dca,gtr)=>{"use strict";gtr.exports=Math.floor});var _tr=S((fca,btr)=>{"use strict";btr.exports=Math.max});var wtr=S((pca,vtr)=>{"use strict";vtr.exports=Math.min});var Ctr=S((mca,Str)=>{"use strict";Str.exports=Math.pow});var Otr=S((hca,xtr)=>{"use strict";xtr.exports=Math.round});var Etr=S((gca,Ttr)=>{"use strict";Ttr.exports=Number.isNaN||function(e){return e!==e}});var Mtr=S((yca,Ptr)=>{"use strict";var ZNn=Etr();Ptr.exports=function(e){return ZNn(e)||e===0?e:e<0?-1:1}});var Atr=S((bca,Rtr)=>{"use strict";Rtr.exports=Object.getOwnPropertyDescriptor});var rGe=S((_ca,Itr)=>{"use strict";var Hwe=Atr();if(Hwe)try{Hwe([],"length")}catch{Hwe=null}Itr.exports=Hwe});var jtr=S((vca,Ntr)=>{"use strict";var Vwe=Object.defineProperty||!1;if(Vwe)try{Vwe({},"a",{value:1})}catch{Vwe=!1}Ntr.exports=Vwe});var $tr=S((wca,Dtr)=>{"use strict";Dtr.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 ktr=S((Sca,Ftr)=>{"use strict";var Ltr=typeof Symbol<"u"&&Symbol,XNn=$tr();Ftr.exports=function(){return typeof Ltr!="function"||typeof Symbol!="function"||typeof Ltr("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:XNn()}});var nGe=S((Cca,qtr)=>{"use strict";qtr.exports=typeof Reflect<"u"&&Reflect.getPrototypeOf||null});var oGe=S((xca,Btr)=>{"use strict";var YNn=tGe();Btr.exports=YNn.getPrototypeOf||null});var Htr=S((Oca,ztr)=>{"use strict";var QNn="Function.prototype.bind called on incompatible ",e1n=Object.prototype.toString,t1n=Math.max,r1n="[object Function]",Utr=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},n1n=function(e,r){
`,this.streamTerminator=n.streamTerminator):this.messageTerminator=n.messageTerminator,o?.addEventListener("abort",()=>this.controller.abort())}iterMessages(){return gnr(this,arguments,function*(){var r,n,o,i;this.controller.signal;let a=ynr(this.stream),s="",u=!1;try{for(var l=!0,c=hnr(a),d;d=yield wC(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 g=m.indexOf(this.prefix);if(g===-1)continue;u=!0,m=m.slice(g+this.prefix.length)}if(this.streamTerminator!=null&&m.includes(this.streamTerminator))return yield wC(void 0);let h=yield wC(this.parse(JSON.parse(m)));yield yield wC(h),u=!1}}}catch(f){n={error:f}}finally{try{!l&&!r&&(o=c.return)&&(yield wC(o.call(c)))}finally{if(n)throw n.error}}})}[Symbol.asyncIterator](){return gnr(this,arguments,function*(){var r,n,o,i;try{for(var a=!0,s=hnr(this.iterMessages()),u;u=yield wC(s.next()),r=u.done,!r;a=!0)i=u.value,a=!1,yield yield wC(i)}catch(l){n={error:l}}finally{try{!a&&!r&&(o=s.return)&&(yield wC(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 FDn.RUNTIME.type==="node"&&typeof e<"u"&&(r+=Buffer.isBuffer(e)?e:Buffer.from(e));return r}};qv.Stream=MGe;function ynr(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{next(){return mnr(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 mnr(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 bnr=S(uSe=>{"use strict";Object.defineProperty(uSe,"__esModule",{value:!0});uSe.Stream=void 0;var qDn=RGe();Object.defineProperty(uSe,"Stream",{enumerable:!0,get:function(){return qDn.Stream}})});var _nr=S(ane=>{"use strict";var BDn=ane&&ane.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ane,"__esModule",{value:!0});ane.encodeAsFormParameter=zDn;var UDn=BDn(bGe());function zDn(t){let r=UDn.default.stringify(t,{encode:!1}).split("&").map(n=>{let[o,i]=n.split("=");return[o,i]});return Object.fromEntries(r)}});var Snr=S((hda,wnr)=>{"use strict";var AGe=Object.defineProperty,HDn=Object.getOwnPropertyDescriptor,VDn=Object.getOwnPropertyNames,JDn=Object.prototype.hasOwnProperty,KDn=(t,e)=>{for(var r in e)AGe(t,r,{get:e[r],enumerable:!0})},WDn=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of VDn(e))!JDn.call(t,o)&&o!==r&&AGe(t,o,{get:()=>e[o],enumerable:!(n=HDn(e,o))||n.enumerable});return t},GDn=t=>WDn(AGe({},"__esModule",{value:!0}),t),vnr={};KDn(vnr,{Blob:()=>YDn,File:()=>QDn,FormData:()=>XDn});wnr.exports=GDn(vnr);var ZDn=function(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:window}(),{FormData:XDn,Blob:YDn,File:QDn}=ZDn});var Dnr=S((gda,jnr)=>{"use strict";var jGe=Object.defineProperty,e$n=Object.getOwnPropertyDescriptor,t$n=Object.getOwnPropertyNames,r$n=Object.prototype.hasOwnProperty,n$n=(t,e)=>{for(var r in e)jGe(t,r,{get:e[r],enumerable:!0})},o$n=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of t$n(e))!r$n.call(t,o)&&o!==r&&jGe(t,o,{get:()=>e[o],enumerable:!(n=e$n(e,o))||n.enumerable});return t},i$n=t=>o$n(jGe({},"__esModule",{value:!0}),t),DGe=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},Rc=(t,e,r)=>(DGe(t,e,"read from private field"),r?r.call(t):e.get(t)),CT=(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)},sne=(t,e,r,n)=>(DGe(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),IGe=(t,e,r)=>(DGe(t,e,"access private method"),r),Mnr={};n$n(Mnr,{FormDataEncoder:()=>p$n,isFile:()=>o2,isFormData:()=>Inr});jnr.exports=i$n(Mnr);var _1=t=>typeof t=="function",a$n=t=>_1(t[Symbol.asyncIterator]),Cnr=65536;function*Rnr(t){if(t.byteLength<=Cnr){yield t;return}let e=
`||e===`
`&&n[r-1]!=="\r"?`\r
`:e),c$n=t=>Object.prototype.toString.call(t).slice(8,-1).toLowerCase();function Tnr(t){if(c$n(t)!=="object")return!1;let e=Object.getPrototypeOf(t);return e==null?!0:(e.constructor&&e.constructor.toString())===Object.toString()}function Enr(t,e){if(typeof e=="string"){for(let[r,n]of Object.entries(t))if(e.toLowerCase()===r.toLowerCase())return n}}var d$n=t=>new Proxy(t,{get:(e,r)=>Enr(e,r),has:(e,r)=>Enr(e,r)!==void 0}),Inr=t=>!!(t&&_1(t.constructor)&&t[Symbol.toStringTag]==="FormData"&&_1(t.append)&&_1(t.getAll)&&_1(t.entries)&&_1(t[Symbol.iterator])),Pnr=t=>String(t).replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/"/g,"%22"),o2=t=>!!(t&&typeof t=="object"&&_1(t.constructor)&&t[Symbol.toStringTag]==="File"&&_1(t.stream)&&t.name!=null),f$n={enableAdditionalHeaders:!1},lSe={writable:!1,configurable:!1},kF,une,cSe,lne,n2,cne,dne,dSe,fSe,$Ge,NGe,Nnr,p$n=class{constructor(t,e,r){if(CT(this,fSe),CT(this,NGe),CT(this,kF,`\r
`),CT(this,une,void 0),CT(this,cSe,void 0),CT(this,lne,"-".repeat(2)),CT(this,n2,new TextEncoder),CT(this,cne,void 0),CT(this,dne,void 0),CT(this,dSe,void 0),!Inr(t))throw new TypeError("Expected first argument to be a FormData instance.");let n;if(Tnr(e)?r=e:n=e,n||(n=l$n()),typeof n!="string")throw new TypeError("Expected boundary argument to be a string.");if(r&&!Tnr(r))throw new TypeError("Expected options argument to be an object.");sne(this,dne,Array.from(t.entries())),sne(this,dSe,{...f$n,...r}),sne(this,une,Rc(this,n2).encode(Rc(this,kF))),sne(this,cSe,Rc(this,une).byteLength),this.boundary=`form-data-boundary-${n}`,this.contentType=`multipart/form-data; boundary=${this.boundary}`,sne(this,cne,Rc(this,n2).encode(`${Rc(this,lne)}${this.boundary}${Rc(this,lne)}${Rc(this,kF).repeat(2)}`));let o={"Content-Type":this.contentType},i=IGe(this,NGe,Nnr).call(this);i&&(this.contentLength=i,o["Content-Length"]=i),this.headers=d$n(Object.freeze(o)),Object.defineProperties(this,{boundary:lSe,contentType:lSe,contentLength:lSe,headers:lSe})}*values(){for(let[t,e]of Rc(this,dne)){let r=o2(e)?e:Rc(this,n2).encode(Anr(e));yield IGe(this,fSe,$Ge).call(this,t,r),yield r,yield Rc(this,une)}yield Rc(this,cne)}async*encode(){for(let t of this.values())o2(t)?yield*u$n(t.stream()):yield*Rnr(t)}[Symbol.iterator](){return this.values()}[Symbol.asyncIterator](){return this.encode()}};kF=new WeakMap;une=new WeakMap;cSe=new WeakMap;lne=new WeakMap;n2=new WeakMap;cne=new WeakMap;dne=new WeakMap;dSe=new WeakMap;fSe=new WeakSet;$Ge=function(t,e){let r="";if(r+=`${Rc(this,lne)}${this.boundary}${Rc(this,kF)}`,r+=`Content-Disposition: form-data; name="${Pnr(t)}"`,o2(e)&&(r+=`; filename="${Pnr(e.name)}"${Rc(this,kF)}`,r+=`Content-Type: ${e.type||"application/octet-stream"}`),Rc(this,dSe).enableAdditionalHeaders===!0){let n=o2(e)?e.size:e.byteLength;n!=null&&!isNaN(n)&&(r+=`${Rc(this,kF)}Content-Length: ${n}`)}return Rc(this,n2).encode(`${r}${Rc(this,kF).repeat(2)}`)};NGe=new WeakSet;Nnr=function(){let t=0;for(let[e,r]of Rc(this,dne)){let n=o2(r)?r:Rc(this,n2).encode(Anr(r)),o=o2(n)?n.size:n.byteLength;if(o==null||isNaN(o))return;t+=IGe(this,fSe,$Ge).call(this,e,n).byteLength,t+=o,t+=Rc(this,cSe)}return String(t+Rc(this,cne).byteLength)}});var Lnr=S((bda,$nr)=>{"use strict";$nr.exports=typeof self=="object"?self.FormData:window.FormData});var Fnr=S(sg=>{"use strict";var m$n=sg&&sg.__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]}),h$n=sg&&sg.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Q5=sg&&sg.__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"&&m$n(r,e,n[o]);return h$n(r,e),r}}(),qF=sg&&sg.__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(sg,"__esModule",{value:!0});sg.WebFormData=sg.Node16FormData=sg.Node18FormData=void 0;sg.newFormData=g$n;var pSe=H5();function LGe(t){return typeof t=="object"&&t!=null&&"name"in t}function g$n(){return qF(this,void 0,void 0,function*(){let t;return pSe.RUNTIME.type==="node"&&pSe.RUNTIME.parsedVersion!=null&&pSe.RUNTIME.parsedVersion>=18?t=new mSe:pSe.RUNTIME.type==="node"?t=new hSe:t=new gSe,yield t.setup(),t})}var mSe=class{setup(){return qF(this,void 0,void 0,function*(){this.fd=new(yield Promise.resolve().then(()=>Q5(Snr()))).FormData})}append(e
`)),{ok:!0,value:e}):n}}});var BGe=S(qGe=>{"use strict";Object.defineProperty(qGe,"__esModule",{value:!0});qGe.stringifyValidationError=C$n;function C$n(t){return t.path.length===0?t.message:`${t.path.join(" -> ")}: ${t.message}`}});var zGe=S(bSe=>{"use strict";Object.defineProperty(bSe,"__esModule",{value:!0});bSe.JsonError=void 0;var x$n=BGe(),UGe=class t extends Error{constructor(e){super(e.map(x$n.stringifyValidationError).join("; ")),this.errors=e,Object.setPrototypeOf(this,t.prototype)}};bSe.JsonError=UGe});var VGe=S(_Se=>{"use strict";Object.defineProperty(_Se,"__esModule",{value:!0});_Se.ParseError=void 0;var O$n=BGe(),HGe=class t extends Error{constructor(e){super(e.map(O$n.stringifyValidationError).join("; ")),this.errors=e,Object.setPrototypeOf(this,t.prototype)}};_Se.ParseError=HGe});var Vnr=S(i2=>{"use strict";Object.defineProperty(i2,"__esModule",{value:!0});i2.getSchemaUtils=fne;i2.nullable=Bnr;i2.optional=Unr;i2.optionalNullable=znr;i2.transform=Hnr;var JGe=dh(),T$n=zGe(),E$n=VGe();function fne(t){return{nullable:()=>Bnr(t),optional:()=>Unr(t),optionalNullable:()=>znr(t),transform:e=>Hnr(t,e),parseOrThrow:(e,r)=>{let n=t.parse(e,r);if(n.ok)return n.value;throw new E$n.ParseError(n.errors)},jsonOrThrow:(e,r)=>{let n=t.json(e,r);if(n.ok)return n.value;throw new T$n.JsonError(n.errors)}}}function Bnr(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:()=>JGe.SchemaType.NULLABLE};return Object.assign(Object.assign({},e),fne(e))}function Unr(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:()=>JGe.SchemaType.OPTIONAL};return Object.assign(Object.assign({},e),fne(e))}function znr(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:()=>JGe.SchemaType.OPTIONAL_NULLABLE};return Object.assign(Object.assign({},e),fne(e))}function Hnr(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),fne(r))}});var y_=S(SS=>{"use strict";Object.defineProperty(SS,"__esModule",{value:!0});SS.ParseError=SS.JsonError=SS.transform=SS.optional=SS.getSchemaUtils=void 0;var KGe=Vnr();Object.defineProperty(SS,"getSchemaUtils",{enumerable:!0,get:function(){return KGe.getSchemaUtils}});Object.defineProperty(SS,"optional",{enumerable:!0,get:function(){return KGe.optional}});Object.defineProperty(SS,"transform",{enumerable:!0,get:function(){return KGe.transform}});var P$n=zGe();Object.defineProperty(SS,"JsonError",{enumerable:!0,get:function(){return P$n.JsonError}});var M$n=VGe();Object.defineProperty(SS,"ParseError",{enumerable:!0,get:function(){return M$n.ParseError}})});var Knr=S(WGe=>{"use strict";Object.defineProperty(WGe,"__esModule",{value:!0});WGe.bigint=N$n;var R$n=dh(),Jnr=hb(),A$n=xT(),I$n=y_();function N$n(){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,Jnr.getErrorMessageForIncorrectType)(e,"bigint | number")}]},json:(e,{breadcrumbsPrefix:r=[]}={})=>typeof e!="bigint"?{ok:!1,errors:[{path:r,message:(0,Jnr.getErrorMessageForIncorrectType)(e,"bigint")}]}:{ok:!0,value:e},getType:()=>R$n.SchemaType.BIGINT};return Object.assign(Object.assign({},(0,A$n.maybeSkipValidation)(t)),(0,I$n.getSchemaUtils)(t))}});var Wnr=S(vSe=>{"use strict";Object.defineProperty(vSe,"__esModule",{value:!0});vSe.bigint=void 0;var j$n=Knr();Object.defineProperty(vSe,"bigint",{enumerable:!0,get:function(){return j$n.bigint}})});var Gnr=S(ZGe=>{"use strict";Object.defineProperty(ZGe,"__esModule",{value:!0});ZGe.date=k$n;var D$n=dh(),GGe=hb(),$$n=xT(),L$n=y_(),F$n=/^([+-]?\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 _ne(this,void 0,void 0,function*(){var o;yield(o=r.return)===null||o===void 0?void 0:o.call(r)})}})}};lg.StreamUtils=T9e;function zor(t,e){return wne(this,arguments,function*(){var n,o,i,a;if(!t.body)throw e?.abort(),new oW.CohereError({message:"Attempted to iterate over a response with no body"});let s=new E9e,u=new BF,l=P9e(t.body);try{for(var c=!0,d=vne(kFn(l)),f;f=yield jl(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 jl(h))}}}catch(p){o={error:p}}finally{try{!c&&!n&&(i=d.return)&&(yield jl(i.call(d)))}finally{if(o)throw o.error}}for(let p of u.flush()){let m=s.decode(p);m&&(yield yield jl(m))}})}function kFn(t){return wne(this,arguments,function*(){var r,n,o,i;let a=new Uint8Array;try{for(var s=!0,u=vne(t),l;l=yield jl(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=qFn(a))!==-1;)yield yield jl(a.slice(0,p)),a=a.slice(p)}}catch(c){n={error:c}}finally{try{!s&&!r&&(o=u.return)&&(yield jl(o.call(u)))}finally{if(n)throw n.error}}a.length>0&&(yield yield jl(a))})}function qFn(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 E9e=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]=UFn(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},BF=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 oW.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 oW.CohereError({message:`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`})}throw new oW.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}};lg.LineDecoder=BF;BF.NEWLINE_CHARS=new Set([`
`,"\r"]);BF.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function BFn(t){let e=new BF,r=[];for(let n of t)r.push(...e.decode(n));return r}function UFn(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}function P9e(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{next(){return _ne(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 _ne(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 Cne=S(OT=>{"use strict";var zFn=OT&&OT.__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]}),HFn=OT&&OT.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),VFn=OT&&OT.__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"&&zFn(r,e,n[o]);return HFn(r,e),r}}();Object.defineProperty(OT,"__esModule",{value:!0});OT.Document=void 0;var Sne=VFn(ne());OT.Document=Sne.serialization.object({data:Sne.serialization.record(Sne.serialization.string(),Sne.serialization.unknown()),id:Sne.serialization.string().optional()})});var M9e=S(TT=>{"use strict";var JFn=TT&&TT.__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]}),KFn=TT&&TT.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),WFn=TT&&TT.__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"&&JFn(r,e,n[o]);return KFn(r,e),r}}();Object.defineProperty(TT,"__esModule",{value:!0});TT.V2ChatStreamRequestDocumentsItem=void 0;var Vor=WFn(ne()),GFn=Cne();TT.V2ChatStreamRequestDocumentsItem=Vor.serialization.undiscriminatedUnion([Vor.serialization.string(),GFn.Document])});var R9e=S(ET=>{"use strict";var ZFn=ET&&ET.__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]}),XFn=ET&&ET.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),YFn=ET&&ET.__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"&&ZFn(r,e,n[o]);return XFn(r,e),r}}();Object.defineProperty(ET,"__esModule",{value:!0});ET.V2ChatStreamRequestSafetyMode=void 0;var QFn=YFn(ne());ET.V2ChatStreamRequestSafetyMode=QFn.serialization.enum_(["CONTEXTUAL","STRICT","OFF"])});var A9e=S(PT=>{"use strict";var ekn=PT&&PT.__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(T){s={error:T}}finally{try{!b&&!a&&(u=_.return)&&(yield u.call(_))}finally{if(s)throw s.error}}for(let T of O.flush()){let R=(0,eu.parseAWSEvent)(T);if(R){let N=yield(0,eu.mapResponseFromBedrock)(m,d,f,R);E.push(JSON.stringify(N)+`
`)}}return E.end(),{ok:!0,body:E,rawResponse:y.rawResponse}}else{let x=yield y.body;return{ok:!0,body:yield(0,eu.mapResponseFromBedrock)(m,d,f,x),rawResponse:y.rawResponse}}}catch(x){throw x}});eu.fetchOverride=xYn});var R1=S(C0e=>{"use strict";Object.defineProperty(C0e,"__esModule",{value:!0});C0e.CohereEnvironment=void 0;C0e.CohereEnvironment={Production:"https://api.cohere.com"}});var XF=S((csr,x0e)=>{(function(t,e,r){typeof x0e<"u"&&x0e.exports?x0e.exports=r():typeof define=="function"&&define.amd?define(r):e[t]=r()})("urljoin",csr,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 cYe=S(w_=>{"use strict";var OYn=w_&&w_.__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]}),TYn=w_&&w_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Wne=w_&&w_.__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"&&OYn(r,e,n[o]);return TYn(r,e),r}}(),TW=w_&&w_.__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())})},EYn=w_&&w_.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(w_,"__esModule",{value:!0});w_.V2=void 0;var O0e=Wne(R1()),Gi=Wne(ne()),Dn=Wne(QN()),YF=Wne(M1()),T0e=EYn(XF()),dg=Wne(Pc()),lYe=class{constructor(e={}){this._options=e}chatStream(e,r){return Gi.HttpResponsePromise.fromPromise(this.__chatStream(e,r))}__chatStream(e,r){return TW(this,void 0,void 0,function*(){var n,o,i;let a=yield((n=this._options.fetcher)!==null&&n!==void 0?n:Gi.fetcher)({url:(0,T0e.default)((i=(o=yield Gi.Supplier.get(this._options.baseUrl))!==null&&o!==void 0?o:yield Gi.Supplier.get(this._options.environment))!==null&&i!==void 0?i:O0e.CohereEnvironment.Production,"v2/chat"),method:"POST",headers:Object.assign({Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield Gi.Supplier.get(this._options.clientName))!=null?yield Gi.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":Gi.RUNTIME.type,"X-Fern-Runtime-Version":Gi.RUNTIME.version},r?.headers),contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},YF.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 Gi.Stream({stream:a.body,parse:s=>TW(this,void 0,void
`}}),rawResponse:u.rawResponse};if(u.error.reason==="status-code")switch(u.error.statusCode){case 400:throw new Ne.BadRequestError(u.error.body,u.rawResponse);case 401:throw new Ne.UnauthorizedError(u.error.body,u.rawResponse);case 403:throw new Ne.ForbiddenError(u.error.body,u.rawResponse);case 404:throw new Ne.NotFoundError(u.error.body,u.rawResponse);case 422:throw new Ne.UnprocessableEntityError(u.error.body,u.rawResponse);case 429:throw new Ne.TooManyRequestsError(u.error.body,u.rawResponse);case 498:throw new Ne.InvalidTokenError(u.error.body,u.rawResponse);case 499:throw new Ne.ClientClosedRequestError(u.error.body,u.rawResponse);case 500:throw new Ne.InternalServerError(u.error.body,u.rawResponse);case 501:throw new Ne.NotImplementedError(u.error.body,u.rawResponse);case 503:throw new Ne.ServiceUnavailableError(u.error.body,u.rawResponse);case 504:throw new Ne.GatewayTimeoutError(u.error.body,u.rawResponse);default:throw new Co.CohereError({statusCode:u.error.statusCode,body:u.error.body,rawResponse:u.rawResponse})}switch(u.error.reason){case"non-json":throw new Co.CohereError({statusCode:u.error.statusCode,body:u.error.rawBody,rawResponse:u.rawResponse});case"timeout":throw new Co.CohereTimeoutError("Timeout exceeded when calling POST /v1/chat.");case"unknown":throw new Co.CohereError({message:u.error.errorMessage,rawResponse:u.rawResponse})}})}chat(e,r){return ot.HttpResponsePromise.fromPromise(this.__chat(e,r))}__chat(e,r){return E_(this,void 0,void 0,function*(){var n,o,i;let{accepts:a}=e,s=bsr(e,["accepts"]),u=yield((n=this._options.fetcher)!==null&&n!==void 0?n:ot.fetcher)({url:(0,TC.default)((i=(o=yield ot.Supplier.get(this._options.baseUrl))!==null&&o!==void 0?o:yield ot.Supplier.get(this._options.environment))!==null&&i!==void 0?i:OC.CohereEnvironment.Production,"v1/chat"),method:"POST",headers:Object.assign({Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield ot.Supplier.get(this._options.clientName))!=null?yield ot.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":ot.RUNTIME.type,"X-Fern-Runtime-Version":ot.RUNTIME.version,Accepts:a??void 0},r?.headers),contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},rd.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:rd.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 Ne.BadRequestError(u.error.body,u.rawResponse);case 401:throw new Ne.UnauthorizedError(u.error.body,u.rawResponse);case 403:throw new Ne.ForbiddenError(u.error.body,u.rawResponse);case 404:throw new Ne.NotFoundError(u.error.body,u.rawResponse);case 422:throw new Ne.UnprocessableEntityError(u.error.body,u.rawResponse);case 429:throw new Ne.TooManyRequestsError(u.error.body,u.rawResponse);case 498:throw new Ne.InvalidTokenError(u.error.body,u.rawResponse);case 499:throw new Ne.ClientClosedRequestError(u.error.body,u.rawResponse);case 500:throw new Ne.InternalServerError(u.error.body,u.rawResponse);case 501:throw new Ne.NotImplementedError(u.error.body,u.rawResponse);case 503:throw new Ne.ServiceUnavailableError(u.error.body,u.rawResponse);case 504:throw new Ne.GatewayTimeoutError(u.error.body,u.rawResponse);default:throw new Co.CohereError({statusCode:u.error.statusCode,body:u.error.body,rawResponse:u.rawResponse})}switch(u.error.reason){case"non-json":throw new Co.CohereError({statusCode:u.error.statusCode,body:u.error.rawBody,rawResponse:u.rawResponse});case"timeout":throw new Co.CohereTimeoutError("Timeout exceeded when calling POST
`}}),rawResponse:a.rawResponse};if(a.error.reason==="status-code")switch(a.error.statusCode){case 400:throw new Ne.BadRequestError(a.error.body,a.rawResponse);case 401:throw new Ne.UnauthorizedError(a.error.body,a.rawResponse);case 403:throw new Ne.ForbiddenError(a.error.body,a.rawResponse);case 404:throw new Ne.NotFoundError(a.error.body,a.rawResponse);case 422:throw new Ne.UnprocessableEntityError(a.error.body,a.rawResponse);case 429:throw new Ne.TooManyRequestsError(a.error.body,a.rawResponse);case 498:throw new Ne.InvalidTokenError(a.error.body,a.rawResponse);case 499:throw new Ne.ClientClosedRequestError(a.error.body,a.rawResponse);case 500:throw new Ne.InternalServerError(a.error.body,a.rawResponse);case 501:throw new Ne.NotImplementedError(a.error.body,a.rawResponse);case 503:throw new Ne.ServiceUnavailableError(a.error.body,a.rawResponse);case 504:throw new Ne.GatewayTimeoutError(a.error.body,a.rawResponse);default:throw new Co.CohereError({statusCode:a.error.statusCode,body:a.error.body,rawResponse:a.rawResponse})}switch(a.error.reason){case"non-json":throw new Co.CohereError({statusCode:a.error.statusCode,body:a.error.rawBody,rawResponse:a.rawResponse});case"timeout":throw new Co.CohereTimeoutError("Timeout exceeded when calling POST /v1/generate.");case"unknown":throw new Co.CohereError({message:a.error.errorMessage,rawResponse:a.rawResponse})}})}generate(e,r){return ot.HttpResponsePromise.fromPromise(this.__generate(e,r))}__generate(e,r){return E_(this,void 0,void 0,function*(){var n,o,i;let a=yield((n=this._options.fetcher)!==null&&n!==void 0?n:ot.fetcher)({url:(0,TC.default)((i=(o=yield ot.Supplier.get(this._options.baseUrl))!==null&&o!==void 0?o:yield ot.Supplier.get(this._options.environment))!==null&&i!==void 0?i:OC.CohereEnvironment.Production,"v1/generate"),method:"POST",headers:Object.assign({Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield ot.Supplier.get(this._options.clientName))!=null?yield ot.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":ot.RUNTIME.type,"X-Fern-Runtime-Version":ot.RUNTIME.version},r?.headers),contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},rd.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:rd.Generation.parseOrThrow(a.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}),rawResponse:a.rawResponse};if(a.error.reason==="status-code")switch(a.error.statusCode){case 400:throw new Ne.BadRequestError(a.error.body,a.rawResponse);case 401:throw new Ne.UnauthorizedError(a.error.body,a.rawResponse);case 403:throw new Ne.ForbiddenError(a.error.body,a.rawResponse);case 404:throw new Ne.NotFoundError(a.error.body,a.rawResponse);case 422:throw new Ne.UnprocessableEntityError(a.error.body,a.rawResponse);case 429:throw new Ne.TooManyRequestsError(a.error.body,a.rawResponse);case 498:throw new Ne.InvalidTokenError(a.error.body,a.rawResponse);case 499:throw new Ne.ClientClosedRequestError(a.error.body,a.rawResponse);case 500:throw new Ne.InternalServerError(a.error.body,a.rawResponse);case 501:throw new Ne.NotImplementedError(a.error.body,a.rawResponse);case 503:throw new Ne.ServiceUnavailableError(a.error.body,a.rawResponse);case 504:throw new Ne.GatewayTimeoutError(a.error.body,a.rawResponse);default:throw new Co.CohereError({statusCode:a.error.statusCode,body:a.error.body,rawResponse:a.rawResponse})}switch(a.error.reason){case"non-json":throw new Co.CohereError({statusCode:a.error.statusCode,body:a.error.rawBody,rawResponse:a.rawResponse});case"timeout":throw new Co.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=$sr.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=AYe.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=AYe.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(..._Qn(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)}},D0e=AYe;yQn(D0e,"specialTokenRegex",t=>new RegExp(t.map(e=>vQn(e)).join("|"),"g"))});var Fsr=v(()=>{Lsr()});async function NYe(t){return t in $0e||($0e[t]=SQn.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>new D0e(e)).catch(e=>{throw delete $0e[t],e})),await $0e[t]}async function L0e(t){return NYe(IYe(t))}var wQn,$0e,SQn,jYe=v(()=>{Do();iz();Fsr();wQn={};Et(wQn,{encodingForModel:()=>L0e,getEncoding:()=>NYe});$0e={},SQn=new Fw({})});function Kv(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 CQn,F0e,xQn,ksr,qsr,OQn,jW,E2,Wv=v(()=>{Do();iO();iz();Gh();kQ();Dsr();jYe();CQn={};Et(CQn,{BaseLangChain:()=>jW,BaseLanguageModel:()=>E2,calculateMaxTokens:()=>qsr,getEmbeddingContextSize:()=>xQn,getModelContextSize:()=>ksr,getModelNameForTiktoken:()=>F0e,isOpenAITool:()=>Kv});F0e=t=>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,xQn=t=>{switch(t){case"text-embedding-ada-002":return 8191;default:return 2046}},ksr=t=>{switch(F0e(t)){case"gpt-3.5-turbo-16k":return 16384;case"gpt-3.5-turbo":return 4096;case"gpt-4-32k":return 32768;case"gpt-4":return 8192;case"text-davinci-003":return 4097;case"text-curie-001":return 2048;case"text-babbage-001":return 2048;case"text-ada-001":return 2048;case"code-davinci-002":return 8e3;case"code-cushman-001":return 2048;default:return 4097}};qsr=async({prompt:t,modelName:e})=>{let r;try{r=(await L0e(F0e(e))).encode(t).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),r=Math.ceil(t.length/4)}return ksr(e)-r},OQn=()=>!1,jW=class extends Lo{constructor(e){super(e);M(this,"verbose");M(this,"callbacks");M(this,"tags");M(this,"metadata");this.verbose=e.verbose??OQn(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}get lc_attributes(){return{callbacks:void 0,verbose:void 0}}},E2=class extends jW{constructor({callbacks:e,callbackManager:r,...n}){let{cache:o,...i}=n;super({callbacks:e??r,...i});M(this,"caller");M(this,"cache");M(this,"_encoding");typeof o=="object"?this.cache=o:o?this.cache=RYe.global():this.cache=void 0,this.caller=new Fw(n??{})}get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}async getNumTokens(e){let r;typeof e=="string"?r=e:r=e.map(o=>typeof o=="string"?o:o.type==="text"&&"text"in o?o.text:"").join("");let n=Math.ceil(r.length/4);if(!this._encodi
`+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&i.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function Eur(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 J0e(t){return!!t.finishReason&&seo.includes(t.finishReason)}function nk(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];J0e(i)&&(o+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(o+=`: ${i.finishMessage}`))}return o}function foe(t){return this instanceof foe?(this.v=t,this):new foe(t)}function ueo(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 foe?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 leo(t){let e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),r=feo(e),[n,o]=r.tee();return{stream:deo(n),response:ceo(o)}}async function ceo(t){let e=[],r=t.getReader();for(;;){let{done:n,value:o}=await r.read();if(n)return YYe(peo(e));e.push(o)}}function deo(t){return ueo(this,arguments,function*(){let r=t.getReader();for(;;){let{value:n,done:o}=yield foe(r.read());if(o)break;yield yield foe(YYe(n))}})}function feo(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(Pur),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(Pur)}return i()}).catch(a=>{let s=a;throw s.stack=a.stack,s.name==="AbortError"?s=new W0e("Request aborted when reading from the stream"):s=new gh("Error reading from the stream"),s})}}})}function peo(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 Nur(t,e,r,n){let o=await moe(e,A2.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(r),n);return leo(o)}async function jur(t,e,r,n){let i=await(await moe(e,A2.GENERATE_CONTENT,t,!1,JSON.stringify(r),n)).json();return{response:YYe(i)}}function Dur(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 lA(t,e){if(!(this instanceof lA))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 Mm(e.headers),this.url=e.url||"",this._initBody(t)}function elr(t,e){return new Promise(function(r,n){var o=new j2(t,e);if(o.signal&&o.signal.aborted)return n(new N2("Aborted","AbortError"));var i=new XMLHttpRequest;function a(){i.abort()}i.onload=function(){var l={statusText:i.statusText,headers:keo(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 lA(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 N2("Aborted","AbortError"))},0)};function s(l){try{return l===""&&bg.location.href?bg.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&&(yb.blob?i.responseType="blob":yb.arrayBuffer&&(i.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof Mm||bg.Headers&&e.headers instanceof bg.Headers)){var u=[];Object.getOwnPropertyNames(e.headers).forEach(function(l){u.push(DW(l)),i.setRequestHeader(l,sQe(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 bg,yb,Gur,Xur,$eo,qeo,N2,tlr=v(()=>{bg=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof window<"u"&&window||{},yb={searchParams:"URLSearchParams"in bg,iterable:"Symbol"in bg&&"iterator"in Symbol,blob:"FileReader"in bg&&"Blob"in bg&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in bg,arrayBuffer:"ArrayBuffer"in bg};yb.arrayBuffer&&(Gur=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],Xur=ArrayBuffer.isView||function(t){return t&&Gur.indexOf(Object.prototype.toString.call(t))>-1});Mm.prototype.append=function(t,e){t=DW(t),e=sQe(e);var r=this.map[t];this.map[t]=r?r+", "+e:e};Mm.prototype.delete=function(t){delete this.map[DW(t)]};Mm.prototype.get=function(t){return t=DW(t),this.has(t)?this.map[t]:null};Mm.prototype.has=function(t){return this.map.hasOwnProperty(DW(t))};Mm.prototype.set=function(t,e){this.map[DW(t)]=sQe(e)};Mm.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)};Mm.prototype.keys=function(){var t=[];return this.forEach(function(e,r){t.push(r)}),uQe(t)};Mm.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),uQe(t)};Mm.prototype.entries=function(){var t=[];return this.forEach(function(e,r){t.push([r,e])}),uQe(t)};yb.iterable&&(Mm.prototype[Symbol.iterator]=Mm.prototype.entries);$eo=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];j2.prototype.clone=function(){return new j2(this,{body:this._bodyInit})};Qur.call(j2.prototype);Qur.call(lA.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)}},Weo=t=>{if(!t)return olr;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=nlr);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},Geo=Object.defineProperty,Zeo=(t,e,r)=>e in t?Geo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,cQe=(t,e,r)=>(Zeo(t,typeof e!="symbol"?e+"":e,r),r),LW=class{constructor(e){cQe(this,"config"),cQe(this,"fetch"),cQe(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e?.headers},e?.proxy||(this.config.host=Weo(e?.host??olr)),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 $W(this.fetch,n,r,{signal:i.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");let s=Keo(a.body),u=new fQe(i,s,()=>{let l=this.ongoingStreamedRequests.indexOf(u);l>-1&&this.ongoingStreamedRequests.splice(l,1)});return this.ongoingStreamedRequests.push(u),u}return await(await $W(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 Jeo(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await $W(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await rlr(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await $W(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await $W(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await $W(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await rlr(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}},pwa=new LW});var hQe,ilr=v(()=>{Wur();$s();D1();Q0e();ym();xv();j1();cO();_O();Gv();o_();hQe=class extends hh{constructor(e){super(e??{});M(this,"model","llama3");M(this,"numa");M(this,"numCtx");M(this,"numBatch");M(this,"numGpu");M(this,"mainGpu");M(this,"lowVram");M(this,"f16Kv");M(this,"logitsAll");M(this,"vocabOnly");M(this,"useMmap");M(this,"useMlock");M(this,"embeddingOnly");M(this,"numThread");M(this,"numKeep");M(this,"seed");M(this,"numPredict");M(this,"topK");M(this,"topP");M(this,"tfsZ");M(this,"typicalP");M(this,"repeatLastN");M(this,"temperature");M(this,"repeatPenalty");M(this,"presencePenalty");M(this,"frequencyPenalty");M(this,"mirostat");M(this,"mirostatTau");M(this,"mirostatEta");M(this,"penalizeNewline");M(this,"streaming");M(this,"format");M(this,"keepAlive");M(this,"client");M(this,"checkOrPullModel",!1);M(this,"baseUrl","http://127.0.0.1:11434");M(this,"think");this.client=new LW({fetch:e?.fetch,host:e?.baseUrl,headers:e?.headers}),this.baseUr
`)}function clr(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}: ${eCe(o,e)},`):r.push(`${n}?: ${eCe(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
`)}function eCe(t,e){if(Yeo(t))return t.anyOf.map(r=>eCe(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["{",clr(t,e+2),"}"].join(`
`);case"array":return t.items?`${eCe(t.items,e)}[]`:"any[]";default:return""}}function tCe(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 FW(t){return"type"in t&&t.type!=="function"}function dlr(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function D2(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 rCe(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function flr(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 plr(t){return t.type==="tool_call"&&"isCustomTool"in t&&t.isCustomTool===!0}function mlr(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 hlr(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 goe=v(()=>{Gv();o_();j1()});function yoe(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var boe,nCe=v(()=>{boe=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 kt,Rm,Ic,ak,pA,kW,qW,BW,UW,zW,HW,VW,JW,KW,WW,mA,hA=v(()=>{nCe();kt=class extends Error{},Rm=class t extends kt{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 ak({message:n,cause:boe(r)});let i=r?.error;return e===400?new kW(e,i,n,o):e===401?new qW(e,i,n,o):e===403?new BW(e,i,n,o):e===404?new UW(e,i,n,o):e===409?new zW(e,i,n,o):e===422?new HW(e,i,n,o):e===429?new VW(e,i,n,o):e>=500?new JW(e,i,n,o):new t(e,i,n,o)}},Ic=class extends Rm{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ak=class extends Rm{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},pA=class extends ak{constructor({message:e}={}){super({message:e??"Request timed out."})}},kW=class extends Rm{},qW=class extends Rm{},BW=class extends Rm{},UW=class extends Rm{},zW=class extends Rm{},HW=class extends Rm{},VW=class extends Rm{},JW=class extends Rm{},KW=class extends kt{constructor(){super("Could not parse response content as the length limit was reached")}},WW=class extends kt{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},mA=class extends Error{constructor(e){super(e)}}});var RC=v(()=>{hA()});function _oe(t){return t!==void 0&&"function"in t&&t.function!==void 0}function glr(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function voe(t){return t?.$brand==="auto-parseable-response-format"}function $2(t){return t?.$bran
]))`;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 sCe(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]:vn(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:vn(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(iCe(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 uCe=v(()=>{yO();vd();aCe()});function Flr(t,e){if(e.mapStrategy==="record")return sCe(t,e);let r=vn(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=vn(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 LQe=v(()=>{vd();uCe()});function klr(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 FQe=v(()=>{});function qlr(){return{not:{}}}var kQe=v(()=>{});function Blr(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var qQe=v(()=>{});function zlr(t,e){if(e.target==="openApi3")return Ulr(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Coe&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=Coe[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 Ulr(t,e)}var Coe,Ulr,lCe=v(()=>{vd();Coe={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Ulr=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>vn(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 Hlr(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:Coe[t.innerType._def.typeName],nullable:!0}:{type:[Coe[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=vn(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=vn(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var BQe=v(()=>{vd();lCe()});function Vlr(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",SQe(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?
`):[]}};Zv=new WeakMap,Xv=new WeakMap;F2.NEWLINE_CHARS=new Set([`
`,"\r"]);F2.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function Ooe(){}function _Ce(t,e,r){return!e||vCe[t]>vCe[r]?Ooe:e[t].bind(e)}function nd(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Pto;let n=Lcr.get(e);if(n&&n[0]===r)return n[1];let o={error:_Ce("error",e,r),warn:_Ce("warn",e,r),info:_Ce("info",e,r),debug:_Ce("debug",e,r)};return Lcr.set(e,[r,o]),o}var vCe,bet,Pto,Lcr,F1,Toe=v(()=>{L1();vCe={off:0,error:200,warn:300,info:400,debug:500},bet=(t,e,r)=>{if(t){if(dcr(vCe,t))return t;nd(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(vCe))}`)}};Pto={error:Ooe,warn:Ooe,info:Ooe,debug:Ooe},Lcr=new WeakMap;F1=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*Mto(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new kt("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 kt("Attempted to iterate over a response with no body");let r=new _et,n=new F2,o=cet(t.body);for await(let i of Rto(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*Rto(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"?YW(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let i;for(;(i=Dcr(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function Ato(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var Eoe,bA,_et,vet=v(()=>{MS();hA();xoe();$cr();xoe();nCe();bCe();Toe();hA();bA=class t{constructor(e,r,n){this.iterator=e,Eoe.set(this,void 0),this.controller=r,qr(this,Eoe,n,"f")}static fromSSEResponse(e,r,n){let o=!1,i=n?nd(n):console;async function*a(){if(o)throw new kt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let s=!1;try{for await(let u of Mto(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 Rm(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 Rm(void 0,l.error,l.message,void 0);yield{event:u.event,data:l}}}s=!0}catch(u){if(yoe(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 F2,u=cet(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 kt("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(yoe(u))return;throw u}finally{s||r.abort()}}return new t(a,r,n)}[(Eoe=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,Eoe,"f")),new t(()=>o(r),this.controller,xe(this,Eoe,"f"))]}toReadableStream(){let e=this,r;return uet({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=YW(JSON.stringify(o)+`
`);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};_et=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]=Ato(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function wCe(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:o,startTime:i}=e,a=await(async()=>{if(e.options.stream)return nd(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller,t):bA.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 wet(d,r)}return await r.text()})();return nd(t).debug(`[${n}] response parsed`,F1({retryOfRequestLogID:o,url:r.url,status:r.status,body:a,durationMs:Date.now()-i})),a}function wet(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 Cet=v(()=>{vet();Toe()});var Poe,k2,SCe=v(()=>{MS();Cet();k2=class t extends Promise{constructor(e,r,n=wCe){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,Poe.set(this,void 0),qr(this,Poe,e,"f")}_thenUnwrap(e){return new t(xe(this,Poe,"f"),this.responsePromise,async(r,n)=>wet(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,Poe,"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)}};Poe=new WeakMap});var CCe,Moe,Roe,_A,Go,k1,Mu=v(()=>{MS();hA();Cet();SCe();L1();Moe=class{constructor(e,r,n,o){CCe.set(this,void 0),qr(this,CCe,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 kt("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await xe(this,CCe,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(CCe=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},Roe=class extends k2{constructor(e,r,n){super(e,r,async(o,i)=>new n(o,i.response,await wCe(o,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},_A=class extends Moe{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}},Go=class extends Moe{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:{...iet(this.options.query),after:r}}:null}},k1=class extends Moe{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:{...iet(this.options.query),after:e}}:null}}});function QW(t,e,r){return Tet(),new File(t,e??"unknown_file",r)}function Aoe(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 Nto(t){let e=typeof t=="fu
${i.map(f=>f.error).join(`
`)}
${a}
${d}`)}return a},$e=kto(Hcr)});var q2,OCe=v(()=>{Br();Mu();Ya();q2=class extends Ue{list(e,r={},n){return this._client.getAPIList($e`/chat/completions/${e}/messages`,Go,{query:r,...n})}}});var e8,Ret,Aet=v(()=>{e8=t=>t?.role==="assistant",Ret=t=>t?.role==="tool"});var Iet,TCe,ECe,Noe,joe,PCe,Doe,q1,$oe,MCe,RCe,t8,Vcr,lk,ACe=v(()=>{MS();RC();lk=class{constructor(){Iet.add(this),this.controller=new AbortController,TCe.set(this,void 0),ECe.set(this,()=>{}),Noe.set(this,()=>{}),joe.set(this,void 0),PCe.set(this,()=>{}),Doe.set(this,()=>{}),q1.set(this,{}),$oe.set(this,!1),MCe.set(this,!1),RCe.set(this,!1),t8.set(this,!1),qr(this,TCe,new Promise((e,r)=>{qr(this,ECe,e,"f"),qr(this,Noe,r,"f")}),"f"),qr(this,joe,new Promise((e,r)=>{qr(this,PCe,e,"f"),qr(this,Doe,r,"f")}),"f"),xe(this,TCe,"f").catch(()=>{}),xe(this,joe,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},xe(this,Iet,"m",Vcr).bind(this))},0)}_connected(){this.ended||(xe(this,ECe,"f").call(this),this._emit("connect"))}get ended(){return xe(this,$oe,"f")}get errored(){return xe(this,MCe,"f")}get aborted(){return xe(this,RCe,"f")}abort(){this.controller.abort()}on(e,r){return(xe(this,q1,"f")[e]||(xe(this,q1,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=xe(this,q1,"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,q1,"f")[e]||(xe(this,q1,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{qr(this,t8,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){qr(this,t8,!0,"f"),await xe(this,joe,"f")}_emit(e,...r){if(xe(this,$oe,"f"))return;e==="end"&&(qr(this,$oe,!0,"f"),xe(this,PCe,"f").call(this));let n=xe(this,q1,"f")[e];if(n&&(xe(this,q1,"f")[e]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...r))),e==="abort"){let o=r[0];!xe(this,t8,"f")&&!n?.length&&Promise.reject(o),xe(this,Noe,"f").call(this,o),xe(this,Doe,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=r[0];!xe(this,t8,"f")&&!n?.length&&Promise.reject(o),xe(this,Noe,"f").call(this,o),xe(this,Doe,"f").call(this,o),this._emit("end")}}_emitFinal(){}};TCe=new WeakMap,ECe=new WeakMap,Noe=new WeakMap,joe=new WeakMap,PCe=new WeakMap,Doe=new WeakMap,q1=new WeakMap,$oe=new WeakMap,MCe=new WeakMap,RCe=new WeakMap,t8=new WeakMap,Iet=new WeakSet,Vcr=function(e){if(qr(this,MCe,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new Ic),e instanceof Ic)return qr(this,RCe,!0,"f"),this._emit("abort",e);if(e instanceof kt)return this._emit("error",e);if(e instanceof Error){let r=new kt(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new kt(String(e)))}});function Jcr(t){return typeof t.parse=="function"}var Net=v(()=>{});var bb,jet,ICe,Det,$et,Let,Kcr,Wcr,Bto,r8,Fet=v(()=>{MS();RC();GW();Aet();ACe();Net();Bto=10,r8=class extends lk{constructor(){super(...arguments),bb.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let r=e.choices[0]?.message;return r&&this._addMessage(r),e}_addMessage(e,r=!0){if("content"in e||(e.content=null),this.messages.push(e),r){if(this._emit("message",e),Ret(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(e8(e)&&e.tool_calls)for(let n of e.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new kt("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),xe(this,bb,"m",jet).call(this)}async finalMessage(){return await this.done(),xe(this,bb,"m",ICe).call(this)}async finalFunctionToolCall(){return await this.done(),xe(this,bb,"m",Det).call(this)}async finalFunctionToolCallResult(){return await this.done(),xe(this,bb,"m",$et).call(this)}async totalUsage(){return await this.done(),xe(this,bb,"m",Let).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[th
\r `.includes(t[n]);)n++};return a()},Uet=t=>Uto(t,yh.ALL^yh.NUM)});var zet=v(()=>{vet()});function Hto(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 kt(`missing finish_reason for choice ${d}`);let{content:m=null,function_call:h,tool_calls:g,...y}=l,b=l.role;if(!b)throw new kt(`missing role for choice ${d}`);if(h){let{arguments:_,name:w}=h;if(_==null)throw new kt(`missing function_call.arguments for choice ${d}`);if(!w)throw new kt(`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 g?{...p,index:d,finish_reason:c,logprobs:f,message:{...y,role:b,content:m,refusal:l.refusal??null,tool_calls:g.map((_,w)=>{let{function:x,type:O,id:E,...T}=_,{arguments:R,name:N,...D}=x||{};if(E==null)throw new kt(`missing choices[${d}].tool_calls[${w}].id
${DCe(t)}`);if(O==null)throw new kt(`missing choices[${d}].tool_calls[${w}].type
${DCe(t)}`);if(N==null)throw new kt(`missing choices[${d}].tool_calls[${w}].function.name
${DCe(t)}`);if(R==null)throw new kt(`missing choices[${d}].tool_calls[${w}].function.arguments
${DCe(t)}`);return{...T,id:E,type:O,function:{...D,name:N,arguments:R}}})}}:{...p,message:{...y,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 ylr(u,e)}function DCe(t){return JSON.stringify(t)}var Im,B1,n8,ck,Het,NCe,Vet,Jet,Ket,jCe,Wet,Zcr,B2,$Ce=v(()=>{MS();Gcr();RC();GW();zet();Fet();B2=class t extends r8{constructor(e){super(),Im.add(this),B1.set(this,void 0),n8.set(this,void 0),ck.set(this,void 0),qr(this,B1,e,"f"),qr(this,n8,[],"f")}get currentChatCompletionSnapshot(){return xe(this,ck,"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,Im,"m",Het).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,Im,"m",Vet).call(this,a);if(i.controller.signal?.aborted)throw new Ic;return this._addChatCompletion(xe(this,Im,"m",jCe).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),xe(this,Im,"m",Het).call(this),this._connected();let o=bA.fromReadableStream(e,this.controller),i;for await(let a of o)i&&i!==a.id&&this._addChatCompletion(xe(this,Im,"m",jCe).call(this)),xe(this,Im,"m",Vet).call(this,a),i=a.id;if(o.controller.signal?.aborted)throw new Ic;return this._addChatCompletion(xe(this,Im,"m",jCe).call(this))}[(B1=new WeakMap,n8=new WeakMap,ck=new WeakMap,Im=new WeakSet,Het=function(){this.ended||qr(this,ck,void 0,"f")},NCe=function(r){let n=xe(this,n8,"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,n8,"f")[r.index]=n,n)},Vet=function(r){if(this.ended)return;let n=xe(this,Im,"m",Zcr).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,Im,"m",NCe).call(this,i);i.finish_reason&&(xe(this,Im,"m",Ket).call(this,i),a.current_tool_call_index!=null&&xe(this,Im,"m",Jet).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,Im,"m",Ket).call(this,i),a.current_tool_call_index!=null&&xe(this,Im,"m",Jet).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))}}},Jet=function(r,n){if(xe(this,Im,"m",NCe).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,B1,"f")?.tools?.find(s=>_oe(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??ert.DEFAULT_TIMEOUT,this.logger=s.logger??console;let u="warn";this.logLevel=u,this.logLevel=bet(s.logLevel,"ClientOptions.logLevel",this)??bet(NC("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??_cr(),qr(this,VCe,wcr,"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 at([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return get(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${uk}`}defaultIdempotencyKey(){return`stainless-node-retry-${ret()}`}makeStatusError(e,r,n,o){return Rm.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 kt?n:new kt(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof r!="string"||!r)throw new kt(`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,Qtt,"m",_dr).call(this)&&n||this.baseURL,i=lcr(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return ccr(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 k2(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(nd(this).debug(`[${l}] sending request`,F1({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(boe),m=Date.now();if(p instanceof globalThis.Error){let y=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new Ic;let b=yoe(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(r)return nd(this).info(`[${l}] connection ${b?"timed out":"failed"} - ${y}`),nd(this).debug(`[${l}] connection ${b?"timed out":"failed"} (${y})`,F1({retryOfRequestLogID:n,url:s,durationMs:m-d,message:p.message})),this.retryRequest(o,r,n??l);throw nd(this).info(`[${l}] connection ${b?"timed out":"failed"} - error; no more retries left`),nd(this).debug(`[${l}] connection ${b?"timed out":"failed"} (error; no more retries left)`,F1({retryOfRequestLogID:n,url:s,durationMs:m-d,message:p.message})),b?new pA:new ak({cause:p})}let h=[...p.headers.entries()].filter(([y])=>y==="x-request-id").map(([y,b])=>", "+y+": "+JSON.stringify(b)).join(""),g=`[${l}${c}${h}] ${a.method} ${s} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${m-d}ms`;if(!p.ok){let y=await this.shouldRetry(p);if(r&&y){let E=`retrying, ${r} attempts remaining`;return await vcr(p.body),nd(this).info(`${g} - ${E}`),nd(this).debug(`[${l}] response error (${E})`,F1({retryOfRequestLogID:n,url:p.ur
`))}let n={name:t.function.name,args:r,type:"tool_call"};return e?.returnId&&(n.id=t.id),n}function Sk(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 FC(t,e){return{name:t.function?.name,args:t.function?.arguments,id:t.id,error:e,type:"invalid_tool_call"}}var trt,kC,wdr=v(()=>{pY();V0();yN();O6();yL();f2e();trt=class extends gL{constructor(e){super(e);M(this,"returnId",!1);M(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);M(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(Us(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=>LC(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}},kC=class extends trt{constructor(e){super(e);M(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);M(this,"lc_serializable",!0);M(this,"returnId",!1);M(this,"keyName");M(this,"returnSingle",!1);M(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 sL(this.zodSchema,e);if(r.success)return r.data;throw new eh(`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 Mro,sH=v(()=>{Do();wdr();Mro={};Et(Mro,{JsonOutputKeyToolsParser:()=>kC,JsonOutputToolsParser:()=>trt,convertLangChainToolCallToOpenAI:()=>Sk,makeInvalidToolCall:()=>FC,parseToolCall:()=>LC})});var uH,Hoe=v(()=>{ok();ik();goe();fCe();CA();nl();D1();Wv();xv();_O();sH();Gv();o_();uH=class extends hh{constructor(e){super(e??{});M(this,"temperature");M(this,"topP");M(this,"frequencyPenalty");M(this,"presencePenalty");M(this,"n");M(this,"logitBias");M(this,"model","gpt-3.5-turbo");M(this,"modelKwargs");M(this,"stop");M(this,"stopSequences");M(this,"user");M(this,"timeout");M(this,"streaming",!1);M(this,"streamUsage",!0);M(this,"maxTokens");M(this,"logprobs");M(this,"topLogprobs");M(this,"apiKey");M(this,"organization");M(this,"__includeRawResponse");M(this,"client");M(this,"clientConfig");M(this,"supportsStrictToolCalling");M(this,"audio");M(this,"modalities");M(this,"reasoning");M(this,"zdrEnabled");M(this,"service_tier");M(this,"promptCacheKey");M(this,"verbosity");M(this,"defaultOptions");M(this,"lc_serializable",!0);let r=typeof e?.configuration?.apiKey=="string"?e?.configuration?.apiKey:void 0;this.apiKey=e?.apiKey??r??gn("OPENAI_API_KEY"),this.organization=e?.configuration?.organization??gn("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.logitBias=e?.logitBias,this.stop=e?.stopSequences??e?.stop,this.stopSequences=this.stop,t
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
`,t}var Sdr=v(()=>{});function xA(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===pA.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===Ic.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=Voe(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=Voe(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=Voe(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=Voe(t,"MODEL_NOT_FOUND"):e=t,e}var lH=v(()=>{Sdr();CA()});function Rro(t){if(t.type==="image"){if(t.url)return{type:"image_url",image_url:{url:t.url}};if(t.data)return{type:"image_url",image_url:{url:`data:${t.mimeType};base64,${t.data}`}}}if(t.type==="audio"&&t.data){let e=MC(()=>{let[,r]=t.mimeType.split("/");return r==="wav"||r==="mp3"?r:"wav"});return{type:"input_audio",input_audio:{data:t.data.toString(),format:e}}}if(t.type==="file"){if(t.data)return{type:"file",file:{file_data:t.data.toString()}};if(t.fileId)return{type:"file",file:{file_id:t.fileId}}}}function Cdr(t,e){let r=dA(t);if(r==="system"&&cA(e)&&(r="developer"),r==="developer")return{role:"developer",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="system")return{role:"system",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="assistant")return{role:"assistant",content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="tool"&&Gb.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(o=>o.type==="text")};if(r==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(o=>o.type==="text").join("")};function*n(o){for(let i of o){i.type==="text"&&(yield{type:"text",text:i.text});let a=Rro(i);a&&(yield a)}}return{role:"user",content:Array.from(n(t.contentBlocks))}}function xdr(t){let e=Us(t)&&t.response_metadata?.model_provider==="openai";function*r(){let n=MC(()=>{try{let y=dA(t);return y==="system"||y==="developer"||y==="assistant"||y==="user"?y:"assistant"}catch{return"assistant"}}),o,i=new Set,a=new Set,s=new Map,u=new Map;function*l(){if(!o)return;let y=o.content;(typeof y=="string"&&y.length>0||Array.isArray(y)&&y.length>0)&&(yield o),o=void 0}let c=y=>{o||(o={type:"message",role:n,content:[]}),typeof o.content=="string"?o.content=o.content.length>0?[{type:"input_text",text:o.content},...y]:[...y]:o.content.push(...y)},d=y=>{if(typeof y=="string")return y;try{return JSON.stringify(y??{})}catch{return"{}"}},f=y=>{let b=MC(()=>{let _=y.metadata?.detail;return _==="low"||_==="high"||_==="auto"?_:"auto"});if(y.fileId)return{type:"input_image",detail:b,file_id:y.fileId};if(y.url)return{type:"input_image",detail:b,image_url:y.url};if(y.data){let _=typeof y.data=="string"?y.data:Buffer.from(y.data).toString("base64"),w=y.mimeType??"image/png";return{type:"input_image",detail:b,image_url:`data:${w};base64,${_}`}}},p=y=>{let b=y.metadata?.filename??y.metadata?.name??y.metadata?.title;if(y.fileId&&typeof b=="string")return{type:"input_file",file_id:y.fileId,...b?{filename:b}:{}};if(y.url&&typeof b=="string")return{type:"input_file",file_url:y.url,...b?{filename:b}:{}};if(y.data&&typeof b=="string"){let _=typeof y.data=="string"?y.data:Buffer.from(y.data).toString("base64");return{type:"input_file",file_data:`data:${y.mimeType??"application/octet-stream"};base64,${_}`,...b?{filename:b}:{}}}},m=y=>{let b=MC(()=>{if(Array.isArray(y.summary)){let O=y.summary?.map(E=>E?.text).filter(E=>typeof E=="string")??[];if(O.length>0)return O}return y.reasoning?[y.reasoning]:[]}),_=b.length>0?b.map(x=>({type:"summary_text",text:x})):[{type:"summary_text",text:""}],w={type:"reasoning",id:y.id??"",summary:_};return y.reasoning&&(w.content=[{type:"reasoning_text",text:y.reasoning}]),w},h=y=>({type:"function_call",name:y.name??"",call_id:y.id??"",arguments:d(y.args)}),g=y=>{let b=d(y.output),_=y.status==="success"?"completed":y.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id
Details: ${m.message}`),m instanceof Error&&m.constructor.name==="ZodError"&&(h=`${h}
${mxe.prettifyError(m)}`),new K3(h,JSON.stringify(e))}else{let m=Fu(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(g=>`${g.keywordLocation}: ${g.error}`).join(`
`)}`),new K3(h,JSON.stringify(e))}i=o}let a=lN(r),u=await Yl.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;J$(e)&&(f=e.id),!f&&ySt(a)&&(f=a.toolCall.id);let p=Xno({content:c,artifact:d,toolCallId:f,name:this.name,metadata:this.metadata});return await u?.handleToolEnd(p),p}},Qrt=class extends Yrt{constructor(e){super(e);M(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)}},ent=class extends Qrt{constructor(e){super(e);M(this,"name");M(this,"description");M(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=lN(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)}},Pfr=class extends Yrt{constructor(e){super(e);M(this,"name");M(this,"description");M(this,"func");M(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=lN(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)}},Gno=class{getTools(){return this.tools}}});var rnt=v(()=>{CA();nl();tnt()});var Mfr=v(()=>{rnt()});var Rfr=v(()=>{xv();tnt();rz()});var Afr=v(()=>{Koe()});var cH=v(()=>{ok();ik();Hoe();lH();Koe();WCe();GCe();ort();irt();art();Adr();srt();Idr();urt();Ndr();rnt();Mfr();Rfr();Afr();CA()});var Nfr=S((oja,Ifr)=>{Ifr.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 Qno,eoo,jfr,Dfr=v(()=>{Qno=L(Nfr(),1),eoo=Object.defineProperty,jfr=(t,e)=>{for(var r in e)eoo(t,r,{get:e[r],enumerable:!0})}});var too,nnt,$fr=v(()=>{Dfr();nl();M2();tk();too={};jfr(too,{JinaEmbeddings:()=>nnt});nnt=class extends ES{constructor(e){let r={maxConcurrency:2,...e};super(r);M(this,"model","jina-clip-v2");M(this,"batchSize",24);M(this,"baseUrl","https://api.jina.ai/v1/embeddings");M(this,"stripNewLines",!0);M(this,"dimensions",1024);M(this,"apiKey");M(this,"normalized",!0);let n=r?.apiKey||gn("JINA_API_KEY")||gn("JINA_AUTH_TOKEN");if(!n)throw new Error("Jina API key not found");this.apiKey=n,this.model=r?.model??this.model,this.dimensions=r?.dimensions??this.dimensions,this.batchSize=r?.batchSize??this.batchSize,this.stripNewLines=r?.stripNewLines??this.stripNewLines,this.normalized=r?.normalized??this.normalized}doStripNewLines(e){return this.stripNewLines?e.map(r=>typeof r=="string"?r.replace(/\n/g," "):r.text?{text:r.text.replace(/\n/g," ")}:r):e}async embedDocuments(e){let r=PS(this.doStripNewLines(e),this.batchSize),n=r.map(a=>{let s=this.getParams(a);return this.embeddingWithRetry(s)}),o=await Promise.all(n),i=[];for(let a=0;a<o.length;a+=1){let s=r[a],u=o[a]||[];for(let l=0;l<s.length;l+=1)i.push(u[l])}return i}async embedQuery(e){let r=this.getParams(this.doStripNewLines([e]),!0);return(await this.embeddingWithRetry(r)||[[]])[0]}getParams(e,r){return{model:this.model,input:e,dimensions:this.dimensions,task:r?"retrieval.query":"retrieval.passage",normalized:this.normalized}}async embeddingWithRetry(e){let n=await(await fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(e)})).json();if("detail"in n&&n.detail)throw new Error(`${n.detail}`);return n.data.map(({embedding:o})=>o)}}});var hxe,Lfr=v(()=>{$fr();hxe=class extends nnt{constructor(e){super(e),e?.baseUrl&&(this.baseUrl=e.baseUrl)}}});var Qoe,Ffr=v(()=>{cH();Qoe=class extends xk{constructor(e){super(e),this.customConfig=e}async embedQuery(e){return(await this.callEmbeddingAPI([e]))[0]}async embedDocuments(e){return await this.callEmbeddingAPI(e)}async callEmbeddingAPI(e){let r={model:this.customConfig.modelName,input:e,encoding_format:"float"},o=`${this.customConfig.configuration?.baseURL||"https://api.openai.com/v1"}/embeddings`,i=this.customConfig.apiKey,s=await
without CORS Error: `+Eo(n)+`
with CORS Error: `+Eo(o);throw new Error(i)}}}}});function Bfr(t){return t!==void 0&&eie.includes(t)?kfr[t]:void 0}var kfr,qfr,eie,yxe=v(()=>{kfr={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"},qfr={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},eie=Object.keys(kfr)});function Au(t,e){if(e.length<ont)Array.prototype.push.apply(t,e);else{let r=e.length;for(let n=0;n<r;n+=ont)Array.prototype.push.apply(t,e.slice(n,n+ont))}}function Jfr(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 ioo(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function aoo(){return typeof process<"u"&&process.release&&process.release.name==="node"}function Vfr(){return BigInt(Math.floor(performance.now()*1e6))}function fH(t){return typeof t=="number"&&(t=BigInt(t)),t<Ufr?`${t}ns`:t<zfr?`${t/Ufr}\u03BCs`:t<Hfr?`${t/zfr}ms`:`${t/Hfr}s`}function qC(){return ioo()?Vfr():aoo()||typeof process<"u"&&typeof process?.hrtime?.bigint=="function"?process.hrtime.bigint():typeof performance<"u"?Vfr():BigInt(0)}function tie(){return`${noo}-${ooo++}`}function j8(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 Kfr(t,e){return e[1]===t[1]?t[0]-e[0]:e[1]-t[1]}function D8(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 bxe(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 $8(t,e){return bxe(t,[e])[e]}fu
- `),loo={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:
- ${uoo}`,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 Wfr(t){return{raw:Number(t),formatted:fH(t)}}function Gfr(t){if(t.id){if(typeof t.id!="string")throw jr("DOCUMENT_ID_MUST_BE_STRING",typeof t.id);return t.id}return tie()}function ant(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(K1(n)){let i=unt(n);if(!Array.isArray(o)||o.length!==i)throw jr("INVALID_INPUT_VECTOR",r,i,o.length);continue}if(L8(n)){if(!Array.isArray(o))return r;let i=snt(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=ant(o,n);if(i)return r+"."+i;continue}if(typeof o!==n)return r}}}function Zfr(t){return t==="geopoint"}function K1(t){return typeof t=="string"&&/^vector\[\d+\]$/.test(t)}function L8(t){return typeof t=="string"&&coo[t]}function snt(t){return doo[t]}function unt(t){let e=Number(t.slice(7,-1));switch(!0){case isNaN(e):throw jr("INVALID_VECTOR_VALUE",t);case e<=0:throw jr("INVALID_VECTOR_SIZE",t);default:return e}}var coo,doo,rie=v(()=>{bh();od();od();coo={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},doo={"string[]":"string","number[]":"number","boolean[]":"boolean","enum[]":"enum"}});function Xfr(){return{idToInternalId:new Map,internalIdToId:[],save:foo,load:poo}}function foo(t){return{internalIdToId:t.internalIdToId}}function poo(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 ru(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?ru(t,e.toString()):e}function AS(t,e){if(t.internalIdToId.length<e)throw new Error(`Invalid internalId ${e}`);return t.internalIdToId[e-1]}var IS=v(()=>{});function hoo(t,e){return{sharedInternalDocumentStore:e,docs:{},count:0}}function goo(t,e){let r=ru(t.sharedInternalDocumentStore,e);return t.docs[r]}function yoo(t,e){let r=e.length,n=Array.from({length:r});for(let o=0;o<r;o++){let i=ru(t.sharedInternalDocumentStore,e[o]);n[o]=t.docs[i]}return n}function boo(t){return t.docs}function _oo(t,e,r){let n=ru(t.sharedInternalDocumentStore,e);return typeof t.docs[n]<"u"?!1:(t.docs[n]=r,t.count++,!0)}function voo(t,e){let r=ru(t.sharedInternalDocumentStore,e);return typeof t.docs[r]>"u"?!1:(delete t.docs[r],t.count--,!0)}function woo(t){return t.count}function Soo(t,e){let r=e;return{docs:r.docs,count:r.count,sharedInternalDocumentStore:t}}function Coo(t){return{docs:t.docs,count:t.count}}function Yfr(){return{create:hoo,get:goo,getMultiple:yoo,getAll:boo,store:_oo,remove:voo,count:woo,load:Soo,save:Coo}}var lnt=v(()=>{IS()});function epr(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),jr("PLUGIN_CRASHED")}return r}var Qfr,tpr=v(()=>{bh();Qfr=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeLoad","afterLoad","afterCreate"]});function BC(t,e,r,n){if(t.some(Sd))return(async()=>{for(let i of t)await i(e,r,n)})();for(let i of t)i(e,r,n)}function pH(t,e,r){if(t.some(Sd))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}},pie=class Ynt extends Ehr{constructor(r){super(r);M(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 Ynt({...n,separators:Ynt.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 Qnt=v(()=>{Phr()});var Mhr,PA,SOe,Rhr=v(()=>{zr();dH();Dt();xhr();Pt();wr();Mhr=L(V8());Qnt();PA=require("obsidian");vb();SOe=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=ce();this.rateLimiter=new die(o.embeddingRequestsPerMin),this.embeddingBatchSize=o.embeddingBatchSize,this.checkpointInterval=8*this.embeddingBatchSize,Ou(async()=>{let i=ce();this.rateLimiter=new die(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 PA.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 PA.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){ue(`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(()=>{J("Copilot index final save completed."),this.dbOps.checkIndexIntegrity().catch(s=>{ue("Background integrity check failed:",s)})}).catch(s=>{ue("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=wd.getModelName(r),o=pie.fromLanguage("markdown",{chunkSize:qz}),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:Zh(new Date(a.stat.ctime)).display,modified:Zh(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,Mhr.MD5)(e).toString()}async getFilesToIndex(e){let{inclusions:r,exclusions:n}=id(),o=this.app.vault.getMarkdownFiles();if(e)return o.filter(c=>ml(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(!ml(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 J([`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 PA.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 PA.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=ce(),o=P_(n.qaInclusions);o.length>0&&r.push(`Inclusions: ${o.join(", ")}`);let a=[...lie(this.app),...P_(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 PA.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 PA.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 PA.Notice("Indexing cancelled");return}e.length>0?new PA.Notice(`Indexing completed with ${e.length} errors. Check console for details.`):new PA.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(),ce().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 vg={};Xn(vg,{default:()=>Z1});var mie,Z1,Dm=v(()=>{MN();dH();Pt();mie=require("obsidian");vOe();Chr();Rhr();Z1=class t{constructor(){this.embeddingsManager=wd.getInstance(),this.dbOps=new G1(app),this.indexOps=new SOe(app,this.dbOps,this.embeddingsManager),this.eventHandler=new wOe(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={...ce()};let e=async()=>{let r=ce(),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())}};Ou(()=>{this.initializationPromise=e()})}async initialize(){if(ce().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 Po&&n.message.includes("Vault adapter not available")&&(r--,r>0)){await new Promise(o=>setTimeout(o,100));continue}new mie.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(),mie.Platform.isMobile&&ce().disableIndexOnMobile?(new mie.Notice("Indexing is disabled on mobile devices"),0):this.indexOps.indexVaultToVectorStore(e)}async clearIndex(){a
${e.join(`
`)}`)}}});var eG,lot=v(()=>{uot();RS();wr();Dt();eG=class t{constructor(){this.mentions=new Map,this.brevilabsClient=Ru.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=Eo(r);return ue(`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=Eo(r);return ue(`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 MA.isImageUrl(s,app.vault))return n.push(s),{type:"image",url:s};if(OAt(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 Bhr,TOe,Uhr=v(()=>{Dt();Bhr=L(V8()),TOe=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)||(J("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,Bhr.MD5)(r).toString();return J("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)){J("Cache hit for PDF:",e.path);let o=await app.vault.adapter.read(n);return JSON.parse(o)}return J("Cache miss for PDF:",e.path),null}catch(r){return ue("Error reading from PDF cache:",r),null}}async set(e,r){try{await this.ensureCacheDir();let n=this.getCacheKey(e),o=this.getCachePath(n);J("Caching PDF response for:",e.path),await app.vault.adapter.write(o,JSON.stringify(r))}catch(n){ue("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);J("Clearing PDF cache, removing files:",e.files.length);for(let r of e.files)await app.vault.adapter.remove(r)}}catch(e){ue("Error clearing PDF cache:",e)}}}});function X1(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 zhr(t){let r=(t?.message||t?.toString()||"").match(/Try again in ([\d\w\s]+)/);return r?r[1]:"some time"}var gie=v(()=>{});var Hhr,POe,Vhr,EOe,Jhr=v(()=>{Hhr=require("obsidian"),EOe=class{constructor(e){this.vault=e;dY(this,POe)}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 Hhr.TFile?await this.vault.cachedRead(l):"";return{...u,content:c}}return u.type==="text"?{...u,content:u.text??""}:{...u,content:""}})),a=[...o];Zwt(this,POe,Vhr).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}};POe=new WeakSet,Vhr=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 Khr,cot,MOe,dot,tG,yie,Ik,ROe=v(()=>{Uhr();hie();Dt();gie();Khr=require("obsidian");Jhr();cot=class{constructor(){this.supportedExtensions=["md"]}async parseFile(e,r){return await r.read(e)}},MOe=class{constructor(e){this.supportedExtensions=["pdf"];this.brevilabsClient=e,this.pdfCache=TOe.getInstance()}async parseFile(e,r){try{J("Parsing PDF file:",e.path);let n=await this.pdfCache.get(e);if(n)return J("Using cached PDF content for:",e.path),n.response;let o=await r.readBinary(e);J("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 ue(`Error extracting content from PDF ${e.path}:`,n),`[Error: Could not extract content from PDF ${e.basename}]`}}async clearCache(){J("Clearing PDF cache"),await this.pdfCache.clear()}},dot=class{constructor(){this.supportedExtensions=["canvas"]}async parseFile(e,r){try{J("Parsing Canvas file:",e.path);let n=new EOe(r),o=await n.load(e);return n.buildPrompt(o)}catch(n){return ue(`Error parsing Canvas file ${e.path}:`,n),`[Error: Could not parse Canvas file ${e.basename}]`}}},tG=class tG{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=UC.getInstance(),this.currentProject=r}static resetRateLimitNoticeTimer(){tG.lastRateLimitNoticeTime=0}async parseFile(e,r){try{if(J(`[Docs4LLMParser] Project ${this.currentProject?.name}: Parsing ${e.extension} file: ${e.path}`),!this.currentProject)throw ue("[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 J(`[Docs4LLMParser] Project ${this.currentProject.name}: Using cached content for: ${e.path}`),n;J(`[Docs4LLMParser] Project ${this.currentProject.name}: Cache miss for: ${e.path}. Proceeding to API call.`);let o=await r.readBinary(e);J(`[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),J(`[Docs4LLMParser] Project ${this.currentProject.name}: Successfully processed and cached: ${e.path}`),a}catch(n){throw ue(`[Docs4LLMParser] Project ${this.currentProject?.name}: Error processing file ${e.path}:`,n),X1(n)&&this.showRateLimitNotice(n),n}}showRateLimitNotice(e){let r=Date.now();if(r-tG.lastRateLimitNoticeTime<6e4)return;tG.lastRateLimitNoticeTime=r;let n=zhr(e);new Khr.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(){J("Cache clearing is now handled at the project level")}};tG.lastRateLimitNoticeTime=0;yie=tG,Ik=class{constructor(e,r,n=!1,o=null){this.parsers=new Map;this.isProjectMode=n,this.currentProject=o,this.registerParser(new cot),this.registerParser(new yie(e,o)),n||this.registerParser(new MOe(e)),this.registerParser(new dot)}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 MOe&&await e.clearCache()}}});var yot={};Xn(yot,{createToolCallMarker:()=>IOe,decodeResultFromMarker:()=>mot,decodeToolCallMarkerResults:()=>vao,ensureEncodedToolCallMarkerResults:()=>AOe,parseToolCallMarkers:()=>hot,updateToolCallMarker:()=>got});function pot(t){try{return`ENC:${encodeURIComponent(t)}`}catch{return t}}function mot(t){if(typeof t!="string"||!t.startsWith("ENC:"))return t;try{return decodeURIComponent(t.slice(4))}catch{return t}}function _ao(t){return`Tool '${t}' ${bao}`}function vao(t){return!t||typeof t!="string"?t:t.replace(/<!--TOOL_CALL_END:([^:]+):(ENC:[\s\S]*?)-->/g,(e,r,n)=>{let o=mot(n)||n;return`<!--TOOL_CALL_END:${r}:${o}-->`})}function AOe(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=pot(n);return`<!--TOOL_CALL_END:${r}:${o}-->`})}function fot(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);fot(_,o,e).forEach(x=>{x.type==="text"&&x.content.trim()?r.push({type:"text",content:x.content}):x.type==="error"&&x.error&&r.push({type:"error",content:x.content,error:x.error})})}let[a,s,u,l,c,d,f,p,m]=i,g=mot(typeof m=="string"?m:""),b=(typeof g=="string"?g.length:0)>5e3?_ao(u):g??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);fot(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&&fot(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 IOe(t,e,r,n,o="",i=!0,a="",s=""){let u=s&&pot(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(()=>(bie(),yot)),m=f(e).segments.map(g=>g.type==="text"?g.content:"").join("").trim();m||(m=e||"");let h=m.length>d?m.slice(0,d)+"... (truncated)":m;J(`Final AI response (truncated):
`,h)}catch{let f=typeof e=="string"?e:String(e??""),p=f.length>d?f.slice(0,d)+"... (truncated)":f;J(`Final AI response (truncated):
`,p)}return e}async handleError(e,r){let n=Eo(e);ue("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}`,ue(o),r(this.enhancedErrorMsg(a,n))}enhancedErrorMsg(e,r){let n=e.search("Troubleshooting URL");return e=n!==-1?e.slice(0,n):e,r.search(/401|invalid|not valid/gi)!==-1&&(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}}});function Whr(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 Ghr(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 Zhr=v(()=>{});function wao(){return 1e4}function Sao(t,e){let r=e??wao();if(!t||t.length<=r)return t;let n=t.substring(0,r),o=t.length-r;return`${n}
... (truncated ${o.toLocaleString()} characters)`}function Cao(t,e,r){let n=Sao(e,r);return`Tool '${t}' result: ${n}`}function bot(t,e=!1){return t.map(r=>e?Cao(r.toolName,r.result):`Tool '${r.toolName}' result: ${r.result}`).join(`
`)}function xao(t){return`<errorChunk>${t}</errorChunk>`}function rG(t,e){let r=xao(t);return e?`${e}
${r}`:`
${r}`}var NOe=v(()=>{});var M_,wH=v(()=>{Zhr();NOe();M_=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}handleClaude37Chunk(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){let r=!1;if(e.additional_kwargs?.delta?.reasoning){if(this.excludeThinking)return!0;this.hasOpenThinkBlock||(this.fullResponse+=`
<think>`,this.hasOpenThinkBlock=!0),this.fullResponse+=e.additional_kwargs.delta.reasoning,r=!0}if(e.additional_kwargs?.reasoning_details){let n=e.additional_kwargs.reasoning_details;if(Array.isArray(n)&&n.length>0){if(this.excludeThinking)return!0;for(let o of n)o.encrypted?(this.hasOpenThinkBlock||(this.fullResponse+=`
<think>`,this.hasOpenThinkBlock=!0),this.fullResponse+="[Encrypted reasoning]",r=!0):o.text?(this.hasOpenThinkBlock||(this.fullResponse+=`
<think>`,this.hasOpenThinkBlock=!0),this.fullResponse+=o.text,r=!0):o.summary&&(this.hasOpenThinkBlock||(this.fullResponse+=`
<think>`,this.hasOpenThinkBlock=!0),this.fullResponse+=o.summary,r=!0)}}return typeof e.content=="string"&&e.content&&this.hasOpenThinkBlock&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),typeof e.content=="string"&&e.content&&(this.fullResponse+=e.content),r}processChunk(e){if(this.shouldTruncate)return;Whr(e).wasTruncated&&(this.wasTruncated=!0);let n=Ghr(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.handleClaude37Chunk(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=rG(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 wie,Xhr=v(()=>{zr();Dt();Pt();wr();vie();wH();wie=class extends Y1{async run(e,r,n,o,i){let a=new M_(n);try{let c=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),d=U6(c),f=[],p=await PN(this.chainManager.userMemoryManager),m=this.chainManager.chatModelManager.getChatModel();p&&f.push({role:wL(m),content:p});for(let g of d)f.push({role:g.role,content:g.content});if(e.content&&Array.isArray(e.content)){let g=e.content.map(y=>y.type==="text"?{...y,text:e.message}:y);f.push({role:"user",content:g})}else f.push({role:"user",content:e.message});J(`Final Request to AI:
`,f);let h=await Xh(()=>this.chainManager.chatModelManager.getChatModel().stream(f,{signal:r.signal}));for await(let g of h){if(r.signal.aborted){J("Stream iteration aborted",{reason:r.signal.reason});break}a.processChunk(g)}}catch(l){l.name==="AbortError"||r.signal.aborted?J("Stream aborted by user",{reason:r.signal.reason}):await this.handleError(l,a.processErrorChunk.bind(a))}let s=a.close(),u={wasTruncated:s.wasTruncated,tokenUsage:s.tokenUsage??void 0};return r.signal.aborted&&r.signal.reason==="new-chat"?(n(""),""):(await this.handleResponse(s.content,e,r,o,n,void 0,void 0,u),s.content)}}});var Oao,SH,jOe=v(()=>{Do();X$();uO();Gh();Oao={};Et(Oao,{BaseRetriever:()=>SH});SH=class extends Lo{constructor(e){super(e);M(this,"callbacks");M(this,"tags");M(this,"metadata");M(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=Jo(lN(r)),i=await(await Yl.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 vot,_ot,Nk,DOe=v(()=>{Dt();zr();vot=require("obsidian");Qnt();_ot={maxChars:qz,overlap:0,maxBytesTotal:10*1024*1024},Nk=class{constructor(e){this.app=e;this.cache=new Map;this.memoryUsage=0;this.splitter=pie.fromLanguage("markdown",{chunkSize:qz,chunkOverlap:0,separators:[`
`,`
`,". "," ",""],keepSeparator:!1})}async getChunks(e,r={}){try{if(!Array.isArray(e))return Ot("ChunkManager: Invalid notePaths provided"),[];if(e.length===0)return[];e.length>1e3&&(Ot("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 Ot("ChunkManager: No valid note paths provided"),[];let o={..._ot,...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):Ot(`ChunkManager: Skipping cache for ${a}, would exceed memory budget`)}i.push(...s)}return J(`ChunkManager: Retrieved ${i.length} chunks from ${n.length} notes (${this.formatMemoryUsage()})`),i}catch(n){return Ot("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||Ot(`ChunkManager: Chunk ${e} not found after regeneration`),o||null}async getValidatedChunks(e){let r=this.cache.get(e);if(!r&&(J(`ChunkManager: Cache miss for ${e}, regenerating...`),r=await this.regenerateChunks(e),!r||r.length===0))return Ot(`ChunkManager: Failed to regenerate chunks for ${e}`),[];let n=this.app.vault.getAbstractFileByPath(e);return n&&n instanceof vot.TFile&&r.length>0&&n.stat.mtime>r[0].mtime&&(J(`ChunkManager: File ${e} modified, regenerating chunks`),r=await this.regenerateChunks(e),!r||r.length===0)?(Ot(`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||"":(Ot(`ChunkManager: Chunk not in cache: ${e} (use async getChunkText for auto-regeneration)`),"")}async regenerateChunks(e){try{let r=await this.generateChunksForNote(e,_ot);if(r.length>0){let n=this.calculateChunkBytes(r);if(this.memoryUsage+n<=_ot.maxBytesTotal){let o=this.cache.get(e);o&&(this.memoryUsage-=this.calculateChunkBytes(o)),this.cache.set(e,r),this.memoryUsage+=n}else Ot(`ChunkManager: Cannot cache regenerated chunks for ${e}, would exceed memory budget`)}return r}catch(r){return Ot(`ChunkManager: Failed to regenerate chunks for ${e}`,r),[]}}clearCache(){this.cache.clear(),this.memoryUsage=0,J("ChunkManager: Cache cleared")}async generateChunksForNote(e,r){try{let n=this.app.vault.getAbstractFileByPath(e);if(!n||!(n instanceof vot.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 Ot(`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){Ot(`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 Ot(`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 wot=S(()=>{});function wg(t,e,r){let n=typeof r,o=typeof t;if(n!=="undefined"){if(o!=="undefined"){if(r){if(o==="function"&&n===o)return function(s){return t(r(s))};if(e=t.constructor,e===r.constructor){if(e===Array)return r.concat(t);if(e===Map){var i=new Map(r);for(var a of t)i.set(a[0],a[1]);return i}if(e===Set){a=new Set(r);for(i of t.values())a.add(i);return a}}}return t}return r}return o==="undefined"?e:t}function nG(t,e){return typeof t>"u"?e:t}function Nc(){return Object.create(null)}function zC(t){return typeof t=="string"}function Cie(t){return typeof t=="object"}function xie(t,e){if(zC(e))t=t[e];else for(let r=0;t&&r<e.length;r++)t=t[e[r]];return t}function sG(t={}){if(!this||this.constructor!==sG)return new sG(...arguments);if(arguments.length)for(t=0;t<arguments.length;t++)this.assign(arguments[t]);else this.assign(t)}function xH(t){t.F=null,t.B.clear(),t.D.clear()}function Pot(t,e,r){r||(e||typeof t!="object"?typeof e=="object"&&(r=e,e=0):r=t),r&&(t=r.query||t,e=r.limit||e);let n=""+(e||0);r&&(n+=(r.offset||0)+!!r.context+!!r.suggest+(r.resolve!==!1)+(r.resolution||this.resolution)+(r.boost||0)),t=(""+t).toLowerCase(),this.cache||(this.cache=new EH);let o=this.cache.get(t+n);if(!o){let i=r&&r.cache;i&&(r.cache=!1),o=this.search(t,e,r),i&&(r.cache=i),this.cache.set(t+n,o)}return o}function EH(t){this.limit=t&&t!==!0?t:1e3,this.cache=new Map,this.h=""}function ngr(t,e,r,n){let o=[];for(let i=0,a;i<t.index.length;i++)if(a=t.index[i],e>=a.length)e-=a.length;else{e=a[n?"splice":"slice"](e,r);let s=e.length;if(s&&(o=o.length?o.concat(e):e,r-=s,n&&(t.length-=s),!r))break;e=0}return o}function uG(t){if(!this||this.constructor!==uG)return new uG(t);this.index=t?[t]:[],this.length=t?t.length:0;let e=this;return new Proxy([],{get(r,n){if(n==="length")return e.length;if(n==="push")return function(o){e.index[e.index.length-1].push(o),e.length++};if(n==="pop")return function(){if(e.length)return e.length--,e.index[e.index.length-1].pop()};if(n==="indexOf")return function(o){let i=0;for(let a=0,s,u;a<e.index.length;a++){if(s=e.index[a],u=s.indexOf(o),u>=0)return i+u;i+=s.length}return-1};if(n==="includes")return function(o){for(let i=0;i<e.index.length;i++)if(e.index[i].includes(o))return!0;return!1};if(n==="slice")return function(o,i){return ngr(e,o||0,i||e.length,!1)};if(n==="splice")return function(o,i){return ngr(e,o||0,i||e.length,!0)};if(n==="constructor")return Array;if(typeof n!="symbol")return(r=e.index[n/2**31|0])&&r[n]},set(r,n,o){return r=n/2**31|0,(e.index[r]||(e.index[r]=[]))[n]=o,e.length++,!0}})}function HC(t=8){if(!this||this.constructor!==HC)return new HC(t);this.index=Nc(),this.h=[],this.size=0,t>32?(this.B=dgr,this.A=BigInt(t)):(this.B=cgr,this.A=t)}function VC(t=8){if(!this||this.constructor!==VC)return new VC(t);this.index=Nc(),this.h=[],this.size=0,t>32?(this.B=dgr,this.
`).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=Eie(e),o=this.combineBaseAndTagTerms(r,n,e),i=new Set([e]);for(let s of o)if(!s.startsWith("#")&&s.length>=3){let u=GOe.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(),J("QueryExpander: Cache cleared")}getCacheSize(){return this.cache.size}async expandQueries(e){return(await this.expand(e)).queries}};XOe.PROMPT_TEMPLATE=`Generate alternative search queries and semantically related terms for the following query:
"{query}"
Instructions:
1. Generate {count} alternative search queries that capture the same intent
2. Extract semantically related terms that someone might use when searching for this topic
3. Include:
- Keywords from the original query
- Synonyms and related concepts
- Domain-specific terminology
- Associated terms someone might use
4. Keep the SAME LANGUAGE as the original query
5. Focus on NOUNS and meaningful concepts
6. EXCLUDE common action verbs in ANY language (find, search, get, \u67E5\u627E, chercher, buscar, etc.)
Example: "find my piano notes"
- Queries: "piano lesson notes", "piano practice sheets"
- Terms: piano, notes, music, sheet, practice, lesson, piece, scales, exercises
Example: "typescript interfaces"
- Queries: "typescript type definitions", "typescript contracts"
- Terms: typescript, interfaces, types, definitions, contracts, typing, declarations
Example: "\u67E5\u627E\u6211\u7684\u7B14\u8BB0" (Chinese)
- Queries: "\u6211\u7684\u5B66\u4E60\u7B14\u8BB0", "\u4E2A\u4EBA\u7B14\u8BB0\u6587\u6863"
- Terms: \u7B14\u8BB0, \u6587\u6863, \u8BB0\u5F55, \u8D44\u6599, \u5B66\u4E60, \u5907\u5FD8\u5F55 (keep in Chinese)
Example: "rechercher documents projet" (French)
- Queries: "documents de projet", "fichiers projet"
- Terms: documents, projet, fichiers, dossiers, archives (keep in French)
Format your response using XML tags:
<queries>
<query>alternative query 1</query>
<query>alternative query 2</query>
</queries>
<terms>
<term>keyword1</term>
<term>keyword2</term>
<term>keyword3</term>
<term>related_term1</term>
<term>related_term2</term>
</terms>`;ZOe=XOe});var Pie,YOe,Ogr=v(()=>{Dt();vb();Pie=class Pie{constructor(e){this.app=e}async batchCachedReadGrep(e,r){let{inclusions:n,exclusions:o}=id(),a=this.app.vault.getMarkdownFiles().filter(d=>ml(d,n,o)),s=new Set,u=Pie.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 g of l)if(m.includes(g)){s.add(p.path),h=!0;break}if(!h){let y=(await this.app.vault.cachedRead(p)).toLowerCase();for(let b of l)if(y.includes(b)){s.add(p.path);break}}}catch(m){J(`GrepScanner: Skipping file ${p.path}: ${m}`)}})),d%Pie.CONFIG.YIELD_INTERVAL===0&&await new Promise(p=>setTimeout(p,0))}let c=Array.from(s).slice(0,r);return c.length>0&&J(` 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}}};Pie.CONFIG={BATCH_SIZE:30,YIELD_INTERVAL:100};YOe=Pie});var Hao,QOe,Tgr=v(()=>{Dt();Hao={enabled:!0,minDocsForBoost:2,maxBoostFactor:1.15,minRelevanceRatio:.4},QOe=class{constructor(e){this.config=Hao;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&&(J(`Folder boost: Boosting ${r.length} folders with significant relevance`),r.slice(0,5).forEach(n=>{let o=(n.relevanceRatio*100).toFixed(1);J(` ${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 Vao,eTe,Egr=v(()=>{Dt();Vao={enabled:!0,maxCandidates:10,backlinkWeight:1,coCitationWeight:.5,sharedTagWeight:.3,boostStrength:.1,maxBoostMultiplier:1.2},eTe=class{constructor(e,r={}){this.metadataCache=e.metadataCache,this.config={...Vao,...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&&J(`GraphBoostCalculator: Boosted ${a.length} notes based on connections`),i}calculateConnections(e,r){let n=t
`))}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 Gao(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 su({content:[{type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}]}))}else e.push(new su({content:[{type:"tool_result",...r.content!=null?{content:Uot(r)}:{},tool_use_id:r.tool_call_id}]}));else e.push(r);return e}function Qgr(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*Zao(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){Zm(n)&&(yield oO(n,Vgr));let o="cache_control"in n?n.cache_control:void 0;if(n.type==="image_url"){let i;typeof n.image_url=="string"?i=Ygr(n.image_url):typeof n.image_url=="object"&&n.image_url!==null&&"url"in n.image_url&&typeof n.image_url.url=="string"&&(i=Ygr(n.image_url.url)),i&&(yield{type:"image",source:i,...o?{cache_control:o}:{}})}else{if(Hgr(n))return n;if(n.type==="document")yield{...n,...o?{cache_control:o}:{}};else if(Bgr(n))yield{type:"thinking",thinking:n.thinking,signature:n.signature,...o?{cache_control:o}:{}};else if(Ugr(n))yield{type:"redacted_thinking",data:n.data,...o?{cache_control:o}:{}};else if(zgr(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 Uot(t){let{content:e}=t;return typeof e=="string"?e:Array.from(Zao(e))}function oTe(t){let e=Gao(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(Us(i)&&i.response_metadata?.output_version==="v1")return{role:a,content:Zgr(i)};if(Us(i)&&i.tool_calls?.length){if(typeof i.content=="string")return i.content===""?{role:a,content:i.tool_calls.map(Qgr)}:{role:a,content:[{type:"text",text:i.content},...i.tool_calls.map(Qgr)]};{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:Uot(i)}}}else return{role:a,content:Uot(i)}});return{messages:Xao(o),system:r}}function Xao(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 zot=v(()=>{Jgr();Xgr();$s()});function eyr(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 Hot(t){let e;return t.status===400&&t.message.includes("tool")?e=iTe(t,"INVALID_TOOL_RESULTS"):t.status===401?e=iTe(t,"MODEL_AUTHENTICATION"):t.status===404?e=iTe(t,"MODEL_NOT_FOUND"):t.status===429?e=iTe(t,"MODEL_RATE_LIMIT"):e=t,e}var nyr=v(()=>{});function ir(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 ej=v(()=>{});var Vot,oyr=v(()=>{Vot=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return Vot=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 tj(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var Iie,dG=v(()=>{Iie=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 tn,_h,Sg,Lk,fG,pG,mG,hG,gG,yG,bG,_G,vG,KC=v(()=>{dG();tn=class extends Error{},_h=class t extends tn{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 Lk({message:n,cause:Iie(r)});let i=r;return e===400?new pG(e,i,n,o):e===401?new mG(e,i,n,o):e===403?new hG(e,i,n,o):e===404?new gG(e,i,n,o):e===409?new yG(e,i,n,o):e===422?new bG(e,i,n,o):e===429?new _G(e,i,n,o):e>=500?new vG(e,i,n,o):new t(e,i,n,o)}},Sg=class extends _h{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Lk=class extends _h{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},fG=class extends Lk{constructor({message:e}={}){super({message:e??"Request timed out."})}},pG=class extends _h{},mG=class extends _h{},hG=class extends _h{},gG=class extends _h{},yG=class extends _h{},bG=class extends _h{},_G=class extends _h{},vG=class extends _h{}});function Wot(t){return typeof t!="object"?{}:t??{}}function ayr(t){if(!t)return!0;for(let e in t)return!1;return!0}function syr(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var Qao,iyr,Jot,Kot,uyr,aTe,RH=v(()=>{KC();Qao=/^[a-z][a-z0-9+.-]*:/i,iyr=t=>Qao.test(t),Jot=t=>(Jot=Array.isArray,Jot(t)),Kot=Jot;uyr=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new tn(`${t} must be an integer`);if(e<0)throw new tn(`${t} must be a positive integer`);return e},aTe=t=>{try{return JSON.parse(t)}catch{return}}});var lyr,cyr=v(()=>{lyr=t=>new Promise(e=>setTimeout(e,t))});var Fk,Got=v(()=>{Fk="0.65.0"});function eso(){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 rso(){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+
`):[]}};ew=new WeakMap,tw=new WeakMap;rj.NEWLINE_CHARS=new Set([`
`,"\r"]);rj.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function Die(){}function uTe(t,e,r){return!e||lTe[t]>lTe[r]?Die:e[t].bind(e)}function vh(t){let e=t.logger,r=t.logLevel??"off";if(!e)return aso;let n=xyr.get(e);if(n&&n[0]===r)return n[1];let o={error:uTe("error",e,r),warn:uTe("warn",e,r),info:uTe("info",e,r),debug:uTe("debug",e,r)};return xyr.set(e,[r,o]),o}var lTe,tit,aso,xyr,nj,cTe=v(()=>{RH();lTe={off:0,error:200,warn:300,info:400,debug:500},tit=(t,e,r)=>{if(t){if(syr(lTe,t))return t;vh(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(lTe))}`)}};aso={error:Die,warn:Die,info:Die,debug:Die},xyr=new WeakMap;nj=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*sso(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new tn("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 tn("Attempted to iterate over a response with no body");let r=new rit,n=new rj,o=Nie(t.body);for await(let i of uso(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*uso(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"?jie(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let i;for(;(i=Cyr(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function lso(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var $ie,RA,rit,nit=v(()=>{ej();KC();wG();eit();wG();dG();RH();Qot();cTe();KC();RA=class t{constructor(e,r,n){this.iterator=e,$ie.set(this,void 0),this.controller=r,ir(this,$ie,n,"f")}static fromSSEResponse(e,r,n){let o=!1,i=n?vh(n):console;async function*a(){if(o)throw new tn("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let s=!1;try{for await(let u of sso(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,aTe(u.data)??u.data,void 0,e.headers)}s=!0}catch(u){if(tj(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 rj,u=Nie(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 tn("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(tj(u))return;throw u}finally{s||r.abort()}}return new t(a,r,n)}[($ie=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,$ie,"f")),new t(()=>o(r),this.controller,Me(this,$ie,"f"))]}toReadableStream(){let e=this,r;return Xot({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=jie(JSON.stringify(o)+`
`);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};rit=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]=lso(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function dTe(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):RA.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 oit(d,r)}return await r.text()})();return vh(t).debug(`[${n}] response parsed`,nj({retryOfRequestLogID:o,url:r.url,status:r.status,body:a,durationMs:Date.now()-i})),a}function oit(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 iit=v(()=>{nit();cTe()});var Lie,AH,fTe=v(()=>{ej();iit();AH=class t extends Promise{constructor(e,r,n=dTe){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,Lie.set(this,void 0),ir(this,Lie,e,"f")}_thenUnwrap(e){return new t(Me(this,Lie,"f"),this.responsePromise,async(r,n)=>oit(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,Lie,"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)}};Lie=new WeakMap});var pTe,ait,Fie,DS,kk=v(()=>{ej();KC();iit();fTe();RH();ait=class{constructor(e,r,n,o){pTe.set(this,void 0),ir(this,pTe,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 tn("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await Me(this,pTe,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(pTe=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},Fie=class extends AH{constructor(e,r,n){super(e,r,async(o,i)=>new n(o,i.response,await dTe(o,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},DS=class extends ait{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:{...Wot(this.options.query),before_id:r}}:null}let e=this.last_id;return e?{...this.options,query:{...Wot(this.options.query),after_id:e}}:null}}});function IH(t,e,r){return uit(),new File(t,e??"unknown_file",r)}function kie(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 dso(t){let e=typeof t=="function"?t:t.fetch,r=Oyr.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 Oyr.set(e,n),n}var uit,lit,Tyr,Oyr,fso,pso,sit,mTe=v(()=>{wG();uit=()=>{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},xy=_so(Iyr)});var CG,fit=v(()=>{AA();kk();IA();mTe();SG();CG=class extends Cd{list(e={},r){let{betas:n,...o}=e??{};return this._client.getAPIList("/v1/files",DS,{query:o,...r,headers:Zi([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},r?.headers])})}delete(e,r={},n){let{betas:o}=r??{};return this._client.delete(xy`/v1/files/${e}`,{...n,headers:Zi([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString()},n?.headers])})}download(e,r={},n){let{betas:o}=r??{};return this._client.get(xy`/v1/files/${e}/content`,{...n,headers:Zi([{"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(xy`/v1/files/${e}`,{...n,headers:Zi([{"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",Tyr({body:o,...r,headers:Zi([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},r?.headers])},this._client))}}});var xG,pit=v(()=>{AA();kk();IA();SG();xG=class extends Cd{retrieve(e,r={},n){let{betas:o}=r??{};return this._client.get(xy`/v1/models/${e}?beta=true`,{...n,headers:Zi([{...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",DS,{query:o,...r,headers:Zi([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers])})}}});var OG,mit=v(()=>{KC();wG();eit();OG=class t{constructor(e,r){this.iterator=e,this.controller=r}async*decoder(){let e=new rj;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 tn("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 tn("Attempted to iterate over a response with no body");return new t(Nie(e.body),r)}}});var qie=v(()=>{KC()});var TG,hit=v(()=>{AA();kk();IA();mit();qie();SG();TG=class extends Cd{create(e,r){let{betas:n,...o}=e;return this._client.post("/v1/messages/batches?beta=true",{body:o,...r,headers:Zi([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}retrieve(e,r={},n){let{betas:o}=r??{};return this._client.get(xy`/v1/messages/batches/${e}?beta=true`,{...n,headers:Zi([{"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",DS,{query:o,...r,headers:Zi([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}delete(e,r={},n){let{betas:o}=r??{};return this._client.delete(xy`/v1/messages/batches/${e}?beta=true`,{...n,headers:Zi([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString()},n?.headers])})}cancel(e,r={},n){let{betas:o}=r??{};return this._client.post(xy`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:Zi([{"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 tn(`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:Zi([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((a,s)=>OG.fromResponse(s.response,s.controller))}}});var git=v(()=>{nit()});var Cso,EG,xso,Oso,gTe,yit=v(()=>{Cso=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=OTe[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:Zi([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers]),stream:e.stream??!1})}stream(e,r){return xTe.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:Zi([{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString()},r?.headers])})}toolRunner(e,r){return new RG(this._client,e,r)}};Uk.Batches=TG;Uk.BetaToolRunner=RG});var jA,Tit=v(()=>{AA();fit();fit();pit();pit();Oit();Oit();jA=class extends Cd{constructor(){super(...arguments),this.models=new xG(this._client),this.messages=new Uk(this._client),this.files=new CG(this._client)}};jA.Models=xG;jA.Messages=Uk;jA.Files=CG});var jH,Eit=v(()=>{AA();IA();jH=class extends Cd{create(e,r){let{betas:n,...o}=e;return this._client.post("/v1/complete",{body:o,timeout:this._client._options.timeout??6e5,...r,headers:Zi([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers]),stream:e.stream??!1})}}});function zyr(t){return t.type==="tool_use"||t.type==="server_tool_use"}var LS,zk,Wie,ETe,Gie,Zie,PTe,Xie,aj,Yie,MTe,RTe,AG,ATe,ITe,Pit,qyr,Mit,Rit,Ait,Iit,Byr,Uyr,NTe,Hyr=v(()=>{ej();dG();qie();git();yit();Uyr="__json_buf";NTe=class t{constructor(){LS.add(this),this.messages=[],this.receivedMessages=[],zk.set(this,void 0),this.controller=new AbortController,Wie.set(this,void 0),ETe.set(this,()=>{}),Gie.set(this,()=>{}),Zie.set(this,void 0),PTe.set(this,()=>{}),Xie.set(this,()=>{}),aj.set(this,{}),Yie.set(this,!1),MTe.set(this,!1),RTe.set(this,!1),AG.set(this,!1),ATe.set(this,void 0),ITe.set(this,void 0),Mit.set(this,e=>{if(ir(this,MTe,!0,"f"),tj(e)&&(e=new Sg),e instanceof Sg)return ir(this,RTe,!0,"f"),this._emit("abort",e);if(e instanceof tn)return this._emit("error",e);if(e instanceof Error){let r=new tn(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new tn(String(e)))}),ir(this,Wie,new Promise((e,r)=>{ir(this,ETe,e,"f"),ir(this,Gie,r,"f")}),"f"),ir(this,Zie,new Promise((e,r)=>{ir(this,PTe,e,"f"),ir(this,Xie,r,"f")}),"f"),Me(this,Wie,"f").catch(()=>{}),Me(this,Zie,"f").catch(()=>{})}get response(){return Me(this,ATe,"f")}get request_id(){return Me(this,ITe,"f")}async withResponse(){let e=await Me(this,Wie,"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,Mit,"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,LS,"m",Rit).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,LS,"m",Ait).call(this,u);if(s.controller.signal?.aborted)throw new Sg;Me(this,LS,"m",Iit).call(this)}finally{o&&i&&o.removeEventListener("abort",i)}}_connected(e){this.ended||(ir(this,ATe,e,"f"),ir(this,ITe,e?.headers.get("request-id"),"f"),Me(this,ETe,"f").call(this,e),this._emit("connect"))}get ended(){return Me(this,Yie,"f")}get errored(){return Me(this,MTe,"f")}get aborted(){return Me(this,RTe,"f")}abort(){this.controller.abort()}on(e,r){return(Me(this,aj,"f")[e]||(Me(this,aj,"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=OTe[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 NTe.createMessage(this,e,r)}countTokens(e,r){return this._client.post("/v1/messages/count_tokens",{body:e,...r})}},Vyr={"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"};Hk.Batches=IG});var DH,Dit=v(()=>{AA();kk();IA();SG();DH=class extends Cd{retrieve(e,r={},n){let{betas:o}=r??{};return this._client.get(xy`/v1/models/${e}`,{...n,headers:Zi([{...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",DS,{query:o,...r,headers:Zi([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers])})}}});var Jyr=v(()=>{Myr();Tit();Eit();jit();Dit()});var Qie,Kyr=v(()=>{Qie=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 $it,Lit,jTe,Wyr,Gyr,Zyr,pc,DA,Fit=v(()=>{ej();oyr();RH();cyr();dG();Zot();wG();_yr();Got();KC();kk();dit();Jyr();fTe();Eit();Dit();Tit();jit();Zot();IA();Kyr();cTe();RH();Gyr="\\n\\nHuman:",Zyr="\\n\\nAssistant:",pc=class{constructor({baseURL:e=Qie("ANTHROPIC_BASE_URL"),apiKey:r=Qie("ANTHROPIC_API_KEY")??null,authToken:n=Qie("ANTHROPIC_AUTH_TOKEN")??null,...o}={}){$it.add(this),jTe.set(this,void 0);let i={apiKey:r,authToken:n,...o,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&myr())throw new tn(`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??Lit.DEFAULT_TIMEOUT,this.logger=i.logger??console;let a="warn";this.logLevel=a,this.logLevel=tit(i.logLevel,"ClientOptions.logLevel",this)??tit(Qie("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??gyr(),ir(this,jTe,byr,"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 Zi([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return Zi([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return Zi([{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 tn(`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 ${Fk}`}defaultIdempotencyKey(){return`stainless-node-retry-${Vot()}`}makeStatusError(e,r,n,o){return _h.generate(e,r,n,o)}buildURL(e,r,n){let o=!Me(this,$it,"m",Wyr).call(this)&&n||this.baseURL,i=iyr(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return ayr(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 tn("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 AH(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`,nj({retryOfRequestLogID:n,method:o.method,url:s,options:o,headers:a.headers})),o.signal?.aborted)throw new Sg;let f=new AbortController,p=await this.fetchWithTimeout(s,a,u,f).catch(Iie),m=Date.now();if(p instanceof globalThis.Error){let y=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new Sg;let b=tj(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"} - ${y}`),vh(this).debug(`[${l}] connection ${b?"timed out":"failed"} (${y})`,nj({retryOfRequestLogID:n,url:s,durationMs:m-d,messag
`);o.enqueue(s)}catch(i){o.error(i)}},async cancel(){await r.return?.()}})}},Git=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]=Vso(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},DG=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 Cg(`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 Cg(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new Cg("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}};DG.NEWLINE_CHARS=new Set([`
`,"\r","\v","\f","","","","\x85","\u2028","\u2029"]);DG.NEWLINE_REGEXP=/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g});async function Yit(t,e,r){if(t=await t,hbr(t))return t;if(mbr(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=cae(o)?[await o.arrayBuffer()]:[o];return new DTe(i,e,r)}let n=await Kso(t);if(e||(e=Gso(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new DTe(n,e,r)}async function Kso(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(cae(t))e.push(await t.arrayBuffer());else if(Zso(t))for await(let r of t)e.push(r);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${Wso(t)}`);return e}function Wso(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function Gso(t){return Zit(t.name)||Zit(t.filename)||Zit(t.path)?.split(/[\\/]/).pop()}var mbr,hbr,cae,Jso,Zit,Zso,Qit,kH,gbr,Xit,qTe=v(()=>{eae();eae();mbr=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",hbr=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&cae(t),cae=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",Jso=t=>hbr(t)||mbr(t)||Jit(t);Zit=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},Zso=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Qit=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody",kH=async t=>{let e=await gbr(t.body);return Hit(e,t)},gbr=async t=>{let e=new Uit;return await Promise.all(Object.entries(t||{}).map(([r,n])=>Xit(e,r,n))),e},Xit=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(Jso(r)){let n=await Yit(r);t.append(e,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>Xit(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>Xit(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 Sbr(t){let{response:e}=t;if(t.options.stream)return $G("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):kTe.fromSSEResponse(e,t.controller);if(e.status===204)return null;if(t.options.__binaryResponse)return e;let n=e.headers.get("content-type")?.split(";")[0]?.trim();if(n?.includes("application/json")||n?.endsWith("+json")){let a=await e.json();return $G("response",e.status,e.url,e.headers,a),a}let i=await e.text();return $G("response",e.status,e.url,e.headers,i),i}function ruo(){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 uuo(t){if(!t)return!0;for(let e in t)return!1;return!0}function luo(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function wbr(t,e){for(let r in e){if(!luo(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 $G(t,...e){typeof process<"u"&&process?.env?.DEBUG==="true"&&console.log(`Groq:DEBUG:${t}`,...e)}var Yso,Qso,BTe,zTe,HTe,ybr,tat,euo,tuo,bbr,_br,vbr,nuo,ouo,i
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 BH(this),this.chat=new Jk(this),this.embeddings=new UH(this),this.audio=new $A(this),this.models=new HH(this),this.batches=new qH(this),this.files=new zH(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}`}}};Tbr=du;du.Groq=Tbr;du.DEFAULT_TIMEOUT=6e4;du.GroqError=Cg;du.APIError=wh;du.APIConnectionError=Vk;du.APIConnectionTimeoutError=NG;du.APIUserAbortError=FH;du.NotFoundError=oae;du.ConflictError=iae;du.RateLimitError=sae;du.BadRequestError=tae;du.AuthenticationError=rae;du.InternalServerError=uae;du.PermissionDeniedError=nae;du.UnprocessableEntityError=aae;du.toFile=Yit;du.fileFromPath=$Te;du.Completions=BH;du.Chat=Jk;du.Embeddings=UH;du.Audio=$A;du.Models=HH;du.Batches=qH;du.Files=zH;Ebr=du});function vuo(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 Rbr(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(!cd.isInstance(t))throw new Error("Invalid generic chat message");return vuo(t);default:throw new Error(`Unknown message type: ${t.type}`)}}function Mbr(t){return t.map(e=>{let r={role:Rbr(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 Us(e)&&e.tool_calls?.length?r.tool_calls=e.tool_calls.map(Sk):(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 wuo(t,e,r){let n=t.tool_calls;switch(t.role){case"assistant":{let o=[],i=[];for(let a of n??[])try{o.push(LC(a,{returnId:!0}))}catch(s){i.push(FC(a,s.message))}return new li({content:t.content||"",additional_kwargs:{tool_calls:n},tool_calls:o,invalid_tool_calls:i,usage_metadata:e,response_metadata:r})}default:return new cd(t.content||"",t.role??"unknown")}}function Suo(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 _v({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 Ur({content:i,tool_call_chunks:f,additional_kwargs:a,id:u,response_metadata:d})}else return o==="system"?new Ky({content:i,response_metadata:d}):o==="developer"?new Ky({content:i,response_metadata:d,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new bv({content:i,additional_kwargs:a,name:t.name,response_metadata:d}):o==="tool"?new Aw({content:i,additional_kwargs:a,tool_call_id:t.tool_call_id,response_metadata:d}):new yv({content:i,role:o,response_metadata:d})}function Cuo(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 yuo,buo,_uo,mat,Abr=v(()=>{o_();D1();$s();ym();nl();Gv();Pbr();xv();_O();sH();j1();yuo=["frequency_penalty","function_call","functions","logit_bias","logprobs","max_completion_tokens","max_tokens","n","parallel_tool_calls","presence_penalty","reasoning_format"
${Xat(this.cause)}`:this.toString()}};ZC.SDKValidationError=Zat;function Xat(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(`${Xat(c,e+1)}`)})}}}return t.issues.length&&o("\u2514\u2500*"),n.slice(1)}});var Qat=S(UA=>{"use strict";var rdo=UA&&UA.__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=UA&&UA.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),odo=UA&&UA.__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"&&rdo(r,e,n[o]);return ndo(r,e),r}}();Object.defineProperty(UA,"__esModule",{value:!0});UA.ResponseValidationError=void 0;var ido=odo(te()),ado=pEe(),sdo=mEe(),Yat=class extends ado.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 ido.ZodError?`${this.rawMessage}
${(0,sdo.formatZodError)(this.cause)}`:this.toString()}};UA.ResponseValidationError=Yat});var tst=S(hEe=>{"use strict";Object.defineProperty(hEe,"__esModule",{value:!0});hEe.SDKError=void 0;var udo=pEe(),est=class extends udo.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"}};hEe.SDKError=est});var ar=S(Lm=>{"use strict";Object.defineProperty(Lm,"__esModule",{value:!0});Lm.jsonErr=ddo;Lm.json=fdo;Lm.jsonl=pdo;Lm.jsonlErr=mdo;Lm.textErr=hdo;Lm.text=gdo;Lm.bytesErr=ydo;Lm.bytes=bdo;Lm.streamErr=_do;Lm.stream=vdo;Lm.sseErr=wdo;Lm.sse=Sdo;Lm.nilErr=Cdo;Lm.nil=xdo;Lm.fail=Odo;Lm.match=Tdo;Lm.unpackHeaders=gEe;var ldo=Qat(),A_r=tst(),I_r=xd(),N_r=UG(),j_r=Uat(),cdo={jsonl:"application/jsonl",json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function ddo(t,e,r){return{...r,err:!0,enc:"json",codes:t,schema:e}}function fdo(t,e,r){return{...r,enc:"json",codes:t,schema:e}}function pdo(t,e,r){return{...r,enc:"jsonl",codes:t,schema:e}}function mdo(t,e,r){return{...r,err:!0,enc:"jsonl",codes:t,schema:e}}function hdo(t,e,r){return{...r,err:!0,enc:"text",codes:t,schema:e}}function gdo(t,e,r){return{...r,enc:"text",codes:t,schema:e}}function ydo(t,e,r){return{...r,err:!0,enc:"bytes",codes:t,schema:e}}function bdo(t,e,r){return{...r,enc:"bytes",codes:t,schema:e}}function _do(t,e,r){return{...r,err:!0,enc:"stream",codes:t,schema:e}}function vdo(t,e,r){return{...r,enc:"stream",codes:t,schema:e}}function wdo(t,e,r){return{...r,err:!0,enc:"sse",codes:t,schema:e}}function Sdo(t,e,r){return{...r,enc:"sse",codes:t,schema:e}}function Cdo(t,e,r){return{...r,err:!0,enc:"nil",codes:t,schema:e}}function xdo(t,e,r){return{...r,enc:"nil",codes:t,schema:e}}function Odo(t){return{enc:"fail",codes:t}}function Tdo(...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:cdo[d.enc];if(p&&(0,N_r.matchResponse)(r,f,p)){a=d;break}else if(!p&&(0,N_r.matchStatusCode)(r,f)){a=d;break}}if(!a)return[{ok:!1,error:new A_r.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 A_r.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:gEe(r.headers)}:null,...(0,j_r.isPlainObject)(i)?i:null,request$:n,response$:r,body$:u}:l?c={...o?.extraFields,...a.hdrs?{Headers:gEe(r.headers)}:null,[l]:i}:a.hdrs?c={...o?.extraFields,...a.hdrs?{Headers:gEe(r.headers)}:null,...(0,j_r.isPlainObject)(i)?i:null}:c=i,"err"in a){let d=D_r(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[D_r(c,d=>a.schema.parse(d),"Response validation failed",{request:n,response:r,body:u}),i]}}var Edo=/, */;function gEe(t){let e={};for(let[r,n]of t.entries())e[r]=n.split(Edo);return e}function D_r(t,e,r,n){try{return(0,I_r.OK)(e(t))}catch(o){return(0,I_r.ERR)(new ldo.ResponseValidationError(r,{cause:o,rawValue:t,rawMessage:r,...n}))}}});var ae=S(tq=>{"use strict";Object.defineProperty(tq,"__esModule",{value:!0});tq.invariant=Pdo;tq.remap=Mdo;tq.combineSignals=Rdo;tq.abortSignalAny=$_r;tq.compactMap=Ado;tq.allRequired=Ido;var rst=class extends Error{constructor(e){super(e),this.name="InvariantError"}};function Pdo(t,e){if(!t)throw new rst(e)}function Mdo(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 Rdo(...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):$_r(e)}}function $_r(t){let e=new AbortController,r=e.signal;i
`)),e(i)}});var wIr=S(wj=>{"use strict";var lNo=wj&&wj.__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]}),cNo=wj&&wj.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),gRe=wj&&wj.__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"&&lNo(r,e,n[o]);return cNo(r,e),r}}();Object.defineProperty(wj,"__esModule",{value:!0});wj.agentsStream=_No;var dNo=gRe(te()),fNo=fr(),pNo=Tq(),Bae=gRe(ar()),mNo=ae(),hNo=ee(),_Ir=sr(),gNo=or(),vIr=gRe($t()),yNo=gRe(Hn()),bNo=ur();function _No(t,e,r){return new bNo.APIPromise(vNo(t,e,r))}async function vNo(t,e,r){let n=(0,hNo.safeParse)(e,b=>vIr.AgentsCompletionStreamRequest$outboundSchema.parse(b),"Input validation failed");if(!n.ok)return[n,{status:"invalid"}];let o=n.value,i=(0,fNo.encodeJSON)("body",o,{explode:!0}),a=(0,gNo.pathToFunc)("/v1/agents/completions#stream")(),s=new Headers((0,mNo.compactMap)({"Content-Type":"application/json",Accept:"text/event-stream"})),u=await(0,_Ir.extractSecurity)(t._options.apiKey),l=u==null?{}:{apiKey:u},c=(0,_Ir.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,g={HttpMeta:{Response:h,Request:p}},[y]=await Bae.match(Bae.sse(200,dNo.instanceof(ReadableStream).transform(b=>new pNo.EventStream(b,_=>_.data==="[DONE]"?{done:!0}:{value:vIr.CompletionEvent$inboundSchema.parse(_)}))),Bae.jsonErr(422,yNo.HTTPValidationError$inboundSchema),Bae.fail("4XX"),Bae.fail("5XX"))(h,p,{extraFields:g});return y.ok?[y,{status:"complete",request:p,response:h}]:[y,{status:"complete",request:p,response:h}]}});var CIr=S(yRe=>{"use strict";Object.defineProperty(yRe,"__esModule",{value:!0});yRe.Agents=void 0;var wNo=bIr(),SNo=wIr(),CNo=jc(),SIr=xd(),Eut=class extends CNo.ClientSDK{async complete(e,r){return(0,SIr.unwrapAsync)((0,wNo.agentsComplete)(this,e,r))}async stream(e,r){return(0,SIr.unwrapAsync)((0,SNo.agentsStream)(this,e,r))}};yRe.Agents=Eut});var Uae=S(Put=>{"use strict";Object.defineProperty(Put,"__esModule",{value:!0});Put.isReadableStream=xNo;function xNo(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 EIr=S(Sj=>{"use strict";var ONo=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]}),TNo=Sj&&Sj.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),TIr=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
]))`;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 rIe=S(tIe=>{"use strict";Object.defineProperty(tIe,"__esModule",{value:!0});tIe.parseRecordDef=void 0;var Pse=te(),vLr=am(),EVo=eIe(),PVo=JAe();function MVo(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===Pse.ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:(0,vLr.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:(0,vLr.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===Pse.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=(0,EVo.parseStringDef)(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===Pse.ZodFirstPartyTypeKind.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===Pse.ZodFirstPartyTypeKind.ZodBranded&&t.keyType._def.type._def.typeName===Pse.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=(0,PVo.parseBrandedDef)(t.keyType._def,e);return{...r,propertyNames:o}}}return r}tIe.parseRecordDef=MVo});var plt=S(nIe=>{"use strict";Object.defineProperty(nIe,"__esModule",{value:!0});nIe.parseMapDef=void 0;var wLr=am(),RVo=rIe();function AVo(t,e){if(e.mapStrategy==="record")return(0,RVo.parseRecordDef)(t,e);let r=(0,wLr.parseDef)(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=(0,wLr.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}}}nIe.parseMapDef=AVo});var mlt=S(oIe=>{"use strict";Object.defineProperty(oIe,"__esModule",{value:!0});oIe.parseNativeEnumDef=void 0;function IVo(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}}oIe.parseNativeEnumDef=IVo});var hlt=S(iIe=>{"use strict";Object.defineProperty(iIe,"__esModule",{value:!0});iIe.parseNeverDef=void 0;function NVo(){return{not:{}}}iIe.parseNeverDef=NVo});var glt=S(aIe=>{"use strict";Object.defineProperty(aIe,"__esModule",{value:!0});aIe.parseNullDef=void 0;function jVo(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}aIe.parseNullDef=jVo});var sIe=S(Rq=>{"use strict";Object.defineProperty(Rq,"__esModule",{value:!0});Rq.parseUnionDef=Rq.primitiveMappings=void 0;var DVo=am();Rq.primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function $Vo(t,e){if(e.target==="openApi3")return SLr(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Rq.primitiveMappings&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=Rq.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(
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(Us(i)&&i.tool_calls?.length)return i.tool_calls.map(a=>({...a,id:dae(a.id??"")})).map(Sk)},o=new Set;for(let i of t)"tool_call_id"in i&&typeof i.tool_call_id=="string"&&o.add(dae(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:dae(i.tool_call_id)}];if(Us(i)){if(a===void 0)return[{role:e(i.getType()),content:s}];{let u=a.filter(l=>o.has(dae(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 P8o(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=hat(r.content);switch(r.role){case"assistant":{let i=[],a=[];for(let s of n)try{let u=LC(s,{returnId:!0});i.push({...u,id:u.id??WTe().replace(/-/g,"")})}catch(u){a.push(FC(s,u.message))}return new li({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 su({content:o})}}function M8o(t,e){if(!t.content&&!t.toolCalls)return e?new Ur({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??WTe().replace(/-/g,""),type:"function"})):void 0,n="assistant";t.role&&(n=t.role);let o=hat(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 _v({content:o}):n==="assistant"?new Ur({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 Aw({content:o,additional_kwargs:i,tool_call_id:r?.[0].id??""}):n==="function"?new bv({content:o,additional_kwargs:i}):new yv({content:o,role:n})}function lkr(t){if(!(!t||!t.length))return t.map(e=>{if("function"in e)return{type:e.type??"function",function:e.function};if(mg(e)){let r=e.description??`Tool: ${e.name}`;return{type:"function",function:{name:e.name,description:r,parameters:Ga(e.schema)?Vi(e.schema):e.schema}}}throw new Error(`Unknown tool type passed to ChatMistral: ${JSON.stringify(e,null,2)}`)})}var ckr,dkr,lct,fkr=v(()=>{Nbr();kbr();ckr=L(ukr(),1),dkr=L(UG(),1);$s();D1();ym();iz();nl();_O();sH();xv();o_();j1();Gv();lct=class extends hh{constructor(e){super(e??{});M(this,"lc_namespace",["langchain","chat_models","mistralai"]);M(this,"model","mistral-small-latest");M(this,"apiKey");M(this,"endpoint");M(this,"serverURL");M(this,"temperature",.7);M(this,"streaming",!1);M(this,"topP",1);M(this,"maxTokens");M(this,"safeMode",!1);M(this,"safePrompt",!1);M(this,"randomSeed");M(this,"seed");M(this,"maxRetries");M(this,"lc_serializable",!0);M(this,"streamUsage",!0);M(this,"beforeRequestHooks");M(this,"requestErrorHooks");M(this,"responseHooks");M(this,"httpClient");M(this,"presencePenalty");M(this,"frequencyPenalty");M(this,"numCompletions");let r=e?.apiKey??gn("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=
`):[]}};cw=new WeakMap;$V.NEWLINE_CHARS=new Set([`
`,"\r"]);$V.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function xct(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 $kr=v(()=>{});async function*V8o(t,e){if(!t.body)throw e.abort(),new Ar("Attempted to iterate over a response with no body");let r=new Oct,n=new $V,o=xct(t.body);for await(let i of J8o(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*J8o(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=jkr(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function K8o(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var uI,Oct,oNe=v(()=>{Use();lw();Dkr();$kr();Bi();lw();uI=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 V8o(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 qm(void 0,s.error,void 0,Tct(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 qm(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 $V,s=xct(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 bct({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?.()}})}};Oct=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]=K8o(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function Mct(t,e,r){if(t=await t,Fkr(t))return t;if(Lkr(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=Xse(o)?[await o.arrayBuffer()]:[o];return new QIe(i,e,r)}let n=await G8o(t);if(e||(e=X8o(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new QIe(n,e,r)}async function G8o(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Xse(t))e.push(await t.arrayBuffer());else if(Y8o(t))for await(let r of t)e.push(r);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${Z8o(t)}`);return e}function Z8o(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function X8o(t){return Ect(t.name)||Ect(t.filename)||Ect(t.path)?.split(/[\\/]/).pop()}var Lkr,Fkr,Xse,W8o,Ect,Y8o,Rct,a0,kkr,Pct,iNe=v(()=>{Use();Use();Lkr=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",Fkr=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Xse(t),Xse=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",W8o=t=>Fkr(t)||Lkr(t)||wct(t);Ect=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},Y8o=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Rct=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody",a0=async t=>{let e=await kkr(t.body);return _ct(e,t)},kkr=async t=>{let e=new yct;return await Promise.all(Object.entries(t||{}).map(([r,n])=>Pct(e,r,n))),e},Pct=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(W8o(r)){let n=await Mct(r);t.append(e,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>Pct(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>Pct(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 Vkr(t){let{response:e}=t;if(t.options.stream)return jD("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):uI.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 jD("response",e.status,e.url,e.headers,a),Jkr(a,e)}let i=await e.text();return jD("response",e.status,e.url,e.headers,i),i}function Jkr(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 oGo(){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 Kkr(t){if(!t)return!0;for(let e in t)return!1;return!0}function Wkr(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function zkr(t,e){fo
\r `.includes(t[n]);)n++};return a()},tdt=t=>_Go(t,Eh.ALL^Eh.NUM)});function wGo(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 Ar(`missing finish_reason for choice ${d}`);let{content:m=null,function_call:h,tool_calls:g,...y}=l,b=l.role;if(!b)throw new Ar(`missing role for choice ${d}`);if(h){let{arguments:_,name:w}=h;if(_==null)throw new Ar(`missing function_call.arguments for choice ${d}`);if(!w)throw new Ar(`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 g?{...p,index:d,finish_reason:c,logprobs:f,message:{...y,role:b,content:m,refusal:l.refusal??null,tool_calls:g.map((_,w)=>{let{function:x,type:O,id:E,...T}=_,{arguments:R,name:N,...D}=x||{};if(E==null)throw new Ar(`missing choices[${d}].tool_calls[${w}].id
${vNe(t)}`);if(O==null)throw new Ar(`missing choices[${d}].tool_calls[${w}].type
${vNe(t)}`);if(N==null)throw new Ar(`missing choices[${d}].tool_calls[${w}].function.name
${vNe(t)}`);if(R==null)throw new Ar(`missing choices[${d}].tool_calls[${w}].function.arguments
${vNe(t)}`);return{...T,id:E,type:O,function:{...D,name:N,arguments:R}}})}}:{...p,message:{...y,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 tqr(u,e)}function vNe(t){return JSON.stringify(t)}var J9,gu,Bm,FD,K9,qq,rdt,bNe,ndt,odt,idt,_Ne,adt,uqr,W9,sdt=v(()=>{lw();Yct();oNe();uue();sqr();J9=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},gu=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)},W9=class t extends V9{constructor(e){super(),Bm.add(this),FD.set(this,void 0),K9.set(this,void 0),qq.set(this,void 0),J9(this,FD,e,"f"),J9(this,K9,[],"f")}get currentChatCompletionSnapshot(){return gu(this,qq,"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())),gu(this,Bm,"m",rdt).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)gu(this,Bm,"m",ndt).call(this,a);if(i.controller.signal?.aborted)throw new sm;return this._addChatCompletion(gu(this,Bm,"m",_Ne).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),gu(this,Bm,"m",rdt).call(this),this._connected();let o=uI.fromReadableStream(e,this.controller),i;for await(let a of o)i&&i!==a.id&&this._addChatCompletion(gu(this,Bm,"m",_Ne).call(this)),gu(this,Bm,"m",ndt).call(this,a),i=a.id;if(o.controller.signal?.aborted)throw new sm;return this._addChatCompletion(gu(this,Bm,"m",_Ne).call(this))}[(FD=new WeakMap,K9=new WeakMap,qq=new WeakMap,Bm=new WeakSet,rdt=function(){this.ended||J9(this,qq,void 0,"f")},bNe=function(r){let n=gu(this,K9,"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},gu(this,K9,"f")[r.index]=n,n)},ndt=function(r){if(this.ended)return;let n=gu(this,Bm,"m",uqr).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=gu(this,Bm,"m",bNe).call(this,i);i.finish_reason&&(gu(this,Bm,"m",idt).call(this,i),a.current_tool_call_index!=null&&gu(this,Bm,"m",odt).call(this,i,a.current_tool_call_index));for(let s of o.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(gu(this,Bm,"m",idt).call(this,i),a.current_tool_call_index!=null&&gu(this,Bm,"m",odt).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 HV(this),this.chat=new $D(this),this.embeddings=new VV(this),this.files=new Uq(this),this.images=new XV(this),this.audio=new cI(this),this.moderations=new QV(this),this.models=new Hq(this),this.fineTuning=new dx(this),this.vectorStores=new pw(this),this.beta=new cx(this),this.batches=new Lq(this),this.uploads=new Wq(this),this.responses=new Kq(this),this.evals=new mI(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 hct(e,{arrayFormat:"brackets"})}};Pqr=No;No.OpenAI=Pqr;No.DEFAULT_TIMEOUT=6e5;No.OpenAIError=Ar;No.APIError=qm;No.APIConnectionError=Iq;No.APIConnectionTimeoutError=Nq;No.APIUserAbortError=sm;No.NotFoundError=Jse;No.ConflictError=Kse;No.RateLimitError=Gse;No.BadRequestError=zse;No.AuthenticationError=Hse;No.InternalServerError=Zse;No.PermissionDeniedError=Vse;No.UnprocessableEntityError=Wse;No.toFile=Mct;No.fileFromPath=eNe;No.Completions=HV;No.Chat=$D;No.ChatCompletionsPage=$q;No.Embeddings=VV;No.Files=Uq;No.FileObjectsPage=WV;No.Images=XV;No.Audio=cI;No.Moderations=QV;No.Models=Hq;No.ModelsPage=YV;No.FineTuning=dx;No.VectorStores=pw;No.VectorStoresPage=eJ;No.VectorStoreSearchResponsesPage=tJ;No.Beta=cx;No.Batches=Lq;No.BatchesPage=LV;No.Uploads=Wq;No.Responses=Kq;No.Evals=mI;No.EvalListResponsesPage=KV;Mqr=No});var ANe,Aqr=v(()=>{$s();ym();cH();Rqr();Dt();ANe=class extends OA{constructor(e){let{enableReasoning:r=!1,reasoningEffort:n,...o}=e;super(o),this.enableReasoning=r,this.reasoningEffort=n,this.openaiClient=new Mqr({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 J(`OpenRouter reasoning enabled with effort: ${n}`),{...r,reasoning:{effort:n}}}else return J("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 Hi({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){Ot(`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){Ot(`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.text,e.outputText,e.completion,e.resultText,e.delta];for(let o of r)if(typeof o=="string"&&o.length>0)return o;let n=[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 o of n){let i=this.extractTextFromCandidate(o);if(i)return i}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 Ur({content:"",response_metadata:o,usage_metadata:n});return new Hi({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)??this.coerceNumber(e.output_tokens)??this.coerceNumber(e.outputTokenCount)??this.coerceNumber(e.completionTokens)??this.coerceNumber(e.completion_tokens)??0,o=this.coerceNumber(e.totalTokens)??this.coerceNumb
`)),i!==void 0&&(u.max_tokens=i),a!==void 0&&(u.temperature=a),s!==void 0&&(u.top_p=s),this.anthropicVersion&&(u.anthropic_version=this.anthropicVersion),u}normaliseMessageContent(e){let{content:r}=e;return typeof r=="string"?r:Array.isArray(r)?r.map(n=>{if(typeof n=="string")return n;if(typeof n=="object"&&n!==null){if("text"in n&&typeof n.text=="string")return n.text;if("content"in n&&typeof n.content=="string")return n.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:""}}});var Nqr={};Xn(Nqr,{default:()=>gI});var NNe,WGo,Ph,gI,hue=v(()=>{Tu();zr();zz();Dt();Pt();wr();Fgr();rbr();zYe();obr();rQe();Ibr();hkr();yQe();cH();ykr();NNe=require("obsidian");Aqr();Iqr();WGo={openai:OA,"azure openai":OA,anthropic:kit,cohereai:qYe,google:eQe,xai:cct,openrouterai:ANe,ollama:hQe,"lm-studio":OA,groq:mat,"3rd party (openai-format)":OA,"copilot-plus":OA,mistralai:lct,deepseek:qit,"amazon-bedrock":INe},Ph=class Ph{constructor(){this.providerApiKeyMap={openai:()=>ce().openAIApiKey,google:()=>ce().googleApiKey,"azure openai":()=>ce().azureOpenAIApiKey,anthropic:()=>ce().anthropicApiKey,cohereai:()=>ce().cohereApiKey,openrouterai:()=>ce().openRouterAiApiKey,groq:()=>ce().groqApiKey,xai:()=>ce().xaiApiKey,ollama:()=>"default-key","lm-studio":()=>"default-key","3rd party (openai-format)":()=>"default-key","copilot-plus":()=>ce().plusLicenseKey,mistralai:()=>ce().mistralApiKey,deepseek:()=>ce().deepseekApiKey,"amazon-bedrock":()=>ce().amazonBedrockApiKey};this.buildModelMap(),Ou(()=>{this.buildModelMap(),this.validateCurrentModel()})}static getInstance(){return Ph.instance||(Ph.instance=new Ph),Ph.instance}getTemperatureForModel(e,r,n){if(!e.isThinkingEnabled)return e.isOSeries||e.isGPT5?Ph.REASONING_MODEL_TEMPERATURE:r.temperature??n.temperature}async getModelConfig(e){let r=ce(),n=e.name,o=z6(n),{isThinkingEnabled:i}=o,a=this.getTemperatureForModel(o,e,r),s=e.maxTokens??r.maxTokens,u={modelName:n,streaming:e.stream??!0,maxRetries:3,maxConcurrency:3,enableCors:e.enableCors,...!i&&a!==void 0?{temperature:a}:{}},c={openai:{modelName:n,apiKey:await $i(e.apiKey||r.openAIApiKey),configuration:{baseURL:e.baseUrl,fetch:e.enableCors?Wc:void 0,organization:await $i(e.openAIOrgId||r.openAIOrgId)},...this.getOpenAISpecialConfig(n,e.maxTokens??r.maxTokens,e.temperature??r.temperature,e)},anthropic:{anthropicApiKey:await $i(e.apiKey||r.anthropicApiKey),model:n,anthropicApiUrl:e.baseUrl,clientOptions:{defaultHeaders:{"anthropic-dangerous-direct-browser-access":"true"},fetch:e.enableCors?Wc:void 0},...i&&{thinking:{type:"enabled",budget_tokens:2048}}},"azure openai":{modelName:e.azureOpenAIApiDeploymentName||r.azureOpenAIApiDeploymentName,apiKey:await $i(e.apiKey||r.azureOpenAIApiKey),configuration:{baseURL:e.baseUrl||`https://${e.azureOpenAIApiInstanceName||r.azureOpenAIApiInstanceName}.openai.azure.com/openai/deployments/${e.azureOpenAIApiDeploymentName||r.azureOpenAIApiDeploymentName}`,defaultQuery:{"api-version":e.azureOpenAIApiVersion||r.azureOpenAIApiVersion},defaultHeaders:{"Content-Type":"application/json","api-key":await $i(e.apiKey||r.azureOpenAIApiKey)},fetch:e.enableCors?Wc:void 0},...this.getOpenAISpecialConfig(n,e.maxTokens??r.maxTokens,e.temperature??r.temperature,e)},cohereai:{apiKey:await $i(e.apiKey||r.cohereApiKey),model:n},google:{apiKey:await $i(e.apiKey||r.googleApiKey),model:n,safetySettings:[{category:PH.HARM_CATEGORY_SEXUALLY_EXPLICIT,threshold:MH.BLOCK_NONE},{category:PH.HARM_CATEGORY_HATE_SPEECH,threshold:MH.BLOCK_NONE},{category:PH.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:MH.BLOCK_NONE},{category:PH.HARM_CATEGORY_HARASSMENT,threshold:MH.BLOCK_NONE}],baseUrl:e.baseUrl},xai:{apiKey:await $i(e.apiKey
without CORS Error: `+Eo(n)+`
with CORS Error: `+Eo(o);throw new Error(i)}}}findModelByName(e){return ce().activeModels.find(n=>n.name===e)}};Ph.REASONING_MODEL_TEMPERATURE=1;gI=Ph});var DNe={};Xn(DNe,{TieredLexicalRetriever:()=>rJ});async function GGo(){try{if(!qdt){let e=await Promise.resolve().then(()=>(hue(),Nqr));qdt=()=>e.default.getInstance()}return qdt().getChatModel()}catch{return null}}var Bdt,qdt,rJ,m7=v(()=>{Dt();Pt();vb();wr();X8();jOe();Bdt=require("obsidian");DOe();nTe();qdt=null;rJ=class extends SH{constructor(r,n){super();this.app=r;this.options=n;this.lc_namespace=["tiered_lexical_retriever"];this.searchCore=new rTe(r,GGo),typeof this.searchCore.getChunkManager=="function"?this.chunkManager=this.searchCore.getChunkManager():this.chunkManager=new Nk(r)}async getRelevantDocuments(r,n){try{if(this.options.timeRange)return this.getTimeRangeDocuments(r);let o=xO(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])];ce().debug&&J("TieredLexicalRetriever: Starting search",{query:r,salientTerms:s,maxK:this.options.maxK});let u=ce(),l=await this.searchCore.retrieve(r,{maxResults:this.options.returnAllTags?$m: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 ce().debug&&J("TieredLexicalRetriever: Search complete",{totalResults:f.length,titleMatches:c.length,searchResults:l.length}),f}catch(o){return Ot("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);ce().debug&&J("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=xO(a,this.app.vault).filter(h=>!G8(h)),l=(await this.getTitleMatches(s)).map(h=>(h.metadata.includeInContext=!0,h)),c=this.app.vault.getMarkdownFiles().filter(h=>!G8(h)),d=[],f=this.options.returnAll?$m:Math.min(this.options.maxK,$m);for(let h of c)if(h.stat.mtime>=n&&h.stat.mtime<=o){if(s.some(g=>g.path===h.path))continue;if(d.length>=f)break;try{let g=await this.app.vault.cachedRead(h),y=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 jm({pageContent:g,metadata:{path:h.path,title:h.basename,mtime:h.stat.mtime,ctime:h.stat.ctime,tags:y?.tags?.map(w=>w.tag)||[],includeInContext:!0,score:_,rerank_score:_,source:"time-filtered"}}))}catch(g){Ot(`TieredLexicalRetriever: Failed to read file ${h.path}`,g)}}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,g)=>{let y=h.metadata.score||0;return(g.metadata.score||0)-y});return ce().debug&&J("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=ce(),a=r.join(" ")||n,s=await this.searchCore.retrieve(a,{maxResults:$m,candidateLimit:$m,salientTerms:r,enableLexicalBoosts:i.enableLexicalBoosts,returnAll:!0}),u=await this.getTitleMat
Question: {question}
Passage:`)}async getRelevantDocuments(r,n){return Xh(async()=>{let o=xO(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 ce().debug&&console.log("No chunks found for query:",r),d;let f=c.reduce((h,g)=>{let y=g.metadata.score;return typeof y=="number"&&!isNaN(y)?Math.max(h,y):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 Ru.getInstance().rerank(r,c.map(g=>g.pageContent.slice(0,3e3)))).response.data.map(g=>({...c[g.index],metadata:{...c[g.index].metadata,rerank_score:g.relevance_score}}))),ce().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 Vhe(async()=>{let n=await this.queryRewritePrompt.format({question:r}),o=await Xh(async()=>(await Rg.instance.getCurrentChainManager().chatModelManager.getChatModelWithTemperature(0)).invoke(n));if(o&&"content"in o){let i=Lz(o.content);return V6(i)}return console.warn("Unexpected rewrittenQuery format. Falling back to original query."),r},W6)}catch(n){return console.error("Error in rewriteQuery:",n),r}}async getExplicitChunks(r){let n=[];for(let o of r){let i=await Z1.getInstance().getDb(),a=await G1.getDocsByPath(i,o.path);if(a){let s=a.map(u=>new jm({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 Z1.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&&(ce().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);J("Daily note date range:",d[0],d[d.length-1]);let f=xO(d.join(", "),app.vault),m=(await this.getExplicitChunks(f)).map(_=>({..._,metadata:{..._.metadata,includeInContext:!0}}));J("Modified time range:",l,c),s.where={mtime:{between:[l,c]}};let g=(await _b(a,s)).hits.map(_=>new jm({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}})),y=[...m,...g];return Array.from(new Set(y.map(_=>_.metadata.id))).map(_=>y.find(w=>w.metadata.id===_)).filter(_=>_!==void 0)}J(`Orama search params:
`,s);let u=await _b(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 jm({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 wd.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 zdt={};Xn(zdt,{MergedSemanticRetriever:()=>yue});var Yq,yue,LNe=v(()=>{$Ne();nTe();m7();X8();jOe();Yq=class Yq extends SH{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?$m:Math.min(this.originalMaxK*2,$m),i={...n,maxK:o,returnAll:this.returnAll,returnAllTags:n.returnAllTags,tagTerms:n.tagTerms};this.lexicalRetriever=new rJ(r,i);let a=this.returnAll?$m:Math.min(this.originalMaxK*2,$m);this.semanticRetriever=new gue({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?$m: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"?Yq.LEXICAL_WEIGHT:Yq.SEMANTIC_WEIGHT,s=i*a;return n==="lexical"&&this.hasTagMatch(o)&&(s*=Yq.TAG_MATCH_BOOST),o.score=s,o.rerank_score=s,new jm({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}};Yq.LEXICAL_WEIGHT=1,Yq.SEMANTIC_WEIGHT=1,Yq.TAG_MATCH_BOOST=1.1;yue=Yq});function XGo(t){return`
<guidance>
${Dqr}
Source Catalog (for reference only):
${t.join(`
`)}
</guidance>`}function YGo(t){return`
${Dqr}
Source Catalog (for reference only):
${t}`}function $qr(t,e){return t?XGo(e):""}function Lqr(t,e){return t?YGo(e):""}function FNe(t,e,r){if(!r||!e?.length||!t)return t||"";if(e9o(t))return t;let n=e.slice(0,QGo).map((o,i)=>{let a=(o.title||o.path||"Untitled").replace(/^\[\[|\]\]$/g,"");return`[^${i+1}]: [[${a}]]`}).join(`
`);return`${t}
#### Sources:
${n}`}function kNe(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 e9o(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 Fqr(t){return t?`
${ZGo}`:""}function t9o(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 r9o(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 n9o(t){return t.split(`
`).map(e=>e.trim()).filter(e=>/^\[\^\d+\]:/.test(e))}function o9o(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 i9o(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 a9o(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 s9o(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 u9o(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 l9o(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function c9o(t){return t!=null}function jqr(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=l9o(i),r.push({index:r.length+1,html:u})}),r}function Hdt(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 kqr(t,e){let r=t9o(t);if(!r)return t;let{mainContent:n,sourcesBlock:o}=r;if(o=r9o(o),!e){let d=jqr(o);return Hdt(n,d)}let i=n9o(o);if(i.length===0){let d=jqr(o);return Hdt(n,d)}let a=o9o(n,i);n=i9o(n,a);let s=a9o(o,a),{uniqueItems:u,consolidationMap:l}=s9o(s);l.size>0&&(n=u9o(n,l),s=u);let c=s.map((d,f)=>d?{index:f+1,html:d}:null).filter(c9o);return Hdt(n,c)}function qNe(t){return t.map(e=>{let r=e.title||e.path||"Untitled",n=e.path||r;return`- [[${r}]] (${n})`})}var Dqr,ZGo,QGo,bue=v(()=>{Dqr=`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)`,ZGo=`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`;QGo=20});var _ue,qqr=v(()=>{zr();Dt();m7();LNe();Dot();Pt();wr();vie();bue();wH();_ue=class extends Y1{async run(e,r,n,o,i){let a=new M_(n);try{let d=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),f=U6(d),p=e.message;f.length>0&&(p=e.message);let m=ce(),h=this.extractTagTerms(p),g={minSimilarityScore:.01,maxK:m.maxSourceChunks,salientTerms:h.length>0?[...h]:[],timeRange:void 0,textWeight:void 0,returnAll:!1,useRerankerThreshold:void 0},b=await(m.enableSemanticSearchV3?new yue(app,{...g,returnAll:h.length>0,returnAllTags:h.length>0,tagTerms:h}):new rJ(app,{...g,returnAll:h.length>0,returnAllTags:h.length>0,tagTerms:h})).getRelevantDocuments(p);this.chainManager.storeRetrieverDocuments(b);let _=b.map(F=>{let B=F.metadata?.title||"Untitled",U=F.metadata?.path||B;return`<${rHe}>
<title>${B}</title>
<path>${U}</path>
<content>
${kNe(F.pageContent)}
</content>
</${rHe}>`}).join(`
`),w=[],x=Y0(),O=b.slice(0,Math.max(5,Math.min(20,b.length))).map(F=>({title:F.metadata?.title||F.metadata?.path||"Untitled",path:F.metadata?.path||F.metadata?.title||""})),E=qNe(O).join(`
`),T=`
Answer the question based only on the following context:
`+_+Lqr(m.enableInlineCitations,E),R=x+T,N=this.chainManager.chatModelManager.getChatModel();R&&w.push({role:wL(N),content:R});for(let F of f)w.push({role:F.role,content:F.content});if(e.content&&Array.isArray(e.content)){let F=e.content.map(B=>B.type==="text"?{...B,text:e.message}:B);w.push({role:"user",content:F})}else w.push({role:"user",content:e.message});J(`Final Request to AI:
`,w);let D=await Xh(()=>this.chainManager.chatModelManager.getChatModel().stream(w,{signal:r.signal}));for await(let F of D){if(r.signal.aborted){J("VaultQA stream iteration aborted",{reason:r.signal.reason});break}a.processChunk(F)}}catch(c){c.name==="AbortError"||r.signal.aborted?J("VaultQA stream aborted by user",{reason:r.signal.reason}):await this.handleError(c,a.processErrorChunk.bind(a))}let s=a.close(),u={wasTruncated:s.wasTruncated,tokenUsage:s.tokenUsage??void 0};if(r.signal.aborted&&r.signal.reason==="new-chat")return n(""),"";let l=this.addSourcestoResponse(s.content);return await this.handleResponse(l,e,r,o,n,void 0,void 0,u),l}addSourcestoResponse(e){let r=ce(),n=this.chainManager.getRetrievedDocuments(),o=CAt(n).map(i=>({title:i}));return FNe(e,o,r.enableInlineCitations)}extractTagTerms(e){return Eie(e)}}});async function BNe(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 Xh(async()=>{let i=await(await Rg.instance.getCurrentChainManager().chatModelManager.getChatModelWithTemperature(0)).invoke([{role:"user",content:r.replace("{chat_history}",n).replace("{question}",t)}]),a=Lz(i.content);return V6(a)})}var Vdt=v(()=>{Xq();wr()});var Qq,vue=v(()=>{Qq=["@vault","@websearch","@composer","@memory"]});function fx(){}function Bqr(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 Uqr(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 zqr(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 Jdt(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 Kdt(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 wue(t,e){return Jdt(t,e,"")}function UNe(t,e){return Kdt(t,e,"")}function Hqr(t,e){return e.slice(0,d9o(t,e))}function d9o(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 Jqr(t,e,r){return r?.ignoreWhitespace!=null&&!r.ignoreWhitespace?p9o(t,e,r):Cue.diff(t,e,r)}function Vqr(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=Uqr(o,a);t.value=Kdt(t.value,a,u),e.value=wue(e.value,u),r.value=wue(r.value,u)}if(n){var l=zqr(i,s);n.value=Jdt(n.value,s,l),e.value=UNe(e.value,l),r.value=UNe(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=Uqr(c,d);e.value=wue(e.value,p);var m=zqr(wue(c,p),f);e.value=UNe(e.value,m),n.value=Jdt(n.value,c,m),t.value=Kdt(t.value,c,c.slice(0,c.length-m.length))}else if(n){var h=n.value.match(/^\s*/)[0],g=e.value.match(/\s*$/)[0],y=Hqr(g,h);e.value=UNe(e.value,y)}else if(t){var b=t.value.match(/\s*$/)[0],_=e.value.match(/^\s*/)[0],w=Hqr(b,_);e.value=wue(e.value,w)}}function p9o(t,e,r){return Kqr.diff(t,e,r)}function m9o(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 Wqr(t,e,r){var n=m9o(r,{ignoreWhitespace:!0});return HNe.diff(t,e,n)}function Wdt(t){"@babel/helpers - typeof";return Wdt=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},Wdt(t)}function Gdt(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]=Gdt(t[i],e,r,n,o);return e.pop(),r.pop(),a}if(t&&t.toJSON&&(t=t.toJSON()),Wdt(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]=Gdt(t[u],e,r,n,u);e.pop(),r.pop()}else a=t;return a}var iQa,zNe,f9o,Cue,Kqr,HNe,h9o,g9o,Sue,Zdt,Xdt=v(()=>{fx.prototype={diff:function(e,r){var n,o=arguments.length>2
`));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};HNe.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))),fx.prototype.equals.call(this,t,e,r)};h9o=new fx;h9o.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};g9o=new fx;g9o.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};Sue=new fx;Sue.useLongestToken=!0;Sue.tokenize=HNe.tokenize;Sue.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(Gdt(t,null,null,o),o," ")};Sue.equals=function(t,e,r){return fx.prototype.equals.call(Sue,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"),r)};Zdt=new fx;Zdt.tokenize=function(t){return t.slice()};Zdt.join=Zdt.removeEmpty=function(t){return t}});function Gqr(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 Zqr=v(()=>{});var BD,Jn,Xqr,Yqr,xue,VNe,Qqr,y9o,Ydt=v(()=>{jn();Dt();Xdt();On();BD=require("obsidian"),Jn=L(X()),Xqr=L(wm());Ro();Yqr=L(X());Zqr();wr();xue="obsidian-copilot-apply-view",VNe=class extends BD.ItemView{constructor(r){super(r);this.root=null;this.state=null;this.result=null}getViewType(){return xue}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,Xqr.createRoot)(n)),this.root.render(Jn.default.createElement(y9o,{app:this.app,state:this.state,close:o=>{this.result=o,this.leaf.detach()}}))}},Qqr=(0,Jn.memo)(({oldLine:t,newLine:e})=>{let r=Jqr(t,e);return Jn.default.createElement(Jn.default.Fragment,null,r.map((n,o)=>n.added?Jn.default.createElement("span",{key:o,className:"tw-text-success"},n.value):n.removed?Jn.default.createElement("span",{key:o,className:"tw-text-error tw-line-through"},n.value):Jn.default.createElement("span",{key:o},n.value)))});Qqr.displayName="WordDiff";y9o=({app:t,state:e,close:r})=>{let[n,o]=(0,Yqr.useState)(()=>e.changes.map(m=>({...m,accepted:null}))),i=Gqr(n),a=(0,Jn.useRef)([]);if(!e||!e.changes)return ue("Invalid state:",e),Jn.default.createElement("div",{className:"tw-flex tw-h-full tw-flex-col tw-items-center tw-justify-center"},Jn.default.createElement("div",{className:"tw-text-error"},"Error: Invalid state - missing changes"),Jn.default.createElement(ve,{onClick:()=>r("failed"),className:"tw-mt-4"},"Close"));let s=async()=>{try{let m=n.map(g=>g.accepted===null?{...g,accepted:!0}:g),h=await c(m);r(h?"accepted":"failed")}catch(m){ue("Error applying changes:",m),new BD.Notice(`Error applying changes: ${m.message}`),r("failed")}},u=async()=>{try{let m=n.map(g=>g.accepted===null?{...g,accepted:!1}:g),h=await c(m);r(h?"rejected":"failed")}catch(m){ue("Error applying changes:",m),new BD.Notice(`Error applying changes: ${m.message}`),r("failed")}},l=async m=>{let h=t.vault.getAbstractFileByPath(m);if(h)return h;if(m.includes("/")){let g=m.split("/").slice(0,-1).join("/");await ty(g)}return await t.vault.create(m,"")},c=async m=>{let h=m.filter(y=>y.added?y.accepted===!0:y.removed?y.accepted===!1:!0).map(y=>y.value).join(""),g=await l(e.path);return!g||!(g instanceof BD.TFile)?(ue("Error in getting file",e.path),new BD.Notice("Failed to create file"),!1):(await t.vault.modify(g,h),new BD.Notice("Changes applied successfully"),!0)},d=m=>{if(!i)return;let h=-1;for(let g=m+1;g<i.length;g++){let y=i[g],b=y.some(w=>w.added||w.removed),_=y.some(w=>(w.added||w.removed)&&w.accepted===null);if(b&&_){h=g;break}}h!==-1&&a.current[h]&&a.current[h]?.scrollIntoView({behavior:"smooth",block:"center"})},f=m=>{o(h=>{let g=[...h],y=i?.[m];return y&&y.forEach(b=>{let _=g.findIndex(w=>w===b);_!==-1&&(g[_]={...g[_],accepted:!0})}),g}),setTimeout(()=>d(m),0)},p=m=>{o(h=>{let g=[...h],y=i?.[m];return y&&y.forEach(b=>{let _=g.findIndex(w=>w===b);_!==-1&&(g[_]={...g[_],accepted:!1})}),g}),setTimeout(()=>d(m),0)};return Jn.default.createElement("div",{className:"tw
`).replace(/\r/g,`
`)}function w9o(t,e,r){let n=(t.match(/\r\n/g)||[]).length,o=(t.match(/(?<!\r)\n/g)||[]).length,i=n>o,a=Oue(t),s=Oue(e),u=Oue(r),l=a.replaceAll(s,u);return i?l.replace(/\n/g,`\r
`):l}function S9o(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 h7,_9o,JNe,v9o,nBr,Qdt=v(()=>{h7=require("obsidian");Ydt();Xdt();yI();bI();wr();_9o=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"}
]
}`)}),JNe=Gl({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:_9o,handler:async({path:t,content:e})=>{let r=typeof e=="string"?e:JSON.stringify(e,null,2),n=await rBr(t,r);return JSON.stringify({result:n,message:`File change result: ${n}. Do not retry or attempt alternative approaches to modify this file in response to the current user request.`})},timeoutMs:0}),v9o=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`)});nBr=Gl({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:v9o,handler:async({path:t,diff:e})=>{let r=app.vault.getAbstractFileByPath(t);if(!r||!(r instanceof h7.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=S9o(e);if(a.length===0)return`No valid SEARCH/REPLACE blocks found in diff. Please use the correct format with ------- SEARCH, =======, and +++++++ REPLACE markers.
diff: ${e}`;let s=0;for(let l of a){let{searchText:c,replaceText:d}=l,f=Oue(o),p=Oue(c);if(!f.includes(p))if(f.includes(p.trimEnd()))c=c.trimEnd(),d=d.trimEnd();else return`Search text not found in file ${t} : "${c}".`;let m=o;o=w9o(o,c,d),o!==m&&s++}if(n===o)return`No changes made to ${t}. The search text was not found or replacement resulted in identical content. Call writeToFile instead`;let u=await rBr(t,o);return JSON.stringify({result:u,blocksApplied:s,message:`Applied ${s} SEARCH/REPLACE block(s) (replacing all occurrences). Result: ${u}. Do not call this tool again to modify this file in response to the current user request.`})}catch(n){return`Error performing SEARCH/REPLACE on ${t}: ${n}. Please check the file path and diff format and try again.`}},timeoutMs:0})});var eft,tft,_I,Tue=v(()=>{eft=require("obsidian"),tft=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""}},_I=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 eft.Notice(n.message):new eft.Notice("An error occurred while executing the tool. Check console for details."),null}}}});function KNe(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 C9o(t){let e=t.trim();return e.length<=oBr?e:`${e.slice(0,oBr)}\u2026`}function x9o(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?C9o(t.message):null,n=typeof t.notePath=="string"?t.notePath:"",i=(typeof t.noteTitle=="string"&&t.noteTitle.trim().length>0?t.noteTitle.trim():KNe(n))||KNe(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 oBr,px,Eue=v(()=>{oBr=180;px=class{static format(e,r){try{let n=r;if(typeof n=="string"&&n.startsWith("ENC:"))try{n=decodeURIComponent(n.slice(4))}catch{}let o;try{o=JSON.parse(n)}catch{o=n}switch(e){case"localSearch":return this.formatLocalSearch(o);case"webSearch":return this.formatWebSearch(o);case"youtubeTranscription":return this.formatYoutubeTranscription(o);case"writeToFile":return this.formatWriteToFile(o);case"replaceInFile":return this.formatReplaceInFile(o);case"readNote":return this.formatReadNote(o);default:return r}}catch{return r}}static formatLocalSearchDocuments(e){if(!Array.isArray(e)||e.length===0)return`\u{1F4DA} Found 0 relevant notes
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(),g=(p?.[1]||"").trim();s.push({title:m,path:h,mtime:g||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=x9o(r);return n||(typeof e=="string"?e:JSON.stringify(e,null,2))}}});function O9o(t){return"children"in t&&"path"in t}function T9o(t){return"path"in t&&!("children"in t)}function E9o(t){let e=t.split(".");return e.length>1&&e.pop()?.toLowerCase()||""}function rft(t,e=!0){let r=[],n={},o={},{inclusions:i,exclusions:a}=id();for(let u of t.children)if(T9o(u)){if(ml(u,i,a)){e&&r.push(u.name);let l=E9o(u.name)||"unknown";l&&(n[l]=(n[l]||0)+1)}}else if(O9o(u)){let l=rft(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 WNe,nft=v(()=>{vb();yI();bI();WNe=t=>Gl({name:"getFileTree",description:"Get the file tree as a nested structure of folders and files",schema:Ct.void(),handler:async()=>{let e=rft(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=rft(t,!1);return r+JSON.stringify(o)}return r+n},isBackground:!0})});async function oft(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 jS())return{toolName:t.name,result:`Error: ${nJ(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 _I.callTool(o,i):s=await Promise.race([_I.callTool(o,i),new Promise((u,l)=>setTimeout(()=>l(new Error(`Tool execution timed out after ${a}ms`)),a))]),s==null?(Ot(`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 ue(`Error executing tool ${t.name}:`,o),{toolName:t.name,result:`Error: ${Eo(o)}`,success:!1}}}function nJ(t){return t==="localSearch"?ce().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 g7(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:"\u{1F50D}"}[t]||"\u{1F527}"}function iBr(t,e){if(t=="writeToFile"||t=="replaceInFile")return"Accept / reject in the Preview";if(t==="localSearch"&&e?.salientTerms&&!ce().enableSemanticSearchV3){let n=Array.isArray(e.salientTerms)?e.salientTerms:[];if(n.length>0)return`Terms: ${n.slice(0,3).join(", ")}${n.length>3?"...":""}`}return null}function ift(t,e){let r=nJ(t.name),n=g7(t.name),o=Object.keys(t.args).length>0?JSON.stringify(t.args,null,2):"(no parameters)";J(`${n} [Iteration ${e}] ${r.toUpperCase()}`),J("Parameters:",o),J("---")}function aft(t,e){if(t==="localSearch")return;let r=nJ(t),n=g7(t),o=e.success?"\u2705 SUCCESS":"\u274C FAILED";J(`${n} ${r.toUpperCase()} RESULT: ${o}`);let i=300,a=String(e.result??"");a.length>i?J(`Result: ${a.substring(0,i)}... (truncated, ${a.length} chars total)`):a.length>0&&J("Result:",a)}function eB(t){let e=new Map;for(let r of t){let n=r.path||r.title,o=e.get(n);(!o||r.score>o.score)&&e.set(n,r)}return Array.from(e.values()).sort((r,n)=>n.score-r.score)}var Pue=v(()=>{Dt();$v();Pt();Tue();wr()});var sft,P9o,M9o,Mue,aBr,R9o,Rue,uft=v(()=>{Vdt();zr();RS();Dt();Pt();yI();Pue();bI();nTe();bue();sft=Ct.object({query:Ct.string().min(1).describe("The search query"),salientTerms:Ct.array(Ct.string()).describe("List of salient terms extracted from the query"),timeRange:Ct.object({startTime:Ct.any(),endTime:Ct.any()}).optional().describe("Time range for search")}),P9o=Gl({name:"lexicalSearch",description:"Search for notes using lexical/keyword-based search",schema:sft,handler:async({timeRange:t,query:e,salientTerms:r})=>{let n=ce(),o=r.filter(y=>y.startsWith("#")),i=t!==void 0,a=o.length>0,s=i||a,u=s?$m:n.maxSourceChunks;J(`lexicalSearch returnAll: ${i} (tags returnAll: ${a})`);let l={minSimilarityScore:s?0:.1,maxK:u,salientTerms:r,timeRange:t?{startTime:t.startTime.epoch,endTime:t.endTime.epoch}:void 0,textWeight:nHe,returnAll:i,useRerankerThr
`+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}),R9o=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")}),Rue=Gl({name:"webSearch",description:"Search the web for information",schema:R9o,isPlusOnly:!0,handler:async({query:t,chatHistory:e})=>{try{let r=await BNe(t,e),n=await Ru.getInstance().webSearch(r),o=n.response.citations||[],a=[{type:"web_search",content:n.response.choices[0].message.content,citations:o,instruction:Fqr(ce().enableInlineCitations)}];return JSON.stringify(a)}catch(r){return console.error(`Error processing web search query ${t}:`,r),""}}})});var sBr=S((lft,cft)=>{(function(t,e){typeof lft=="object"&&typeof cft<"u"?cft.exports=e():typeof define=="function"&&define.amd?define(e):(t=typeof globalThis<"u"?globalThis:t||self).dayjs_plugin_quarterOfYear=e()})(lft,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 tB=S((dft,fft)=>{(function(t,e){typeof dft=="object"&&typeof fft<"u"?fft.exports=e():typeof define=="function"&&define.amd?define(e):(t=typeof globalThis<"u"?globalThis:t||self).dayjs=e()})(dft,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,g={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(F){var B=["th","st","nd","rd"],U=F%100;return"["+F+(B[(U-20)%10]||B[U]||B[0])+"]"}},y=function(F,B,U){var H=String(F);return!H||H.length>=B?F:""+Array(B+1-H.length).join(U)+F},b={s:y,z:function(F){var B=-F.utcOffset(),U=Math.abs(B),H=Math.floor(U/60),G=U%60;return(B<=0?"+":"-")+y(H,2,"0")+":"+y(G,2,"0")},m:function F(B,U){if(B.date()<U.date())return-F(U,B);var H=12*(U.year()-B.year())+(U.month()-B.month()),G=B.clone().add(H,l),ie=U-G<0,oe=B.clone().add(H+(ie?-1:1),l);return+(-(H+(U-G)/(ie?G-oe:oe-G))||0)},a:function(F){return F<0?Math.ceil(F)||0:Math.floor(F)},p:function(F){return{M:l,y:d,w:u,d:s,D:f,h:a,m:i,s:o,ms:n,Q:c}[F]||String(F||"").toLowerCase().replace(/s$/,"")},u:function(F){return F===void 0}},_="en",w={};w[_]=g;var x="$isDayjsObject",O=function(F){return F instanceof N||!(!F||!F[x])},E=function F(B,U,H){var G;if(!B)return _;if(typeof B=="string"){var ie=B.toLowerCase();w[ie]&&(G=ie),U&&(w[ie]=U,G=ie);var oe=B.split("-");if(!G&&oe.length>1)return F(oe[0])}else{var z=B.name;w[z]=B,G=z}return!H&&G&&(_=G),G||!H&&_},T=function(F,B){if(O(F))return F.clone();var U=typeof B=="object"?B:{};return U.date=F,U.args=arguments,new N(U)},R=b;R.l=E,R.i=O,R.w=function(F,B){return T(F,{locale:B.$L,utc:B.$u,x:B.$x,$offset:B.$offset})};var N=function(){function F(U){this.$L=E(U.locale,null,!0),this.parse(U),this.$x=this.$x||U.x||{},this[x]=!0}var B=F.prototype;return B.parse=function(U){this.$d=function(H){var G=H.date,ie=H.utc;if(G===null)return new Date(NaN);if(R.u(G))return new Date;if(G instanceof Date)return new Date(G);if(typeof G=="string"&&!/Z$/i.test(G)){var oe=G.match(m);if(oe){var z=oe[2]-1||0,Q=(oe[7]||"0").substring(0,3);return ie?new Date(Date.UTC(oe[1],z,oe[3]||1,oe[4]||0,oe[5]||0,oe[6]||0,Q)):new Date(oe[1],z,oe[3]||1,oe[4]||0
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,Aue.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,Aue.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?(GNe(o,n),mx(o,n),e.timezoneOffset!==null&&o.assign("timezoneOffset",-e.instant.getTimezoneOffset())):(y7(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}},UD=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 Ka(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 hft(t,e,r="\\s{0,5},?\\s{0,5}"){let n=e.replace(/\((?!\?)/g,"(?:");return`${t}${n}(?:${r}${n}){0,10}`}function I9o(t){let e;return t instanceof Array?e=[...t]:t instanceof Map?e=Array.from(t.keys()):e=Object.keys(t),e}function Ag(t){return`(?:${I9o(t).sort((r,n)=>n.length-r.length).join("|").replace(/\./g,"\\.")})`}var iB=v(()=>{});function XNe(t){return t<100&&(t>50?t=t+1900:t=t+2e3),t}function aB(t,e,r){let n=(0,dBr.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 dBr,_7=v(()=>{dBr=L(tB(),1)});function N9o(t){let e=t.toLowerCase();return gft[e]!==void 0?gft[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 w7(t){let e=t.toLowerCase();return yft[e]!==void 0?yft[e]:(e=e.replace(/(?:st|nd|rd|th)$/i,""),parseInt(e))}function uB(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 XNe(e)}function u0(t){let e={},r=t,n=fBr.exec(r);for(;n;)D9o(e,n),r=r.substring(n[0].length).trim(),n=fBr.exec(r);return Object.keys(e).length==0?null:e}function D9o(t,e){if(e[0].match(/^[a-zA-Z]+$/))return;let r=N9o(e[1]),n=Iue[e[2].toLowerCase()];t[n]=r}var bft,_ft,s0,gft,yft,pBr,Iue,mBr,v7,sB,hBr,fBr,j9o,gBr,zD,lB,Um=v(()=>{iB();_7();bft={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},_ft={january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12},s0={..._ft,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},gft={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})=>fXo(t),isBackground:!0}),Zzr={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};T1e=Gl({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})=>vXo(t),isBackground:!0});E1e=Gl({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})=>wXo(t),isBackground:!0});P1e=Gl({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})=>SXo(t,e,r),isBackground:!0})});var H7,CB,M1e=v(()=>{H7=require("obsidian");Dt();Pt();wr();$s();CB=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 H7.TFile?this.recentConversationsContent=await this.app.vault.read(e):(this.recentConversationsContent="",J("[UserMemoryManager] Recent Conversations file not found, skipping memory load"));let r=this.app.vault.getAbstractFileByPath(this.getSavedMemoriesFilePath());r instanceof H7.TFile?this.savedMemoriesContent=await this.app.vault.read(r):(this.savedMemoriesContent="",J("[UserMemoryManager] Saved Memories file not found, skipping saved memory load"))}catch(e){ue("[UserMemoryManager] Error reading memory files:",e),this.recentConversationsContent="",this.savedMemoriesContent=""}}addRecentConversation(e,r){if(!ce().enableRecentConversations){Ot("[UserMemoryManager] Recent history referencing is disabled, skipping analysis");return}if(e.length===0){Ot("[UserMemoryManager] No messages to analyze for user memory");return}this.updateMemory(e,r).catch(o=>{ue("[UserMemoryManager] Background user memory operation failed:",o)})}async updateSavedMemory(e,r){if(!ce().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=ce(),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 ue("[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){J("[UserMemoryManager] Memory update already in progress, skipping.");return}this.isUpdatingMemory=!0;try{if(await this.ensureMemoryFolderExists(),!r){ue("[UserMemoryManager] No chat model available, skipping memory update");return}if(e.length===0){J("[UserMemoryManager] No messages available, skipping memory update");return}let n=await this.createConversationSection(e,r);await this.addToRecentConversationsFile(this.getRecentConversationFilePath(),n)}catch(n){ue("[UserMemoryManager] Error analyzing chat messages for user memory:",n)}finally{this.isUpdatingMemory=!1}}async ensureMemoryFolderExists(){let r=ce().memoryFolderName;await ty(r)}getRecentConversationFilePath(){return`${ce().memoryFolderName}/Recent Conversations.md`}getSavedMemoriesFilePath(){return`${ce().memoryFolderName}/Saved Memories.md`}async updateSavedMemoryFile(e,r,n){let o=this.app.vault.getAbstractFileByPath(e),i=o instanceof H7.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 Ym(a),new su(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 H7.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 H7.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=ce().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 Ym(o),new su(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 ue("[UserMemoryManager] Failed to parse LLM response as JSON:",c),{title:"Untitled Conversation",summary:"Summary generation failed"}}}catch(s){return ue("[UserMemoryManager] Failed to extract title and summary:",s),{title:"Untitled Conversation",summary:"Summary generation failed"}}}}});var CXo,R1e,Spt=v(()=>{yI();bI();M1e();Dt();hue();CXo=Ct.object({statement:Ct.string().min(1).describe("The user statement for explicitly updating saved memories")}),R1e=Gl({name:"updateMemory",description:"Update the user memory when the user explicitly asks to update the memory",schema:CXo,handler:async({statement:t})=>{try{let e=new CB(app),r=gI.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 ue("[updateMemoryTool] Error updating memory:",e),{success:!1,message:`Failed to save memory: ${e.message}`}}}})});var pJ,Cpt=v(()=>{Xq();Tu();nft();uft();wpt();Tue();wr();RS();Spt();vue();pJ=class{static initTools(e){this.tools.length===0&&(this.tools=[O1e,P1e,E1e,T1e,Mue,aBr,Rue,WNe(e.getRoot())])}static async analyzeIntent(e){try{let r=await Ru.getInstance().broca(e,Jz());if(!r?.response)throw new Error(r?.detail||"Broca API call failed");let n=r.response.tool_calls,o=r.response.salience_terms,i=[],a;for(let s of n){let u=this.tools.find(l=>l.name===s.tool);if(u){let l=s.args||{};if(u.name==="getTimeRangeMs"&&(a=await _I.callTool(u,l)),u.name=="getFileTree"&&Jz())continue;i.push({tool:u,args:l})}}return await this.processAtCommands(e,i,{timeRange:a,salientTerms:o}),i}catch(r){throw console.error("Error in intent analysis:",r),r}}static async processAtCommands(e,r,n){let o=e.toLowerCase(),{timeRange:i,salientTerms:a}=n;if(o.includes("@vault")){let s=this.removeAtCommands(e);r.push({tool:Mue,args:{timeRange:i||void 0,query:s,salientTerms:a}})}if(o.includes("@websearch")||o.includes("@web")){let s=this.removeAtCommands(e),l=await Rg.instance.getCurrentChainManager().memoryManager.getMemory().loadMemoryVariables({}),c=U6(l);r.push({tool:Rue,args:{query:s,chatHistory:c}})}if(o.includes("@memory")){let s=this.removeAtCommands(e);r.push({tool:R1e,args:{statement:s}})}}static removeAtCommands(e){return e.split(" ").filter(r=>!Qq.includes(r.toLowerCase())).join(" ").trim()}};pJ.tools=[]});var A1e,Xzr=v(()=>{Eue();A1e=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=px.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 zle(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=xXo(r);n&&e.push({role:n,content:r.content})}}return e}function xXo(t){return t.role==="human"||t.role==="user"||t.sender==="user"?"user":t.role==="ai"||t.role==="assistant"||t.sender==="AI"?"assistant":null}function I1e(t,e){let r=zle(t);for(let n of r)e.push({role:n.role,content:n.content})}function N1e(t){return t.map(e=>{let r;return typeof e.content=="string"?r=e.content:Array.isArray(e.content)?r=e.content.filter(o=>o.type==="text").map(o=>o.text||"").join(" ")||"[Image content]":r=String(e.content||""),{role:e.role,content:r}})}var j1e=v(()=>{});function xpt(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 Yzr(t){try{let e=JSON.parse(t);return Array.isArray(e)?xpt(e):"Invalid search results format."}catch(e){return Ot("Failed to format localSearch result string:",e),"Error processing search results."}}function Qzr(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 OXo(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 TXo(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 e4r(t){if(!Array.isArray(t)||t.length===0){J("Search Results: (none)");return}let e=0,r=t.map((u,l)=>{let c=OXo(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=TXo(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;J(`Search Results (debug table): ${n} rows; in-context ${e}/${n}`),mAt(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)} |`);Lhe(["",`Results: ${n} rows; in-context ${e}/${n}`,"",i,a,...s,""])}var t4r=v(()=>{Dt()});function r4r(t,e){return[t,e].map(n=>n?.trim()).filter(n=>!!n).join(`
`)}function n4r(t,e){let r=t?`
${t}
`:"";return`<localSearch${e?` timeRange="${e}"`:""}>${r}</localSearch>`}function o4r(t,e){if(!e)return t;let r="Have inline citations according to the guidance.",n=t.trimEnd();return n?n.toLowerCase().includes(r.toLowerCase())?n:`${n}
${r}`:r}function Opt(t,e,r){let n=t.trim();if(!n)return e;let o=r?`Question: ${e}`:e;return`${n}
${o}`}function i4r(t,e){let r=e.trim();return!r||t.includes(r)?t:Opt(t,r,!0)}var Tpt=v(()=>{});var vI,D1e=v(()=>{Vdt();vue();zr();uot();Dt();$v();Pt();Qdt();Tue();Eue();wr();Cpt();vie();Xzr();j1e();bue();t4r();Tpt();wH();Pue();vI=class extends Y1{constructor(){super(...arguments);this.lastCitationSources=null}async processImageUrls(r){let n=[],o=await vH.processUrlBatch(r,n,this.chainManager.app.vault);return vH.showFailedImagesNotice(n),o}async processChatInputImages(r){let n=[],o=await vH.processChatImageBatch(r,n,this.chainManager.app.vault);return vH.showFailedImagesNotice(n),o}extractNoteContent(r){let n=/<note_context>([\s\S]*?)<\/note_context>/g,o=/<active_note>([\s\S]*?)<\/active_note>/g,i=/<content>([\s\S]*?)<\/content>/g,a="",s;for(;(s=n.exec(r))!==null;){let u=s[1],l;for(;(l=i.exec(u))!==null;)a+=l[1]+`
`}for(;(s=o.exec(r))!==null;){let u=s[1],l;for(;(l=i.exec(u))!==null;)a+=l[1]+`
`}return a.trim()}async extractEmbeddedImages(r,n){let o=/!\[\[(.*?\.(png|jpg|jpeg|gif|webp|bmp|svg))\]\]/g,i=/!\[.*?\]\(([^)]+)\)/g,a=[],s=[...r.matchAll(o)];for(let l of s){let c=l[1];if(n){let d=app.metadataCache.getFirstLinkpathDest(c,n);d?a.push(d.path):(Ot(`Could not resolve embedded image: ${c} from source: ${n}`),a.push(c))}else a.push(c)}let u=[...r.matchAll(i)];for(let l of u){let c=l[1].trim();if(!c)continue;if(c.match(/^https?:\/\//)){a.push(c);continue}let d=c.replace(/^\.\//,"").replace(/^\//,"");if(n){let f=app.metadataCache.getFirstLinkpathDest(d,n);f?a.push(f.path):a.push(d)}else a.push(d)}return a}async buildMessageContent(r,n){let o=[],i=[],a=ce(),s=[];if(a.passMarkdownImages){let d;if(n.context?.notes&&n.context.notes.length>0)d=n.context.notes[0].path;else{let p=this.chainManager.app?.workspace.getActiveFile();p&&(d=p.path)}let f=this.extractNoteContent(r);if(f){let p=await this.extractEmbeddedImages(f,d);p.length>0&&s.push({urls:p,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>
${RAt}
</OUTPUT_FORMAT>`;return`${r}
${o}`}async streamMultimodalResponse(r,n,o,i){let u=(await this.chainManager.memoryManager.getMemory().loadMemoryVariables({})).history||[],l=[],c=await this.getSystemPrompt();u.length>0&&(c+=`
The following is the relevant conversation history. Use this context to maintain consistency in your responses:`);let d=this.chainManager.chatModelManager.getChatModel();c&&l.push({role:wL(d),content:`${c}
IMPORTANT: Maintain consistency with previous responses in the conversation. If you've provided information about a person or topic before, use that same information in follow-up questions.`}),I1e(u,l);let f=this.chainManager.chatModelManager.getChatModel(),m=this.isMultimodalModel(f)?await this.buildMessageContent(r,n):r;l.push({role:"user",content:m});let h=m instanceof Array?m[0].text:m;J("Enhanced user message: ",h),J("Final request to AI",{messages:l.length});let g=new A1e(_I,JNe),y=await Xh(()=>this.chainManager.chatModelManager.getChatModel().stream(l,{signal:o.signal}));for await(let b of y){if(o.signal.aborted){J("CopilotPlus multimodal stream iteration aborted",{reason:o.signal.reason});break}for await(let _ of g.processChunk(b))i.processChunk(_)}}async run(r,n,o,i,a){let{updateLoadingMessage:s}=a,u=new M_(o),l=[];if(!await jS({isCopilotPlus:!0})){await this.handleError(new Error("Invalid license key"),u.processErrorChunk.bind(u));let g=u.close().content;return this.handleResponse(g,r,n,i,o,void 0)}try{J("==== Step 1: Analyzing intent ====");let g,y=r.originalMessage||r.message;try{g=await pJ.analyzeIntent(y)}catch(H){return this.handleResponse(_At(H),r,n,i,o)}let b=r.message.split(" ").filter(H=>!Qq.includes(H.toLowerCase())).join(" ").trim(),{toolOutputs:_,sources:w}=await this.executeToolCalls(g,s);l=w;let O=_.find(H=>H.tool==="localSearch"&&H.output!=null)&&l.length>0,R=(await this.chainManager.memoryManager.getMemory().loadMemoryVariables({})).history||[],N=zle(R),D=N1e(N),F=b;D.length>0&&(J("Condensing question"),F=await BNe(b,D),J("Condensed standalone question: ",F));let B=this.prepareEnhancedUserMessage(F,_),U=_.some(H=>H.tool!=="localSearch"&&H.output!=null);O&&!U&&(B=`Answer the question with as detailed as possible based only on the following context:
${B}`),B=this.appendComposerInstructionsIfNeeded(B,r),J("Invoking LLM with all tool results"),await this.streamMultimodalResponse(B,r,n,u)}catch(g){s?.(EO.DEFAULT),g.name==="AbortError"||n.signal.aborted?J("CopilotPlus stream aborted by user",{reason:n.signal.reason}):await this.handleError(g,u.processErrorChunk.bind(u))}if(n.signal.aborted&&n.signal.reason==="new-chat")return o(""),"";let d=u.close(),f=d.content,p={wasTruncated:d.wasTruncated,tokenUsage:d.tokenUsage??void 0},m=ce(),h=this.lastCitationSources&&this.lastCitationSources.length>0?this.lastCitationSources:(l||[]).map(g=>({title:g.title,path:g.path}));return f=FNe(f,h,m.enableInlineCitations),await this.handleResponse(f,r,n,i,o,l,void 0,p),f}getSources(r){return!r||!Array.isArray(r)?(Ot("No valid documents provided to getSources"),[]):this.sortUniqueDocsByScore(r)}sortUniqueDocsByScore(r){let n=new Map;for(let o of r){if(!o.title||!o?.score&&!o?.rerank_score){Ot("Invalid document structure:",o);continue}let i=o.path||o.title,a=n.get(i),s=o&&"rerank_score"in o,u=s?o.rerank_score:o.score;(!a||u>(a.score??0))&&n.set(i,{title:o.title,path:o.path||o.title,score:u,isReranked:s,explanation:o.explanation||null})}return Array.from(n.values()).sort((o,i)=>(i.score??0)-(o.score??0))}async executeToolCalls(r,n){let o=[],i=[];for(let a of r){J(`Step 2: Calling tool: ${a.tool.name}`),a.tool.name==="localSearch"?n?.(EO.READING_FILES):a.tool.name==="webSearch"?n?.(EO.SEARCHING_WEB):a.tool.name==="getFileTree"&&n?.(EO.READING_FILE_TREE);let s=await _I.callTool(a.tool,a.args);if(a.tool.name==="localSearch"){let l={result:typeof s=="string"?s:JSON.stringify(s),success:s!=null},c=this.getTimeExpression(r),d=this.processLocalSearchResult(l,c);i.push(...d.sources),o.push({tool:a.tool.name,output:d.formattedForLLM})}else o.push({tool:a.tool.name,output:s})}return{toolOutputs:o,sources:eB(i)}}prepareEnhancedUserMessage(r,n){let o="",i=!1,a=n.find(l=>l.tool==="localSearch"&&l.output!=null);a&&typeof a.output=="string"&&/<document>/.test(a.output)&&(i=!0);let s=n.filter(l=>l.output!=null);if(s.length>0&&(o=((i&&s.length===1?"":`
# Additional context:
`)+s.map(d=>{let f=d.output;return typeof f!="string"&&(f=JSON.stringify(f)),d.tool==="localSearch"?f:`<${d.tool}>
${f}
</${d.tool}>`}).join(`
`)).trim()),!o)return r;let u=i&&s.length===1;return Opt(o,r,u)}getTimeExpression(r){let n=r.find(o=>o.tool.name==="getTimeRangeMs");return n?n.args.timeExpression:""}prepareLocalSearchResult(r,n){let o=r.filter(m=>m.includeInContext),i=o.reduce((m,h)=>m+(h.content?.length||0),0),a=o;if(i>oHe){let m=oHe/i;J("Truncating document contents to fit context length. Truncation ratio:",m),a=o.map(h=>({...h,content:h.content?.slice(0,Math.floor((h.content?.length||0)*m))||""}))}let s=a.map((m,h)=>({...m,__sourceId:h+1,content:kNe(m.content||"")})),u=xpt(s),l=s.slice(0,Math.min(20,s.length)).map(m=>({title:m.title||m.path||"Untitled",path:m.path||m.title||""})),c=qNe(l);this.lastCitationSources=s.slice(0,Math.min(20,s.length)).map((m,h)=>({title:m.title||m.path||"Untitled",path:m.path||void 0}));let d=ce(),f=$qr(d.enableInlineCitations,c),p=r4r(f,u);return n4r(p,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};e4r(u),o=Qzr(u),i=this.prepareLocalSearchResult(u,n||""),a=px.format("localSearch",i)}catch(s){Ot("Failed to parse localSearch results:",s);let u=Yzr(r.result);i=n?`<localSearch timeRange="${n}">
${u}
</localSearch>`:`<localSearch>
${u}
</localSearch>`,a=px.format("localSearch",i)}return{formattedForLLM:i,formattedForDisplay:a,sources:o}}async getSystemPrompt(){return PN(this.chainManager.userMemoryManager)}}});var Hle,a4r=v(()=>{Tu();Pt();Xq();D1e();Hle=class extends vI{async getSystemPrompt(){let e=Y0(),r=tc();if(!r)return e;let n=await Rg.instance.getProjectContext(r.id);return e=`${e}
<project_system_prompt>
${r.systemPrompt}
</project_system_prompt>`,n&&(e=`${e}
<project_context>
${n}
</project_context>`),e}}});function MXo(){return typeof app>"u"||!app?.metadataCache?null:app.metadataCache}function u4r(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 RXo(t,e,r){let n=t,o=u4r(n.getFrontmatterTags?.()),i=e?u4r(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 AXo(t){let e=t,r=JSON.stringify(e);if(r.length<=Ept)return e;let n=e.tags.length;for(;r.length>Ept&&n>s4r;)n=Math.max(s4r,Math.floor(n/2)),e={...e,tags:t.tags.slice(0,n),returnedTagCount:n,truncated:!0},r=JSON.stringify(e);return r.length>Ept?{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 l4r(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 Ept,EXo,s4r,PXo,c4r,d4r=v(()=>{yI();bI();Ept=5e5,EXo=500,s4r=50,PXo=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.");c4r=()=>Gl({name:"getTagList",description:"Get the list of tags in the vault with occurrence statistics.",schema:PXo,handler:async t=>{let e=MXo(),r=t?.includeInline??!0,n=t?.maxEntries??EXo;if(!e)return l4r({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=RXo(e,r,n),i=AXo(o);return l4r(i)},isBackground:!0})});function $1e(t){return t.replace(/\\/g,"/").toLowerCase()}function IXo(t){return t.replace(/\.[^/.]+$/,"")}function NXo(t,e){if(e.length===0)return!1;let n=$1e(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=IXo(s);if(!s.includes(a)&&!u.includes(a))return!1}else if(!s.includes(a))return!1}return!0}function Mpt(t){return/\.[^/]+$/.test(t)}async function jXo(t){let e=b=>{let _=app.vault.getAbstractFileByPath(b);return _ instanceof Vle.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(!Mpt(b))for(let w of[".md",".canvas"]){let x=e(`${b}${w}`);if(x)return{type:"resolved",file:x}}}let c=app.metadataCache,d=u.trim();if(c&&d){let b=new Set([d]);if(!Mpt(d))for(let _ of[".md",".canvas"])b.add(`${d}${_}`);for(let _ of b){let w=c.getFirstLinkpathDest?.(_,"");if(w instanceof Vle.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=$1e(d),m=new Set([p]);if(!Mpt(d))for(let b of[".md",".canvas"])m.add($1e(`${d}${b}`));for(let b of f){let _=$1e(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 g=p.split("/").filter(Boolean);if(g.length===0)return{type:"not_found"};let y=f.filter(b=>NXo(b.path,g));return y.length===1?{type:"resolved",file:y[0]}:y.length>1?{type:"not_unique",matches:y}:{type:"not_found"}}async function DXo(t){try{return await app.vault.cachedRead(t)}catch(e){return Ot(`readNote: failed to read ${t.path}`,e),""}}function $Xo(){let t=new Map,e=app.vault.getMarkdownFiles?.()??[];for(let r of e)if(r instanceof Vle.TFile){let n=t.get(r.basename)??[];n.push(r),t.set(r.basename,n)}return t}function LXo(t,e,r){let n=t.trim();if(!n)return[];let o=new Map,i=app.metadataCache.getFirstLinkpathDest?.(n,e);if(i instanceof Vle.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 FXo(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=$Xo());let p=LXo(d,e.path,o);n.set(f,{linkText:d,displayText:u?.trim()||d,section:c?.trim()||void 0,candidates:p.map(m=>({path:m.path,title:m.basename})),unresolved:p.length===0?!0:void 0})}return Array.from(n.values())}function kXo(t,e){let r=e.split(/\r?\n/),n=r.length===1&&r[0]===""?0:r.length;if(n===0)return[{id:`${t.path}#L1-1`,notePath:t.path,chunkIndex:0,content:"",heading:""}];let o=Math.ceil(n/Ppt),i=[];
`).trimEnd(),heading:d})}return i}var Vle,Ppt,qXo,f4r,p4r=v(()=>{Vle=require("obsidian");yI();Dt();bI();Ppt=200;qXo=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.")}),f4r=Gl({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:qXo,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 jXo(r);if(n.type==="not_found")return Ot(`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 Ot(`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 DXo(o),s=kXo(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];J(`readNote: returning chunk ${l.chunkIndex} of ${u} for ${i}`);let c=l.chunkIndex<u-1,d=FXo(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}}})});var V_,Jle=v(()=>{V_=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()}}});var m4r,h4r,g4r=v(()=>{RS();wr();yI();bI();m4r=5e4,h4r=Gl({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>m4r)return JSON.stringify({success:!1,message:`Input too long: Maximum allowed length is ${m4r} characters`});let r=TAt(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 Ru.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
- Use to browse the vault's file structure
- Use this tool when the user asks for the vault structure, or a specific file or folder but you are unsure about the exact path.
- Use this tool too look up folders when user asks to create new notes under a folder.
- Use this tool to look up files under certain folders.
- 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>`}})}function zXo(){V_.getInstance().register({tool:c4r(),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 HXo(){V_.getInstance().register({tool:R1e,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 L1e(t){let e=V_.getInstance(),r=ce(),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(BXo),t&&(UXo(t),zXo()),r.enableSavedMemory&&HXo())}var BXo,Rpt=v(()=>{Pt();Qdt();nft();d4r();Spt();p4r();uft();wpt();Jle();g4r();BXo=[{tool:Mue,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:Rue,metadata:{id:"webSearch",displayName:"Web Search",description:"Search the internet for information",category:"search",copilotCommands:["@websearch","@web"],customPromptInstructions:`For webSearch:
- Only use when the user explicitly requests web/internet search
- Always provide an empty chatHistory array
Example usage:
<use_tool>
<name>webSearch</name>
<query>piano learning techniques</query>
<chatHistory>[]</chatHistory>
</use_tool>`}},{tool:O1e,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):
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:E1e,metadata:{id:"getTimeInfoByEpoch",displayName:"Get Time Info",description:"Convert epoch timestamp to human-readable format",category:"time",isAlwaysEnabled:!0}},{tool:T1e,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:P1e,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:f4r,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.
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:JNe,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
Example usage:
<use_tool>
<name>writeToFile</name>
<path>path/to/note.md</path>
<content>FULL CONTENT OF THE NOTE</content>
</use_tool>`}},{tool:nBr,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:h4r,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>`}}]});function Dpt(t){return t.map(e=>e.content).filter(e=>e&&e.trim().length>0).join(`
`)}function F1e(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 jpt,mJ,Apt,Ipt,Npt,V7,k1e=v(()=>{Dt();jpt=50;mJ=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 Dpt(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/settings/model.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
When creating a new file in given folder, you must use the getFileTree tool to confirm folder first unless user explicitly ask to create new folders
Example for "create a new note in the projects folder":
1. Call getFileTree to get the exact folder path
2. Use writeToFile with the folder path
Example for "create a new note about topic X":
1. Use writeToFile with the path "topicX.md" for creating the note in the root folder
`}),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
- Only use web search if: the query explicitly asks for web search, OR the query explicitly requires current/web information
- NEVER mention tool names like "localSearch", "webSearch", etc. in your responses. Use natural language like "searching your vault", "searching the web", etc.
You can use multiple tools in sequence. After each tool execution, you'll receive the results and can decide whether to use more tools or provide your final response.
Always explain your reasoning before using tools. Be conversational and clear about what you're doing.
When you've gathered enough information, provide your final response without any tool calls.
IMPORTANT: Do not include any code blocks (\`\`\`) or tool_code blocks in your responses. Only use the <use_tool> format for tool calls.
NOTE: Use individual XML parameter tags. For arrays, use JSON format like ["item1", "item2"].`}),u}enhanceUserMessage(e,r){return e}needsSpecialHandling(){return!1}},Apt=class extends mJ{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}},Ipt=class extends mJ{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>jpt}},Npt=class extends mJ{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
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}},V7=class{static createAdapter(e){let r=(e.modelName||e.model||"").toLowerCase();if(J(`Creating model adapter for: ${r}`),r.includes("gpt")){let n=new Apt(r);return n.isGPT5Model()?J("Using GPTModelAdapter with GPT-5 specific enhancements"):J("Using GPTModelAdapter"),n}return r.includes("claude")?(J("Using ClaudeModelAdapter"),new Ipt(r)):r.includes("gemini")||r.includes("google/gemini")?(J("Using GeminiModelAdapter"),new Npt(r)):r.includes("copilot-plus")?(J("Using BaseModelAdapter for Copilot Plus"),new mJ(r)):(J("Using BaseModelAdapter (default)"),new mJ(r))}}});function VXo(t){let{systemSections:e,rawHistory:r,adapterName:n,originalUserMessage:o,enhancedUserMessage:i}=t,a=[...e];if(r&&r.length>0){let u=zle(r);if(u.length>0){let c=N1e(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 JXo(t){return t.map(e=>`${`[Section: ${e.label} | Source: ${e.source}]`}
${e.content}`).join(`
`)}function y4r(t){let e=VXo(t),r=JXo(e),n=Dpt(t.systemSections);return{sections:e,annotatedPrompt:r,systemPrompt:n}}var b4r=v(()=>{k1e();j1e()});async function KXo(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=F1e(s.message),m=r.enhanceUserMessage(s.message,p);return y4r({systemSections:u,rawHistory:d,adapterName:r.constructor?.name||"ModelAdapter",originalUserMessage:f,enhancedUserMessage:m})}async function WXo(t){return PN(t.userMemoryManager)}async function _4r(t){let{chainManager:e,adapter:r,availableTools:n,toolDescriptions:o,userMessage:i}=t,a=V_.getInstance(),s=n.map(c=>c.name),u=n.map(c=>a.getToolMetadata(c.name)).filter(c=>c!==void 0),l=await WXo(e);return KXo({chainManager:e,adapter:r,basePrompt:l,toolDescriptions:o,toolNames:s,toolMetadata:u,userMessage:i})}var v4r=v(()=>{Pt();Jle();k1e();b4r()});function GXo(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 w4r(t){let{messages:e,modelName:r}=t;try{J7={timestamp:new Date().toISOString(),modelName:r,serializedMessages:GXo(e)}}catch{J7={timestamp:new Date().toISOString(),modelName:r,serializedMessages:String(e)}}}function K7(){J7=null}async function q1e(){if(!J7)return;let{timestamp:t,modelName:e,serializedMessages:r}=J7,n=[`### Agent Prompt Payload \u2014 ${t}${e?` (model: ${e})`:""}`];Lhe([...n,"```json",r,"```",""]),J7=null}var J7,W7=v(()=>{Dt();J7=null});function B1e(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){Ot("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]=$pt(p,f))}a||Ot(`Detected partial tool call block for tool "${s}" - treating as best effort parse`),e.push({name:s,args:u})}}}catch(r){return ue("Error parsing XML tool calls:",r),[]}return e}function $pt(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 $pt(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,$pt(u)])}return i.length>0?Object.fromEntries(i):t}function S4r(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 Kle(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 Lpt=v(()=>{Dt()});var Wle,C4r=v(()=>{Dt();$v();Pt();Rpt();bI();Jle();Eue();wr();NOe();$s();D1e();j1e();k1e();wH();bie();Pue();Tpt();v4r();W7();Lpt();Wle=class t extends vI{constructor(){super(...arguments);this.llmFormattedMessages=[];this.lastDisplayedContent=""}getAvailableTools(){let r=ce(),n=V_.getInstance();n.getAllTools().length===0&&L1e(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=eBr(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 PN(o),a=t.generateToolDescriptions(r),s=r.map(c=>c.name),u=V_.getInstance(),l=r.map(c=>u.getToolMetadata(c.name)).filter(c=>c!==void 0);return n.enhanceSystemPrompt(i,a,s,l)}async generateSystemPrompt(){let r=this.getAvailableTools(),n=this.chainManager.chatModelManager.getChatModel(),o=V7.createAdapter(n);return t.generateSystemPrompt(r,o,this.chainManager.userMemoryManager)}async buildToolPromptDebugReport(r){let n=this.getAvailableTools(),o=V7.createAdapter(this.chainManager.chatModelManager.getChatModel()),i=t.generateToolDescriptions(n);return _4r({chainManager:this.chainManager,adapter:o,availableTools:n,toolDescriptions:i,userMessage:r})}applyCiCOrderingToLocalSearchResult(r,n){let o=ce(),i=o4r(n,!!o?.enableInlineCitations);return i4r(r,i)}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 jS({isAutonomousAgent:!0}),c=this.chainManager.chatModelManager.getChatModel(),d=V7.createAdapter(c),f=new M_(o,d);if(!l){await this.handleError(new Error("Invalid license key"),f.processErrorChunk.bind(f));let h=f.close().content;return this.handleResponse(h,r,n,i,o,void 0)}let p=c?.modelName,m=await this.prepareAgentConversation(r,d,c);try{let h=await this.executeAgentLoop({...m,adapter:d,abortController:n,updateCurrentAiMessage:o});s=h.fullAIResponse,u=h.responseMetadata,m.iterationHistory=h.iterationHistory,m.collectedSources=h.collectedSources,this.llmFormattedMessages=h.llmMessages}catch(h){if(h.name==="AbortError"||n.signal.aborted)J("Autonomous agent stream aborted by user",{reason:n.signal.reason});else{ue("Autonomous agent failed, falling back to regular Plus mode:",h);try{return await new vI(this.chainManager).run(r,n,o,i,a)}catch(g){ue("Fallback to regular Plus mode also failed:",g),this.lastDisplayedContent&&f.processChunk({content:this.lastDisplayedContent});let y=Eo(h),b=`
Fallback to regular Plus mode also failed: `+Eo(g);return await this.handleError(new Error(y+b),f.processErrorChunk.bind(f)),s=f.close().content,this.handleResponse(s,r,n,i,o,void 0,s)}}}return await this.finalizeAgentRun({...m,userMessage:r,abortController:n,addMessage:i,updateCurrentAiMessage:o,modelNameForLog:p,responseMetadata:u,fullAIResponse:s})}async prepareAgentConversation(r,n,o){let i=[],a=[],s=[],l={availableTools:this.getAvailableTools(),getTemporaryToolCallId:this.getTemporaryToolCallId.bind(this),processLocalSearchResult:this.processLocalSearchResult.bind(this),applyCiCOrderingToLocalSearchResult:this.applyCiCOrderingToLocalSearchResult.bind(this)},f=(await this.chainManager.memoryManager.getMemory().loadMemoryVariables({})).history||[],p=await this.generateSystemPrompt();p&&i.push({role:wL(o),content:p}),I1e(f,i);let m=this.isMultimodalModel(o),h=F1e(r.message),g=n.enhanceUserMessage(r.message,h),y=m?await this.buildMessageContent(g,r):g;return i.push({role:"user",content:y}),{conversationMessages:i,iterationHistory:a,collectedSources:s,originalUserPrompt:r.originalMessage||r.message,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=ce().autonomousAgentMaxIterations,g=0,y="",b;for(;g<h&&!this.isAbortRequested(l);){g+=1,J(`=== Autonomous Agent Iteration ${g} ===`);let _=[],w=await this.streamResponse(n,l,H=>this.updateStreamingDisplay(H,d,_,c,s),u);b={wasTruncated:w.wasTruncated,tokenUsage:w.tokenUsage??void 0};let x=w.content;if(!x)break;let O=B1e(x),E=u.detectPrematureResponse?.(x);if(E?.hasPremature&&g===1&&(E.type==="before"?(Ot("\u26A0\uFE0F Model provided premature response BEFORE tool calls!"),Ot("Sanitizing response to keep only tool calls for first iteration")):E.type==="after"&&(Ot("\u26A0\uFE0F Model provided hallucinated response AFTER tool calls!"),Ot("Truncating response at last tool call for first iteration"))),O.length===0){let H=Kle(x),G=[...d];H.trim()&&G.push(H),y=G.join(`
`);let ie=AOe(x);n.push({role:"assistant",content:ie}),p.push(x);break}let T=x;u.sanitizeResponse&&E?.hasPremature&&(T=u.sanitizeResponse(x,g));let R=Kle(T);R.trim()&&d.push(R);let N=[],D=new Map;_.splice(O.length);for(let H=0;H<O.length;H+=1){let G=O[H];if(this.isAbortRequested(l))break;ift(G,g);let oe=m.find(re=>re.name===G.name)?.isBackground||!1,z;if(!oe){let re=g7(G.name),Z=nJ(G.name);if(G.name==="readNote"){let j=typeof G.args?.notePath=="string"?G.args.notePath:null;j&&j.trim().length>0&&(Z=KNe(j))}let $=iBr(G.name);z=`${G.name}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,D.set(H,z);let q=IOe(z,G.name,Z,re,$||"",!0,"",""),Y=_.findIndex(j=>j.includes(s.getTemporaryToolCallId(G.name,H)));Y!==-1?_[Y]=q:(_.push(q),Ot("Created tool call marker for tool call that was not created during streaming",G.name)),c([...d,..._].join(`
`))}let Q=await oft(G,m,a);if(Q.success||(Q.displayResult=rG(Q.result,"Tool execution failed")),G.name==="localSearch"){if(Q.success){let re=s.processLocalSearchResult(Q);f.push(...re.sources),Q.result=s.applyCiCOrderingToLocalSearchResult(re.formattedForLLM,a||""),Q.displayResult=re.formattedForDisplay}}else G.name==="readNote"&&Q.success&&(Q.displayResult=px.format("readNote",Q.result));if(N.push(Q),z&&!oe){let re=_.findIndex(Z=>Z.includes(z));re!==-1&&(_[re]=got(_[re],z,Q.displayResult??Q.result)),c([...d,..._].join(`
`))}aft(G.name,Q)}_.length>0&&d.push(_.join(`
`));let F=T;if(p.push(F),N.length>0){let H=bot(N,!0);H&&p.push(H)}let B=AOe(T);n.push({role:"assistant",content:B});let U=bot(N,!1);n.push({role:"user",content:U}),J("Tool results added to conversation")}if(g>=h&&!y){Ot(`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.`;y=d.join(`
`)+_,n.push({role:"assistant",content:y})}return{fullAIResponse:y,responseMetadata:b,iterationHistory:d,collectedSources:f,llmMessages:p}}updateStreamingDisplay(r,n,o,i,a){let s=Kle(r),u=[...n];s.trim()&&u.push(s);let l=B1e(r),c=new Set(a.availableTools.filter(h=>h.isBackground).map(h=>h.name)),d=[];l.forEach(h=>{c.has(h.name)||d.push(h.name)});let f=S4r(r);if(f){let h=r.lastIndexOf(f);r.length-h>jpt&&d.push(f)}Array.from(new Set(d)).forEach((h,g)=>{let y=a.getTemporaryToolCallId(h,g);if(o.findIndex(w=>w.includes(y))!==-1)return;let _=IOe(y,h,nJ(h),g7(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=eB(i);!p&&o.length>0&&(Ot("fullAIResponse was empty, using iteration history"),p=o.join(`
`)),n.length>0&&w4r({messages:[...n],modelName:c}),await Promise.resolve().then(()=>(bie(),yot));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=new M_(o,i),s=2,u=0;for(;u<=s;)try{let c=r.map(p=>p.role==="user"?new su(p.content):new li(p.content)),d=await Xh(()=>this.chainManager.chatModelManager.getChatModel().stream(c,{signal:n.signal}));for await(let p of d){if(n.signal.aborted)break;a.processChunk(p)}let f=a.close();return{content:f.content,wasTruncated:f.wasTruncated,tokenUsage:f.tokenUsage}}catch(c){if(c.name==="AbortError"||n.signal.aborted){let f=a.close();return{content:f.content,wasTruncated:f.wasTruncated,tokenUsage:f.tokenUsage}}if((c?.message?.includes("overloaded")||c?.message?.includes("Overloaded")||c?.error?.type==="overloaded_error")&&u<s){u++,J(`Retrying autonomous agent request (attempt ${u}/${s+1}) due to overloaded error`),await new Promise(f=>setTimeout(f,1e3*u));continue}throw c}let l=a.close();return{content:l.content,wasTruncated:l.wasTruncated,tokenUsage:l.tokenUsage}}}});var x4r=v(()=>{vie();Xhr();qqr();D1e();a4r();C4r();wH();Lpt();Pue()});var ZXo,O4r,XXo,T4r,YXo,E4r,QXo,P4r,U1e=v(()=>{Tv();ZXo=`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:`,O4r=new uu({inputVariables:["summary","new_lines"],template:ZXo}),XXo=`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:`,T4r=new uu({inputVariables:["entities","history","input"],template:XXo}),YXo=`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:`,E4r=new uu({inputVariables:["history","input"],template:YXo}),QXo=`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):`,P4r=new uu({inputVariables:["entity","summary","history","input"],template:QXo})});var eYo,tYo,M4r,Gle,Fpt=v(()=>{Do();V$();V0();G$();$s();eYo={};Et(eYo,{BaseChatMessageHistory:()=>tYo,BaseListChatMessageHistory:()=>M4r,InMemoryChatMessageHistory:()=>Gle});tYo=class extends Vh{async addMessages(t){for(let e of t)await this.addMessage(e)}},M4r=class extends Vh{addUserMessage(t){return this.addMessage(new su(t))}addAIMessage(t){return this.addMessage(new li(t))}async addMessages(t){for(let e of t)await this.addMessage(e)}clear(){throw new Error("Not implemented.")}},Gle=class extends M4r{constructor(e){super(...arguments);M(this,"lc_namespace",["langchain","stores","message","in_memory"]);M(this,"messages",[]);this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}}});function z1e(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 rYo,hJ,R4r,gJ,Zle,Xle=v(()=>{Do();rYo={};Et(rYo,{BaseMemory:()=>hJ,getInputValue:()=>gJ,getOutputValue:()=>Zle,getPromptInputKey:()=>z1e});hJ=class{},R4r=(t,e)=>{if(e!==void 0)return t[e];let r=Object.keys(t);if(r.length===1)return t[r[0]]},gJ=(t,e)=>{let r=R4r(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},Zle=(t,e)=>{let r=R4r(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 nYo,Ab,xB=v(()=>{Rhe();Fpt();Xle();nYo={};I6(nYo,{BaseChatMemory:()=>Ab});Ab=class extends hJ{constructor(e){super();M(this,"chatHistory");M(this,"returnMessages",!1);M(this,"inputKey");M(this,"outputKey");this.chatHistory=e?.chatHistory??new Gle,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(gJ(e,this.inputKey)),await this.chatHistory.addAIMessage(Zle(r,this.outputKey))}async clear(){await this.chatHistory.clear()}}});function kpt(t,e){let r=new Set;for(let n of e)t.has(n)&&r.add(n);return r}function A4r(t,e){let r=new Set(t);for(let n of e)r.add(n);return r}function Yle(t,e){let r=new Set(t);for(let n of e)r.delete(n);return r}var I4r=v(()=>{});var qpt={};Xn(qpt,{SequentialChain:()=>oYo,SimpleSequentialChain:()=>iYo});function Qle(t){return Array.from(t).map(e=>`"${e}"`).join(", ")}var oYo,iYo,Bpt=v(()=>{G7();I4r();oYo=class N4r extends jy{constructor(r){super(r);M(this,"chains");M(this,"inputVariables");M(this,"outputVariables");M(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=kpt(n,o);if(i.size>0)throw new Error(`The following keys: ${Qle(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=A4r(n,o);for(let s of this.chains){let u=Yle(new Set(s.inputKeys),a);if(s.memory&&(u=Yle(u,new Set(s.memory.memoryKeys))),u.size>0)throw new Error(`Missing variables for chain "${s._chainType()}": ${Qle(u)}. Only got the following variables: ${Qle(a)}.`);let l=new Set(s.outputKeys),c=kpt(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 D4r({llmChain:await Ih.deserialize(r.llm_chain)})}serialize(){return{_type:this._chainType(),llm_chain:this.llmChain.serialize()}}},$4r=class L4r extends jy{constructor(r){super(r);M(this,"llmChain");M(this,"inputKey","input_documents");M(this,"documentVariableName","context");M(this,"returnIntermediateSteps",!1);M(this,"maxTokens",3e3);M(this,"maxIterations",10);M(this,"ensureMapStep",!1);M(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,g)=>n.getChild(`map_${g+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 L4r({llmChain:await Ih.deserialize(r.llm_chain),combineDocumentChain:await H1e.deserialize(r.combine_document_chain)})}serialize(){return{_type:this._chainType(),llm_chain:this.llmChain.serialize(),combine_document_chain:this.combineDocumentChain.serialize()}}},F4r=class k4r extends jy{constructor(r){super(r);M(this,"llmChain");M(this,"inputKey","input_documents");M(this,"outputKey","output_text");M(this,"documentVariableName","context");M(this,"initialResponseName","existing_answer");M(this,"refineLLMChain");M(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 uu({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"]}),uYo=`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}`,lYo=[Gw.fromTemplate(uYo),a_.fromTemplate("{question}")],cYo=hd.fromMessages(lYo),G4r=new X7(sYo,[[Y7,cYo]])});var X4r=v(()=>{Tv();K1e()});var Y4r=v(()=>{Tv();K1e()});function Q4r(t,e={}){let{prompt:r=G4r.getPrompt(t),verbose:n}=e,o=new Ih({prompt:r,llm:t,verbose:n});return new H1e({llmChain:o,verbose:n})}var e2r=v(()=>{yJ();ece();Z4r();X4r();Y4r()});var r2r={};Xn(r2r,{VectorDBQAChain:()=>dYo});var dYo,n2r=v(()=>{G7();e2r();dYo=class t2r extends jy{constructor(r){super(r);M(this,"k",4);M(this,"inputKey","query");M(this,"vectorstore");M(this,"combineDocumentsChain");M(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 t2r({combineDocumentsChain:await jy.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=Q4r(r);return new this({vectorstore:n,combineDocumentsChain:i,...o})}}});var o2r,i2r,fYo,a2r,s2r=v(()=>{Tv();o2r=`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:`,i2r=new uu({inputVariables:["api_docs","question"],template:o2r}),fYo=`${o2r} {api_url}
Here is the response from the API:
{api_response}
Summarize this response to answer the original question.
Summary:`,a2r=new uu({inputVariables:["api_docs","question","api_url","api_response"],template:fYo})});var l2r={};Xn(l2r,{APIChain:()=>pYo});var pYo,c2r=v(()=>{G7();yJ();s2r();pYo=class u2r extends jy{constructor(r){super(r);M(this,"apiAnswerChain");M(this,"apiRequestChain");M(this,"apiDocs");M(this,"headers",{});M(this,"inputKey","question");M(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 u2r({apiAnswerChain:await Ih.deserialize(o),apiRequestChain:await Ih.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=i2r,apiResponsePrompt:a=a2r}=o,s=new Ih({prompt:i,llm:r}),u=new Ih({prompt:a,llm:r});return new this({apiAnswerChain:u,apiRequestChain:s,apiDocs:n,...o})}}});var jy,G7=v(()=>{xv();Wv();ym();X$();jy=class extends jW{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=Jo(e),n=await this._formatValues(t),i=await(await Yl.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{a=await(n.signal?Promise.race([this._call(n,i,r),new Promise((s,u)=>{n.signal?.addEventListener("abort",()=>{u(new Error("AbortError"))})})]):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,dN,{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,...lN(e)};return this.invoke(t,n)}async apply(t,e){return Promise.all(t.map(async(r,n)=>this.call(r,e?.[n])))}static async deserialize(t,e={}){switch(t._type){case"
`);await this.vectorStoreRetriever.addDocuments([new jm({pageContent:o,metadata:n})])}}});var S2r,C2r=v(()=>{V$();S2r=class extends Vh{}});var x2r,O2r=v(()=>{C2r();x2r=class extends S2r{constructor(){super();M(this,"lc_namespace",["langchain","stores","entity","in_memory"]);M(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 T2r,E2r=v(()=>{yJ();U1e();xB();O2r();$s();Xle();T2r=class extends Ab{constructor(e){super({chatHistory:e.chatHistory,returnMessages:e.returnMessages??!1,inputKey:e.inputKey,outputKey:e.outputKey});M(this,"entityExtractionChain");M(this,"entitySummarizationChain");M(this,"entityStore");M(this,"entityCache",[]);M(this,"k",3);M(this,"chatHistoryKey","history");M(this,"llm");M(this,"entitiesKey","entities");M(this,"humanPrefix");M(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 Ih({llm:this.llm,prompt:e.entityExtractionPrompt??E4r}),this.entitySummarizationChain=new Ih({llm:this.llm,prompt:e.entitySummarizationPrompt??P4r}),this.entityStore=e.entityStore??new x2r,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??z1e(e,this.memoryVariables),n=await this.chatHistory.getMessages(),o=rl(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??z1e(e,this.memoryVariables),o=await this.chatHistory.getMessages(),i=rl(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 P2r,M2r=v(()=>{xB();P2r=class extends Ab{constructor(e){super({chatHistory:e?.chatHistory,returnMessages:e?.returnMessages??!1,inputKey:e?.inputKey,outputKey:e?.outputKey});M(this,"humanPrefix","Human");M(this,"aiPrefix","AI");M(this,"memoryKey","history");M(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 R2r,A2r=v(()=>{xB();$s();R2r=class extends Ab{constructor(e){super(e);M(this,"humanPrefix","Human");M(this,"aiPrefix","AI");M(this,"memor
Answer the question with as detailed as possible based only on the following context:
{context}
Question: {question}
`;this.qaPrompt=hd.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 X1e,oce,j2r=v(()=>{Tu();gd();zr();x4r();Dt();Pt();wr();Tv();X1e=require("obsidian");hue();I2r();N2r();M1e();oce=class{constructor(e){this.retrievedDocuments=[];this.app=e,this.memoryManager=rce.getInstance(),this.chatModelManager=gI.getInstance(),this.promptManager=nce.getInstance(),this.userMemoryManager=new CB(e),this.initialize(),Ou(async()=>{await this.createChainWithNewModel()})}getRetrievedDocuments(){return this.retrievedDocuments}async initialize(){await this.createChainWithNewModel()}getChain(){return this.chain}getRetrievalChain(){return this.retrievalChain}validateChainType(e){if(e==null)throw new Error("No chain type set")}validateChatModel(){if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){let e="Chat model is not initialized properly, check your API key in Copilot setting and make sure you have API access.";throw new X1e.Notice(e),new Error(e)}}validateChainInitialization(){(!this.chain||!vAt(this.chain))&&(J("Reinitializing chat chain after detecting missing or unsupported instance."),this.createChainWithNewModel({},!1))}storeRetrieverDocuments(e){this.retrievedDocuments=e}async createChainWithNewModel(e={},r=!0){let n=jN(),o=tc();if(n==="project"&&!o)return;let i=n==="project"?o?.projectModelKey:eK();if(!i)throw new X1e.Notice("No model key found"),new Error("No model key found");try{if(r){let a=qhe(i,ce().activeModels);if(a||(console.error("Resetting default model. No model configuration found for: ",i),a=SO[0],i=a.name+"|"+a.provider),n==="project"&&!a.projectEnabled){let u=ce().activeModels.find(l=>l.enabled&&l.projectEnabled);if(u)a=u,i=u.name+"|"+u.provider,new X1e.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,...o?.modelConfigs};await this.chatModelManager.setChatModel(s)}this.setChain(n,e),J(`Setting model to ${i}`)}catch(a){ue(`createChainWithNewModel failed: ${a}`),J(`modelKey: ${i}`)}}async setChain(e,r={}){if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){console.error("setChain failed: No chat model set.");return}this.validateChainType(e);let n=this.chatModelManager.getChatModel(),o=this.memoryManager.getMemory(),i=this.promptManager.getChatPrompt();switch(e){case"llm_chain":{this.chain=oee.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),Hz("llm_chain");break}case"vault_qa":{await this.initializeQAChain(r);let a=ce(),s=a.enableSemanticSearchV3?new(await Promise.resolve().then(()=>($Ne(),Udt))).HybridRetriever({minSimilarityScore:.01,maxK:a.maxSourceChunks,salientTerms:[]}):new(await Promise.resolve().then(()=>(m7(),DNe))).TieredLexicalRetriever(app,{minSimilarityScore:.01,maxK:a.maxSourceChunks,salientTerms:[],timeRange:void 0,textWeight:void 0,returnAll:!1,useRerankerThreshold:void 0});this.retrievalChain=oee.createConversationalRetrievalChain({llm:n,retriever:s,systemMessage:Y0()},this.storeRetrieverDocuments.bind(this),ce().debug),Hz("vault_qa"),ce().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=oee.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),Hz("copilot_plus");break}case"project":{await this.initializeQAChain(r),this.chain=oee.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),Hz("project");break}default:this.validateChainType(e);break}}getChainRunner(){let e=jN(),r=ce();switch(e){case"llm_chain":return new wie(this);case"vault_qa":return new _ue(this);case"copilot_plus":return r.enableAutonom
`,e),this.validateChatModel(),this.validateChainInitialization();let s=this.chatModelManager.getChatModel();if(a||ree(s)){let l=hd.fromMessages([new vO("history"),a_.fromTemplate("{input}")]);ree(s)&&(l=hd.fromMessages([[Xs,Y0()||""],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===Xs&&await this.memoryManager.getMemory().saveContext({input:n.message},{output:o.message})}}}});var Y1e,D2r=v(()=>{Tu();Dt();Pt();wr();gie();Y1e=class t{constructor(e){this.app=e}static getInstance(e){return t.instance||(t.instance=new t(e)),t.instance}clearAllLoadStates(){dIt({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=X1(o)?"Rate limit exceeded. (Rate limit: 50 files or 100MB per 3 hours, whichever is reached first)":Eo(o);throw this.setFileOrUrlProcessFailed(e,r,i),o}}setFileOrUrlStartProcess(e){ei.set(fee,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){AO("processingFiles",r=>r.filter(n=>n!==e)),AO("success",r=>r.includes(e)?r:[...r,e])}setFileOrUrlProcessFailed(e,r,n){AO("processingFiles",o=>o.filter(i=>i!==e)),AO("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){J(`[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])];AO("total",s=>a),J(`[preComputeAllItems] Project ${e.name}: Added ${n.length} items to tracking (${a.length} total unique items)`)}}markAllCachedItemsAsSuccess(e,r,n){J(`[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&&J(`[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&&J(`[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&&J(`[markAllCachedItemsAsSuccess] Project ${e.name}: Marked ${s.length} cached files that match current project patterns as successful.`)}}markCachedItemAsSuccess(e){AO("total",r=>r.includes(e)?r:[...r,e]),AO("success",r=>r.includes(e)?r:[...r,e])}makeItemFailed(e,r,n){AO("total",o=>o.includes(e)?o:[...o,e]),AO("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 bJ,Rg,Xq=v(()=>{Tu();hie();gd();zr();Dt();lot();vb();Pt();ROe();wr();gie();bJ=require("obsidian");RS();j2r();D2r();Rg=class t{constructor(e,r){this.app=e,this.plugin=r,this.currentProjectId=null,this.chainMangerInstance=new oce(e),this.projectContextCache=UC.getInstance(),this.fileParserManager=new Ik(Ru.getInstance(),this.app.vault,!0,null),this.loadTracker=Y1e.getInstance(this.app),iIt(async()=>{await this.getCurrentChainManager().createChainWithNewModel()}),aIt(async()=>{if(Jz())return;let n=ce(),o=n.enableSemanticSearchV3&&n.indexVaultToVectorStore==="ON MODE SWITCH"&&(jN()==="vault_qa"||jN()==="copilot_plus");await this.getCurrentChainManager().createChainWithNewModel({refreshIndex:o})}),tK(async n=>{await this.switchProject(n)}),this.setupProjectListChangeMonitor()}setupProjectListChangeMonitor(){Ou(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&&JSON.stringify(a)!==JSON.stringify(i)&&(await this.compareAndUpdateCache(a,i),this.currentProjectId===i.id&&await Promise.all([this.loadProjectContext(i,!0),this.getCurrentChainManager().createChainWithNewModel()]))}})}static getInstance(e,r){return t.instance||(t.instance=new t(e,r)),t.instance}getCurrentChainManager(){return this.chainMangerInstance}getCurrentProjectId(){return this.currentProjectId}async switchProject(e){try{if(this.loadTracker.clearAllLoadStates(),RO(!0),J("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 Ik(Ru.getInstance(),this.app.vault,!0,e),await this.loadProjectContext(e),this.refreshChatView(),J(`Switched to project: ${e.name}`)}catch(r){throw ue(`Failed to switch project: ${r}`),r}finally{RO(!1)}}async saveCurrentProjectMessage(){await this.plugin.autosaveCurrentChat()}async loadNextProjectMessage(){await this.plugin.chatUIState.handleProjectSwitch()}async loadProjectContext(e,r=!1){r&&(this.loadTracker.clearAllLoadStates(),RO(!0));try{if(!e.contextSource)return Ot(`[loadProjectContext] Project ${e.name}: No contextSource. Aborting.`),null;J(`[loadProjectContext] Starting for project: ${e.name}`);let n=await this.projectContextCache.getOrInitializeCache(e),o=this.getProjectAllFiles(e);this.loadTracker.preComputeAllItems(e,o),this.loadTracker.markAllCachedItemsAsSuccess(e,n,o);let[i]=await Promise.all([this.processMarkdownFiles(e,n,o),this.processWebUrls(e,n),this.processYoutubeUrls(e,n)]);return i.timestamp=Date.now(),await this.projectContextCache.setCacheSafely(e,i),await this.processNonMarkdownFiles(e,o),J(`[loadProjectContext] Completed for project: ${e.name}.`),i}catch(n){throw ue(`[loadProjectContext] Failed for project ${e.name}:`,n),n}finally{r&&RO(!1)}}async compareAndUpdateCache(e,r){try{if(!await this.projectContextCache.get(e))return!0;let o=e.contextSource?.inclusions||"",i=r.contextSource?.inclusions||"",a=e.contextSource?.exclusions||"",s=r.contextSource?.exclusions||"";(o!==i||
`).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){ue(`Error comparing project configurations: ${n}`)}}refreshChatView(){let e=this.app.workspace.getLeavesOfType(Tc)[0]?.view;e&&e.updateView()}async getProjectContext(e){let r=ce().projectList.find(o=>o.id===e);if(!r)return Ot(`[getProjectContext] Project not found for ID: ${e}`),null;J(`[getProjectContext] Getting context for project: ${r.name} (ID: ${e})`);let n=this.projectContextCache.getSync(r);if(!n||n.markdownNeedsReload){n?J(`[getProjectContext] Project ${r.name}: Markdown needs reload. Triggering full load.`):J(`[getProjectContext] Project ${r.name}: Memory cache miss. Triggering full load.`);let o=await this.loadProjectContext(r,!0);if(!o)return ue(`[getProjectContext] Project ${r.name}: loadProjectContext returned null.`),null;n=o}else J(`[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(J(`[processMarkdownFiles] Starting for project: ${e.name}`),r.markdownNeedsReload||!r.markdownContext||!r.markdownContext.trim()){J(`[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,J(`[processMarkdownFiles] Project ${e.name}: Markdown content updated.`)}else J(`[processMarkdownFiles] Project ${e.name}: Markdown content already up-to-date.`);return J(`[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");J(`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,J(`Completed processing markdown file: ${o.path}`)}catch(s){ue(`Error processing file ${o.path}: ${s}`),i=`[Error: ${Eo(s)}]`}return`${a}
${i}`}));return J("All markdown files processed for project context"),n.join(`
`)}async processWebUrls(e,r){J(`[processWebUrls] Starting for project: ${e.name}`);let n=e.contextSource?.webUrls?.trim()||"";if(!n)return Object.keys(r.webContexts).length>0&&(J(`[processWebUrls] Project ${e.name}: Clearing all Web contexts as none are configured.`),r.webContexts={}),r;let o=n.split(`
`).filter(c=>c.trim());J(`[processWebUrls] Project ${e.name}: Found ${o.length} URLs in config.`);let i=Object.keys(r.webContexts),a=o.filter(c=>!r.webContexts[c]);a.length>0&&J(`[processWebUrls] Project ${e.name}: Fetching content for ${a.length} new/updated Web URLs.`);let s=i.filter(c=>!o.includes(c));if(s.length>0){J(`[processWebUrls] Project ${e.name}: Removing ${s.length} obsolete Web URL contexts.`);for(let c of s)delete r.webContexts[c]}let u=a.map(async c=>{let d=await this.processWebUrlContext(c);return d&&J(`[processWebUrls] Project ${e.name}: Successfully fetched content for URL: ${c.substring(0,50)}...`),{url:c,context:d}});return(await Promise.all(u)).forEach(c=>{c&&c.context?r.webContexts[c.url]=c.context:c&&!c.context&&Ot(`[processWebUrls] Project ${e.name}: Fetched empty content for Web URL: ${c.url}`)}),J(`[processWebUrls] Completed for project: ${e.name}. Total Web contexts: ${Object.keys(r.webContexts).length}`),r}async processYoutubeUrls(e,r){J(`[processYoutubeUrls] Starting for project: ${e.name}`);let n=e.contextSource?.youtubeUrls?.trim()||"";if(!n)return Object.keys(r.youtubeContexts).length>0&&(J(`[processYoutubeUrls] Project ${e.name}: Clearing all YouTube contexts as none are configured.`),r.youtubeContexts={}),r;let o=n.split(`
`).filter(c=>c.trim());J(`[processYoutubeUrls] Project ${e.name}: Found ${o.length} YouTube URLs in config.`);let i=Object.keys(r.youtubeContexts),a=o.filter(c=>!r.youtubeContexts[c]);a.length>0&&J(`[processYoutubeUrls] Project ${e.name}: Fetching transcripts for ${a.length} new/updated YouTube URLs.`);let s=i.filter(c=>!o.includes(c));if(s.length>0){J(`[processYoutubeUrls] Project ${e.name}: Removing ${s.length} obsolete YouTube URL contexts.`);for(let c of s)delete r.youtubeContexts[c]}let u=a.map(async c=>{let d=await this.processYoutubeUrlContext(c);return d&&J(`[processYoutubeUrls] Project ${e.name}: Successfully fetched transcript for YouTube URL: ${c.substring(0,50)}...`),{url:c,context:d}});return(await Promise.all(u)).forEach(c=>{c&&c.context?r.youtubeContexts[c.url]=c.context:c&&!c.context&&Ot(`[processYoutubeUrls] Project ${e.name}: Fetched empty transcript for YouTube URL: ${c.url}`)}),J(`[processYoutubeUrls] Completed for project: ${e.name}. Total YouTube contexts: ${Object.keys(r.youtubeContexts).length}`),r}async processWebUrlContext(e){if(!e?.trim())return"";try{let r=eG.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 ue(`Failed to process web URL: ${r}`),""}}async processYoutubeUrlContext(e){if(!e?.trim())return"";try{let r=await this.loadTracker.executeWithProcessTracking(e,"youtube",async()=>Ru.getInstance().youtube4llm(e));return r.response.transcript?`
YouTube transcript from ${e}:
${r.response.transcript}`:""}catch(r){return ue(`Failed to process YouTube URL ${e}: ${r}`),new bJ.Notice(`Failed to process YouTube URL ${e}: ${Eo(r)}`),""}}async processNonMarkdownFiles(e,r){let n=r.filter(i=>i.extension!=="md");if(J(`[loadProjectContext] Project ${e.name}: Checking for non-markdown processing: ${n.length} files .`),n.length<=0)return;this.fileParserManager=new Ik(Ru.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)||(J(`[loadProjectContext] Project ${e.name}: Parsing/caching new/updated file: ${a}`),await this.fileParserManager.parseFile(i,this.app.vault)),o++})}catch(s){if(ue(`[loadProjectContext] Project ${e.name}: Error parsing file ${a}:`,s),X1(s))throw s}}o>0&&J(`[loadProjectContext] Project ${e.name}: Processed and cached ${o} non-markdown files.`)}async retryFailedItem(e){try{if(!this.currentProjectId){Ot("[retryFailedItem] No current project, aborting retry");return}let r=ce().projectList.find(n=>n.id===this.currentProjectId);if(!r){ue(`[retryFailedItem] Current project not found: ${this.currentProjectId}`);return}switch(J(`[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:Ot(`[retryFailedItem] Unknown item type: ${e.type}`);return}J(`[retryFailedItem] Successfully retried ${e.type} item: ${e.path}`),new bJ.Notice(`Retry successful: ${e.path}`)}catch(r){ue(`[retryFailedItem] Failed to retry ${e.type} item ${e.path}:`,r),new bJ.Notice(`Retry failed: ${Eo(r)}`)}}async retryWebUrl(e,r){let n=await this.processWebUrlContext(r);if(!n){Ot(`[retryWebUrl] Project ${e.name}: Fetched empty content for Web URL: ${r}`);return}J(`[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){Ot(`[retryYoutubeUrl] Project ${e.name}: Fetched empty transcript for YouTube URL: ${r}`);return}J(`[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 bJ.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()=>{}),J(`[retryMarkdownFile] Successfully reprocessed markdown file: ${r}`),await this.projectContextCache.invalidateMarkdownContext(e)}catch(o){throw ue(`[retryMarkdownFile] Error processing file ${r}: ${o}`),o}}async retryNonMarkdownFile(e,r){let n=this.app.vault.getAbstractFileByPath(r);if(!(n instanceof bJ.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)),J(`[retryNonMarkdownFile] Successfully reprocessed non-markdown file: ${r}`)}catch(o){throw ue(`[retryNonMarkdownFile] Error processing file ${r}: ${o}`),o}}getProjectAllFiles(e){let{inclusions:r,exclusions:n}=id({inclusions:e.contextSource.inclusions,exclusions:e.contextSource.exclusions,isProject:!0});return this.app.vault.getFiles().filter(o=>ml(o,r,n,!0))}onunload(){this.projectContextCache.cleanup()}}});var $2r={};Xn($2r,{AutocompleteCache:()=>ice});var ice,Jpt=v(()=>{Dt();ice=class t{constructor(){this.cache=new Map,this.maxSize=200,this.ttlMs=10*60*1e3}static getInstance(){return t.instance||(t.instance=new t),t.instance}get(e){let r=this.cache.get
`)&&a.startsWith(`
`)&&(a=a.substring(1)),a}},emt=class{process(e){let{completion:r,context:n}=e;if(n==="CodeBlock"){let o=r;return o=o.replace(/```[a-zA-Z]*[ \t]*\n?/g,""),o=o.replace(/\n?```[ \t]*\n?/g,""),o.endsWith(`
`)&&(o=o.slice(0,-1)),o}return r}},tje=class{constructor(){this.processors=[];this.processors.push(new emt),this.processors.push(new Ypt),this.processors.push(new Qpt)}process(e,r,n,o){let a={prefix:e,suffix:r,completion:n,context:o};for(let s of this.processors)a.completion=s.process(a);return a.completion}};iee();var q2r=require("obsidian");function B2r(t,e=20){let r=app.metadataCache.getFileCache(t),n=[];if(r?.links)for(let o of r.links){let i=app.metadataCache.getFirstLinkpathDest(o.link,t.path);if(i&&(n.push(i),n.length>=e))break}if(r?.embeds&&n.length<e)for(let o of r.embeds){let i=app.metadataCache.getFirstLinkpathDest(o.link,t.path);if(i&&(n.push(i),n.length>=e))break}return[...new Set(n)]}function U2r(t,e=20){let r=[],n=app.metadataCache.getBacklinksForFile(t);if(n?.data)for(let[o]of n.data){let i=app.vault.getAbstractFileByPath(o);if(i instanceof q2r.TFile&&(r.push(i),r.length>=e))break}return r}vOe();Pt();var tmt=require("obsidian"),SYo=.4,CYo=20,z2r=.7,rje=.3;async function xYo(t,e){let r=ce().debug,n=await G1.getDocsByPath(e,t);if(!n)return r&&console.log("No hits found for note:",t),[];let o=[];for(let i of n){if(!i?.document?.embedding){r&&console.log("No embedding found for note:",t);continue}o.push(i.document.embedding)}return o}function OYo(t){if(t.length===0)return[];let e=t[0].length,r=Array(e).fill(0);for(let n of t)for(let o=0;o<e;o++)r[o]+=n[o];for(let n=0;n<e;n++)r[n]/=t.length;return r}function TYo(t,e){let r=new Map;for(let n of t){let o=r.get(n.document.path);o?n.score>o&&r.set(n.document.path,n.score):r.set(n.document.path,n.score)}return r.delete(e),r}async function EYo({db:t,filePath:e}){let r=ce().debug,n=await xYo(e,t),o=OYo(n);if(o.length===0)return r&&console.log("No embeddings found for note:",e),new Map;let i=await G1.getDocsByEmbedding(t,o,{limit:CYo,similarity:SYo});return TYo(i,e)}function PYo(t){let e=new Map,n=B2r(t).map(a=>a.path);for(let a of n)e.set(a,{links:!0,backlinks:!1});let i=U2r(t).map(a=>a.path);for(let a of i)e.has(a)?e.set(a,{links:!0,backlinks:!0}):e.set(a,{links:!1,backlinks:!0});return e}function MYo(t,e){let r=new Map,n=z2r+rje;for(let[o,i]of t)r.set(o,i*z2r/n);for(let[o,i]of e){let a=0;i.links&&i.backlinks?a=rje:(i.links||i.backlinks)&&(a=rje*.8),r.set(o,(r.get(o)??0)+a)}return r}async function oje({db:t,filePath:e}){let r=app.vault.getAbstractFileByPath(e);if(!(r instanceof tmt.TFile))return[];let n=await EYo({db:t,filePath:e}),o=PYo(r),i=MYo(n,o);return Array.from(i.entries()).sort((s,u)=>{let l=s[0],c=u[0],d=nje(n.get(l)??0),f=nje(n.get(c)??0);return d!==f?f-d:u[1]-s[1]}).map(([s,u])=>{let l=app.vault.getAbstractFileByPath(s);return!(l instanceof tmt.TFile)||l.extension!=="md"?null:{document:{path:s,title:l.basename},metadata:{score:u,similarityScore:n.get(s),hasOutgoingLinks:o.get(s)?.links??!1,hasBacklinks:o.get(s)?.backlinks??!1}}}).filter(s=>s!==null)}function nje(t){return t>.7?3:t>.55?2:1}var V2r=require("obsidian"),RYo={cjk:[[19968,40959],[13312,19903],[131072,173791],[173824,177983],[177984,178207],[178208,183983]],japanese:[[12352,12447],[12448,12543]],korean:[[44032,55215],[4352,4607]],other:[[3584,3711],[1536,1791],[2304,2431],[2432,2559],[2688,2815],[2944,3071]]};function AYo(t,e){let r=t.codePointAt(0);return r?e.some(([n,o])=>r>=n&&r<=o):!1}function J2r(t){let e=t.replace(/[\p{Emoji}\p{Symbol}\p{Punctuation}]/gu,"");if(!e)return!1;for(let r of e)if(Object.values(RYo).some(n=>AYo(r,n)))return!0;return!1}function K2r(t,e){let r="",n="",o=Math.max(0,e.line-5);for(let u=o;u<e.line;u++)r+=t.getLine(u)+`
`;let i=t.getLine(e.line);r+=i.slice(0,e.ch),(e.ch===0||e.ch===i.length&&i.trim()==="")&&(r+=`
`);let a=Math.max(0,e.line-50);for(let u=a;u<e.line;u++)n+=t.getLine(u)+`
`;n+=i.slice(0,e.ch)+"{{CURSOR}}"+i.slice(e.ch)+`
`;let s=Math.min(t.lineCount()-1,e.line+50);for(let u=e.line+1;u<=s;u++)n+=t.getLine(u)+`
`;return{prefix:r,noteContext:n}}var OB=class OB{constructor(){this.currentNotePath=null;this.cachedNotes=null;this.cachedNoteTitles=[]}static getInstance(){return OB.instance||(OB.instance=new OB),OB.instance}getRelevantNoteTitles(){return this.cachedNoteTitles}async getRelevantNotes(e){if(!e)return this.currentNotePath=null,this.cachedNotes=null,this.cachedNoteTitles=[],"";if(this.currentNotePath===e.path&&this.cachedNotes!==null)return this.cachedNotes;let r=[];try{let a=await(await Promise.resolve().then(()=>(Dm(),vg))).default.getInstance().getDb();a&&(r=await oje({db:a,filePath:e.path}))}catch(i){console.warn("Failed to fetch relevant notes for autocomplete:",i)}let n=r.slice(0,OB.MAX_RELEVANT_NOTES);this.cachedNoteTitles=n.map(i=>i.document.title);let o=await Promise.all(n.map(async i=>{let a=app.vault.getAbstractFileByPath(i.document.path);if(!(a instanceof V2r.TFile))return"";let s=await app.vault.cachedRead(a);if(!s)return"";let u=s.length>3e3?s.slice(0,3e3)+"...":s;return`[[${i.document.title}]]:
${u}`}));return this.currentNotePath=e.path,this.cachedNotes=o.join(`
`),this.cachedNotes}clearCache(){this.currentNotePath=null,this.cachedNotes=null,this.cachedNoteTitles=[]}};OB.MAX_RELEVANT_NOTES=3;var H2r=OB;var _J=class{constructor(){this.MIN_WORD_LENGTH=4;this.STOP_WORDS=new Set(["a","ain","all","am","an","and","any","are","as","at","be","but","by","can","d","did","do","don","few","for","had","has","he","her","him","his","how","i","if","in","is","isn","it","its","ll","m","ma","me","my","no","nor","not","now","o","of","off","on","or","our","out","own","re","s","she","so","t","the","to","too","up","ve","was","we","who","why","won","y","you"])}extractWords(e){return(this.preprocessText(e).match(/\b[a-zA-Z]+(?:'[a-zA-Z]+)?\b/g)||[]).filter(o=>this.isValidWord(o))}isWordCharacter(e){return/[a-zA-Z']/.test(e)}isValidWord(e){return!(e.length<this.MIN_WORD_LENGTH||!/^[a-zA-Z]+(?:'[a-zA-Z]+)?$/.test(e)||this.STOP_WORDS.has(e.toLowerCase())||e===e.toUpperCase()&&e.length>4)}getLanguage(){return"en"}preprocessText(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`[^`]+`/g," ").replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/<[^>]+>/g," ").replace(/^#+\s+/gm,"").replace(/[*_]{1,2}([^*_]+)[*_]{1,2}/g,"$1").replace(/^\s*[-*+]\s+/gm,"").replace(/^\s*\d+\.\s+/gm,"").replace(/\s+/g," ").trim()}};var ace=class{constructor(e=5e4){this.wordCount=0;this.root=this.createNode(),this.maxSize=e}createNode(){return{children:new Map,isEndOfWord:!1,wordEntry:void 0}}addWord(e,r){if(!e||e.length<4||this.wordCount>=this.maxSize&&!this.hasWord(e))return;let n=this.root;for(let o of e)n.children.has(o)||n.children.set(o,this.createNode()),n=n.children.get(o);n.isEndOfWord?n.wordEntry&&(n.wordEntry.frequency++,n.wordEntry.lastSeen=Date.now(),r&&!n.wordEntry.contexts.includes(r)&&(n.wordEntry.contexts.push(r),n.wordEntry.contexts.length>10&&(n.wordEntry.contexts=n.wordEntry.contexts.slice(-10)))):(n.isEndOfWord=!0,n.wordEntry={word:e,frequency:1,contexts:r?[r]:[],lastSeen:Date.now()},this.wordCount++)}hasWord(e){let r=this.findNode(e);return r!==null&&r.isEndOfWord}getWordEntry(e){let r=this.findNode(e);return r&&r.isEndOfWord&&r.wordEntry?r.wordEntry:null}findNode(e){let r=this.root;for(let n of e){if(!r.children.has(n))return null;r=r.children.get(n)}return r}getSuggestions(e,r=10){if(!e)return[];let n=[],o=this.generatePrefixVariants(e);for(let a of o){let s=this.findNode(a);if(s&&(this.collectWords(s,a,n,r,e),n.length>=r))break}let i=this.deduplicateSuggestions(n);return i.sort((a,s)=>s.score-a.score),i.slice(0,r)}generatePrefixVariants(e){let r=new Set;return r.add(e),r.add(e.toLowerCase()),e.length>0&&r.add(e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()),r.add(e.toUpperCase()),Array.from(r)}deduplicateSuggestions(e){let r=new Map;for(let n of e){let o=n.word,i=r.get(o);(!i||n.score>i.score)&&r.set(o,n)}return Array.from(r.values())}collectWords(e,r,n,o,i){if(!(n.length>=o)){if(e.isEndOfWord&&e.wordEntry){let a=this.calculateScore(e.wordEntry)+this.getCaseMatchBonus(r,i);n.push({word:r,score:a,source:"vault"})}for(let[a,s]of e.children)this.collectWords(s,r+a,n,o,i)}}getCaseMatchBonus(e,r){if(e.length<r.length)return 0;let n=e.substring(0,r.length);return n===r?2:this.hasSameCasePattern(n,r)?1.5:1}hasSameCasePattern(e,r){if(e.length<r.length)return!1;for(let n=0;n<r.length;n++){let o=e[n],i=r[n],a=o===o.toUpperCase(),s=i===i.toUpperCase();if(a!==s)return!1}return!0}calculateScore(e){let r=Math.log(e.frequency+1)*10,n=Math.max(0,(Date.now()-e.lastSeen)/(1e3*60*60*24)),o=Math.max(0,10-n);return r+o}getStats(){let e=0,r=0,n=(o,i=0)=>{e++,r=Math.max(r,i);for(let a of o.children.values())n(a,i+1)};return n(this.root),{wordCount:this.wordCount,nodeCount:e,maxDepth:r}}clear(){this.root=this.createNode(),this.wordCount=0}getAllWords(){let e=[],r=n=>{n.isEndOfWord&&n.wordEntry&&e.push(n.wordEntry);for(let o of n.children.values())r(o)};return r(this.root),e}addWords(e,r){for(let n of e)this.addWord(n,r)}pruneByFrequency(e=2){let r=0,n=o=>{let i=[];for(let[a,s]of o.children)n(s)&&i.push(a);for(let a of i)o.children.delete(a);return o.isEndOfWord&&o.wordEntry&&o.wordEntry.frequenc
`))return!1;let o=e.split(`
`),i=o[o.length-1];if(/^#{1,6}(\s*)$/.test(i))return!1;let a=e.trim().split(/\s+/).filter(u=>u.replace(/[\p{Emoji}\p{Symbol}\p{Punctuation}]/gu,"").length>0),s=a[a.length-1]||"";return J2r(s)?!0:e.endsWith(" ")}async*handleUnifiedCompletion(){if(!this.isActive)return;let e=app.workspace.getActiveViewOfType(rmt.MarkdownView);if(!e)return;await new Promise(c=>setTimeout(c,10));let r=e.editor,n=r.getCursor(),{prefix:o,noteContext:i}=K2r(r,n),a=r.getLine(n.line).substring(n.ch)||"";if(this.lastCursorPosition){let c=Math.abs(n.line-this.lastCursorPosition.line),d=Math.abs(n.ch-this.lastCursorPosition.ch);(c>0||d>5)&&this.clearActiveRequests()}this.lastCursorPosition={line:n.line,ch:n.ch};let s=Date.now();if(s-this.lastRequestTime<this.minRequestInterval)return;let u=ce();if(this.shouldUseWordCompletion(o,u)){let c=this.getCurrentWordFromPrefix(o);if(!c||c.length<2)return;let d=`word:${c}:${o.slice(-50)}`;if(this.activeRequests.has(d))return;let f=this.wordCompletionManager.getSuggestions(c);if(f.length===0)return;let p=f.some(b=>b.word===c),m=f.some(b=>b.word.length-c.length>=2);if(p&&!m)return;let h=p?f.filter(b=>b.word!==c):f;if(h.length===0)return;this.lastRequestTime=s;let g=h[0],y=this.generateCaseMatchedCompletion(g.word,c);y&&(yield{display_suggestion:y,complete_suggestion:y})}else{if(!u.enableAutocomplete||!this.shouldContinueSuggesting(o,a))return;let c=o.slice(-this.options.maxContextLength);if(c.length<this.options.minTriggerLength)return;let d=`sentence:${c.slice(-100)}`;if(this.activeRequests.has(d))return;this.lastRequestTime=s;return}}shouldUseWordCompletion(e,r){if(!r.enableWordCompletion||e.endsWith("[[")||/\[\[[^\]]*$/.test(e))return!1;let o=e.trim(),i=o[o.length-1];if(i&&/[a-zA-Z']/.test(i)){let a=this.getCurrentWordFromPrefix(e);if(a&&a.length>=2){let s=this.wordCompletionManager.getSuggestions(a);if(s.length===0)return!1;let u=s.some(c=>c.word===a),l=s.some(c=>c.word.length-a.length>=2);return!(u&&!l)}}return!1}getCurrentWordFromPrefix(e){let r=e.length;for(let o=e.length-1;o>=0;o--){let i=e[o];if(!/[a-zA-Z']/.test(i)){r=o+1;break}o===0&&(r=0)}let n=e.substring(r);return n.length>=2?n:null}generateCaseMatchedCompletion(e,r){if(e.length<=r.length)return"";let n=e.substring(r.length),o=r===r.toUpperCase(),i=r===r.toLowerCase(),a=r.length>0&&r[0]===r[0].toUpperCase()&&r.slice(1)===r.slice(1).toLowerCase();return o?n.toUpperCase():i||a?n.toLowerCase():n}detectContext(e){let r=e.split(`
`).pop()||"";if(/^\s*[-*+]\s/.test(r))return"UnorderedList";if(/^\s*\d+\.\s/.test(r))return"NumberedList";if(/^\s*[-*+]\s\[[ x]\]\s/.test(r))return"TaskList";if(e.includes("```")&&(e.split("```").length-1)%2===1)return"CodeBlock"}triggerCompletion(){this.isActive&&(this.clearActiveRequests(),this.forceFetch())}clearActiveRequests(){this.activeRequests.size>0&&this.activeRequests.clear()}getWordCompletionManager(){return this.wordCompletionManager}setCacheEnabled(e){this.cacheEnabled=e,e||this.cache.clear()}getCacheEnabled(){return this.cacheEnabled}};var aje=class t{constructor(e){this.plugin=e;let r=ce();this.cmIntegration=ije.getInstance({delay:Xw.DELAY_MS,minTriggerLength:Xw.MIN_TRIGGER_LENGTH,maxContextLength:Xw.MAX_CONTEXT_LENGTH}),this.unsubscribeSettings=Ou((o,i)=>{let a=(o.enableAutocomplete||o.enableWordCompletion)&&o.isPlusUser===!0,s=(i.enableAutocomplete||i.enableWordCompletion)&&i.isPlusUser===!0;a!==s&&this.cmIntegration.setActive(s)});let n=(r.enableAutocomplete||r.enableWordCompletion)&&r.isPlusUser===!0;this.cmIntegration.setActive(n),this.registerExtension()}static getInstance(e){return t.instance||(t.instance=new t(e)),t.instance}registerExtension(){try{this.plugin.registerEditorExtension([this.cmIntegration.getExtension()])}catch(e){ue("[Copilot Autocomplete] Failed to register CodeMirror extension:",e)}}destroy(){this.unsubscribeSettings(),this.cmIntegration.setActive(!1),this.cmIntegration.destroy()}};Tu();L6();iot();hie();Dt();W7();var xHr=require("obsidian");Ro();var sje=L(X());jn();var yi=sje.forwardRef(({className:t,type:e,...r},n)=>sje.createElement("input",{type:e,className:Oe("!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}));yi.displayName="Input";var uje=L(X());var eHr=L(X(),1);var Z2r=L(X(),1),X2r=L(Bu(),1);var Ig=L(X(),1);var G2r=L(X(),1);function NYo(t,e){typeof t=="function"?t(e):t!=null&&(t.current=e)}function wJ(...t){return e=>t.forEach(r=>NYo(r,e))}function Fc(...t){return G2r.useCallback(wJ(...t),t)}var eZ=L(mt(),1),omt=Ig.forwardRef((t,e)=>{let{children:r,...n}=t,o=Ig.Children.toArray(r),i=o.find(DYo);if(i){let a=i.props.children,s=o.map(u=>u===i?Ig.Children.count(a)>1?Ig.Children.only(null):Ig.isValidElement(a)?a.props.children:null:u);return(0,eZ.jsx)(nmt,{...n,ref:e,children:Ig.isValidElement(a)?Ig.cloneElement(a,void 0,s):null})}return(0,eZ.jsx)(nmt,{...n,ref:e,children:r})});omt.displayName="Slot";var nmt=Ig.forwardRef((t,e)=>{let{children:r,...n}=t;if(Ig.isValidElement(r)){let o=LYo(r);return Ig.cloneElement(r,{...$Yo(n,r.props),ref:e?wJ(e,o):o})}return Ig.Children.count(r)>1?Ig.Children.only(null):null});nmt.displayName="SlotClone";var jYo=({children:t})=>(0,eZ.jsx)(eZ.Fragment,{children:t});function DYo(t){return Ig.isValidElement(t)&&t.type===jYo}function $Yo(t,e){let r={...e};for(let n in e){let o=t[n],i=e[n];/^on[A-Z]/.test(n)?o&&i?r[n]=(...s)=>{i(...s),o(...s)}:o&&(r[n]=o):n==="style"?r[n]={...o,...i}:n==="className"&&(r[n]=[o,i].filter(Boolean).join(" "))}return{...t,...r}}function LYo(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,r=e&&"isReactWarning"in e&&e.isReactWarning;return r?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,r=e&&"isReactWarning"in e&&e.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}var Y2r=L(mt(),1),FYo=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],ou=FYo.reduce((t,e)=>{let r=Z2r.forwardRef((n,o)=>{let{asChild:i,...a}=n,s=i?omt:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,Y2r.jsx)(s,{...a,ref:o})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});function Q2r(t,e){t&&X2r.flushSync(()=>t.dispatchEvent(e))}var tHr=L(mt(),1),kYo="Label",rHr=eHr.forwardRef((t,e
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}];var aZ=require("obsidian");Pt();TN();TN();var SJ=j6(),CJ=th([]),ymt=new Set;function xJ(t){ymt.add(t)}function OJ(t){ymt.delete(t)}function uce(t){return ymt.has(t)}function lce(t){let e=SJ.get(CJ);SJ.set(CJ,e.filter(r=>r.title!==t))}function TJ(t,e){let r=SJ.get(CJ),n;(e?r.findIndex(i=>i.title===e):-1)!==-1?n=r.map(i=>i.title===e?t:i):n=[...r,t],SJ.set(CJ,n)}function mje(t){SJ.set(CJ,t)}function hje(){return Zw(CJ,{store:SJ})}function K_(){return SJ.get(CJ)}iee();wr();zr();function gje(t,e,r){let n=t.trim();return r&&n===r?null:n?/[#<>:"/\\|?*[\]^\x00-\x1F]/g.test(n)?'Command name contains invalid characters. Avoid using: < > : " / \\ | ? * [ ] ^':e.some(i=>i.title.toLowerCase()===n.toLowerCase())?"A command with this name already exists":null:"Command name cannot be empty"}function sZ(t){return encodeURIComponent(t.toLowerCase())}function RB(){return(0,aZ.normalizePath)(ce().customPromptsFolder)}function uZ(t){return`${RB()}/${t}.md`}function lZ(t){if(!(t instanceof aZ.TFile)||t.extension!=="md")return!1;let e=RB();return!(!t.path.startsWith(e+"/")||t.path.slice(e.length+1).includes("/"))}function iQo(t){if(t.startsWith("---")){let e=t.indexOf("---",3);if(e!==-1)return t.slice(e+3).trimStart()}return t}function SHr(t){return app.metadataCache.getFileCache(t)?.frontmatter?.[xI]!=null}async function cce(t){let e=await app.vault.read(t),r=iQo(e),n=app.metadataCache.getFileCache(t),o=n?.frontmatter?.[XD]??CI.showInContextMenu,i=n?.frontmatter?.[YD]??CI.showInSlashMenu,a=n?.frontmatter?.[e$]??CI.lastUsedMs,s=n?.frontmatter?.[xI]??CI.order,u=n?.frontmatter?.[QD]??CI.modelKey;return{title:t.basename,modelKey:u,content:r,showInContextMenu:o,showInSlashMenu:i,order:s,lastUsedMs:a}}async function yje(){let t=app.vault.getFiles().filter(r=>lZ(r)),e=await Promise.all(t.map(cce));return mje(e),e}function dce(t){return[...t].sort((e,r)=>e.order===r.order?e.title.localeCompare(r.title):e.order-r.order)}function aQo(t){return[...t].sort((e,r)=>e.lastUsedMs===r.lastUsedMs?e.title.localeCompare(r.title):r.lastUsedMs-e.lastUsedMs)}function sQo(t){return[...t].sort((e,r)=>e.title.localeCompare(r.title))}function bje(t){switch(ce().promptSortStrategy){case"timestamp":return aQo(t);case"alphabetical":return sQo(t);case"manual":return dce(t);default:return t}}async function bmt(t,e,r=!1){let o=(await _mt(t,e,app.vault,app.workspace.getActiveFile())).processedPrompt;if(o.includes(`{${u_}}`)||r)return o;let i=o.indexOf(gmt);return i===-1&&e.trim()?o+`
<`+u_+">"+e+"</"+u_+">":o.slice(0,i)+e+o.slice(i+gmt.length)}var uQo=/\{(?!copilot-selection\})([^}]+)\}/g;async function lQo(t,e,r){let n=new Map,o=new Set,i;for(;(i=uQo.exec(t))!==null;){let a=i[1].trim(),s={content:"",files:[]};if(a.toLowerCase()==="activenote")if(r){let u=await q6(r,e);u&&(s.content=`<${kz}>
## ${khe(r)}
${u}
</${kz}>`,s.files.push(r))}else new aZ.Notice("No active note found.");else if(a.startsWith("#")){let u=a.slice(1).split(",").map(d=>d.trim()),l=await Fhe(e,u),c=[];for(let d of l){let f=await q6(d,e);f&&(c.push(`<${kz}>
## ${khe(d)}
${f}
</${kz}>`),s.files.push(d))}s.content=c.join(`
`)}else{let u=SAt(a),l=await eee(e,u),c=[];for(let d of l){let f=await q6(d,e);f&&(c.push(`<${kz}>
## ${khe(d)}
${f}
</${kz}>`),s.files.push(d))}s.content=c.join(`
`)}s.content?(n.set(a,s.content),s.files.forEach(u=>o.add(u))):a.toLowerCase()!=="activenote"&&(a.startsWith('"')||console.warn(`No notes found for variable: ${a}`))}return{variablesMap:n,includedFiles:o}}async function _mt(t,e,r,n){let o=ce(),i=new Set;if(!o.enableCustomPromptTemplating)return t.includes("{}")&&!e&&n&&i.add(n),{processedPrompt:t+`
`,includedFiles:Array.from(i)};let{variablesMap:a,includedFiles:s}=await lQo(t,r,n);s.forEach(f=>i.add(f));let u=t,l="",c=null;u.includes("{}")&&(u=u.replace(/\{\}/g,`{${u_}}`),e?l+=`<${u_}>
${e}
</${u_}>`:n?(c=await q6(n,r),l+=`<${u_} type="active_note">
${c||""}
</${u_}>`,i.add(n)):l+=`<${u_}>
(No selected text or active note available)
</${u_}>`);for(let[f,p]of a.entries())f.toLowerCase()==="activenote"&&c!==null||(l?l+=`
<${see} name="${f}">
${p}
</${see}>`:l+=`<${see} name="${f}">
${p}
</${see}>`);let d=xO(u,r);for(let f of d)if(!i.has(f)){let p=await q6(f,r);if(p){let m=await r.adapter.stat(f.path),h=m?new Date(m.ctime).toISOString():"Unknown",g=m?new Date(m.mtime).toISOString():"Unknown",y=`<${aee}>
<title>${f.basename}</title>
<path>${f.path}</path>
<ctime>${h}</ctime>
<mtime>${g}</mtime>
<content>
${p}
</content>
</${aee}>`;l&&(l+=`
`),l+=`${y}`,i.add(f)}}return{processedPrompt:l?`${u}
${l}`:`${u}
`,includedFiles:Array.from(i)}}function CHr(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 _je(){let e=K_().reduce((r,n)=>r>n.order?r:n.order,0);return e===Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:e+10}async function vmt(t,e){try{xJ(t.path),await app.fileManager.processFrontMatter(t,r=>{r[XD]==null&&(r[XD]=e.showInContextMenu),r[YD]==null&&(r[YD]=e.showInSlashMenu),r[xI]==null&&(r[xI]=e.order),r[QD]==null&&(r[QD]=e.modelKey),r[e$]==null&&(r[e$]=e.lastUsedMs)})}finally{OJ(t.path)}}function vje(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()===`\`\`\`${iZ}`){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 cQo({commands:t,command:e,onConfirm:r,onCancel:n}){let i=So().activeModels.filter(f=>f.enabled).map(f=>({label:pje(f),value:Qn(f)})),[a,s]=(0,Is.useState)(e),[u,l]=(0,Is.useState)({}),c=(f,p)=>{s(m=>({...m,[f]:p})),l(m=>({...m,[f]:void 0}))},d=()=>{let f={},p=gje(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 Is.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4 tw-p-4"},Is.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Is.default.createElement(Ib,{htmlFor:"title"},"Name"),Is.default.createElement(yi,{id:"title",value:a.title,onChange:f=>c("title",f.target.value),placeholder:"Enter command name"}),u.title&&Is.default.createElement("div",{className:"tw-text-sm tw-text-error"},u.title)),Is.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Is.default.createElement(Ib,{htmlFor:"content"},"Prompt"),Is.default.createElement(vHr,null),Is.default.createElement(Cx,{id:"content",value:a.content,onChange:f=>c("content",f.target.value),placeholder:"Enter command prompt",className:"tw-min-h-[200px]"}),u.content&&Is.default.createElement("div",{className:"tw-text-sm tw-text-error"},u.content)),Is.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Is.default.createElement(Ib,{htmlFor:"modelKey"},"Model (Optional)"),Is.default.createElement("div",{className:"tw-group tw-relative tw-w-full"},Is.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)){ue(`Model ${p} not found`),c("modelKey","");return}c("modelKey",f.target.value)},className:Oe("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")},Is.default.createElement("option",{value:""},"Inherit from chat model"),i.map(f=>Is.default.createElement("option",{key:f.value,value:f.value.toString()},f.label))),Is.default.createElement("div",{className:Oe("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")},Is.default.createElement(Qs,{className:"tw-size-4"})))),Is.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Is.default.createElement(sd,{id:"showInContextMenu",checked:a.showInContextMenu,onCheckedChange:f=>c("showInContextMenu",f)}),Is.default.createElement(Ib,{htmlFor:"showInContextMenu"},"Show in context menu")),Is.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Is.default.createElement(sd,{id:"showInSlashMenu",checked:a.showInSlashMenu,onCheckedChange:f=>c("showInSlashMenu",f)}),Is.default.createElement(Ib,{htmlFor:"showInSlashMenu"},"Show in slash menu")),Is.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},Is.default.createElement(ve,{variant:"secondary",onClick:n},"Cancel"),Is.default.createElement(ve,{variant:"default",onClick:d},"Save")))}var AB=class extends xHr.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,OHr.createRoot)(r);let n=o=>{this.onUpdate(o),this.close()};this.root.render(Is.default.createElement(cQo,{commands:this.commands,command:this.command,onConfirm:n,onCancel:()=>this.close()}))}onClose(){this.root.unmount()}};var fce=require("obsidian");MN();wr();var jg=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=uZ(e.title);try{xJ(o);let i=e.order;n.autoOrder&&(i=_je()),e={...e,order:i};let a=RB();await ty(a);let
Source: ${d.url}
${d.transcript}`;await navigator.clipboard.writeText(w),new cZ.Notice("Transcript copied to clipboard!")}catch(w){ue("Failed to copy to clipboard:",w),new cZ.Notice("Failed to copy to clipboard")}},y=async()=>{if(d)try{let w=`# YouTube Video Transcript
Source: ${d.url}
${d.transcript}`;await $z(w,!1),t()}catch(w){ue("Failed to insert to note:",w),new cZ.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(ve,{variant:"ghost",onClick:b},"Download Another"),Du.createElement(ve,{variant:"default",onClick:g},"Copy to Clipboard"),Du.createElement(ve,{variant:"default",onClick:y},"Insert at Cursor"),Du.createElement(ve,{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(yi,{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(ve,{variant:"secondary",onClick:t,disabled:i},"Cancel"),Du.createElement(ve,{variant:"default",onClick:h,disabled:i||!l},i?"Downloading...":"Download Transcript")))}var Cje=class extends cZ.Modal{constructor(e){super(e),this.setTitle("Download YouTube Script (plus)")}onOpen(){let{contentEl:e}=this;this.root=(0,EHr.createRoot)(e);let r=()=>{this.close()};this.root.render(Du.createElement(pQo,{onClose:r}))}onClose(){this.root.unmount()}};$v();vb();Pt();wr();var qs=require("obsidian");J3();zr();function Dg(t,e,r){t.addCommand({id:e,name:Jhe[e],callback:r})}function PHr(t,e,r){t.addCommand({id:e,name:Jhe[e],editorCallback:r})}function mQo(t,e,r){t.addCommand({id:e,name:Jhe[e],checkCallback:r})}function wmt(t,e,r){PHr(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 qs.Notice(`Selected text contains ${i} words and ${a} tokens.`)}),Dg(t,Nn.COUNT_TOTAL_VAULT_TOKENS,async()=>{try{let n=await Gnt(t.app),o=await t.projectManager.getCurrentChainManager().chatModelManager.countTokens(n);new qs.Notice(`Total tokens in your vault: ${o}`)}catch(n){ue("Error counting tokens: ",n),new qs.Notice("An error occurred while counting tokens.")}}),Dg(t,Nn.TOGGLE_COPILOT_CHAT_WINDOW,()=>{t.toggleView()}),Dg(t,Nn.OPEN_COPILOT_CHAT_WINDOW,()=>{t.activateView()}),Dg(t,Nn.NEW_CHAT,()=>{K7(),t.newChat()}),mQo(t,Nn.TRIGGER_QUICK_COMMAND,n=>{let o=t.app.workspace.getActiveViewOfType(qs.MarkdownView);if(n)return!!(!Y2e()&&o&&o.editor);if(Y2e())return new qs.Notice("Quick command is not available in source mode."),!1;if(!o||!o.editor)return new qs.Notice("No active editor found."),!1;let i=o.editor;if(!i.getSelection().trim())return new qs.Notice("Please select some text first. Selected text is required for quick commands."),!1;vje(i);let u=i.getCursor("from").line,l=`\`\`\`${iZ}
\`\`\`
`;return i.replaceRange(l,{line:u,ch:0}),!0}),Dg(t,Nn.CLEAR_LOCAL_COPILOT_INDEX,async()=>{try{await(await Promise.resolve().then(()=>(Dm(),vg))).default.getInstance().clearIndex(),new qs.Notice("Cleared local Copilot semantic index.")}catch(n){ue("Error clearing semantic index:",n),new qs.Notice("Failed to clear semantic index.")}}),Dg(t,Nn.GARBAGE_COLLECT_COPILOT_INDEX,async()=>{try{let o=await(await Promise.resolve().then(()=>(Dm(),vg))).default.getInstance().garbageCollectVectorStore();new qs.Notice(`Garbage collection completed. Removed ${o} stale documents.`)}catch(n){ue("Error during garbage collection:",n),new qs.Notice("Failed to garbage collect semantic index.")}}),Dg(t,Nn.INDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let{getSettings:n}=await Promise.resolve().then(()=>(Pt(),YQ));if(n().enableSemanticSearchV3){let a=await(await Promise.resolve().then(()=>(Dm(),vg))).default.getInstance().indexVaultToVectorStore(!1);new qs.Notice(`Semantic search index refreshed with ${a} documents.`)}else new qs.Notice("Lexical search builds indexes on demand. No manual indexing required.")}catch(n){ue("Error building index:",n),new qs.Notice("An error occurred while building the index.")}}),Dg(t,Nn.FORCE_REINDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let{getSettings:n}=await Promise.resolve().then(()=>(Pt(),YQ));if(n().enableSemanticSearchV3){let a=await(await Promise.resolve().then(()=>(Dm(),vg))).default.getInstance().indexVaultToVectorStore(!0);new qs.Notice(`Semantic search index rebuilt with ${a} documents.`)}else new qs.Notice("Lexical search builds indexes on demand. No manual indexing required.")}catch(n){ue("Error rebuilding index:",n),new qs.Notice("An error occurred while rebuilding the index.")}}),Dg(t,Nn.LOAD_COPILOT_CHAT_CONVERSATION,()=>{t.loadCopilotChatHistory()}),Dg(t,Nn.LIST_INDEXED_FILES,async()=>{try{let o=await(await Promise.resolve().then(()=>(Dm(),vg))).default.getInstance().getIndexedFiles(),{getMatchingPatterns:i,shouldIndexFile:a}=await Promise.resolve().then(()=>(vb(),whr)),{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 x=await t.app.vault.cachedRead(w);!x||x.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`,g="copilot",y=`${g}/${h}`;await ty(g);let b=t.app.vault.getAbstractFileByPath(y);b?await t.app.vault.modify(b,m):await t.app.vault.create(y,m);let _=t.app.vault.getAbstractFileByPath(y);_&&(await t.app.workspace.getLeaf().openFile(_),new qs.Notice(`Listed ${p.size} indexed files`))}catch(n){ue("Error listing indexed files:",n),new qs.Notice("Failed to list indexed files.")}}),Dg(t,Nn.CLEAR_COPILOT_CACHE,async()=>{try{await t.fileParserManager.clearPDFCache(),await UC.getInstance().clearAllCache(),await Q8.getInstance().clear();let{AutocompleteCache:o}=await Promise.resolve().then(()=>(Jpt(),$2r));o.getInstance().clear(),new qs.Notice("All Copilot caches cleared successfully")}catch(n){ue("Error clearing Copilot caches:",n),new qs.Notice("Failed to clear Copilot caches")}}),Dg(t,Nn.OPEN_LOG_FILE,async()=>{try{await q1e(),await ey.openLogFile()}catch(n){ue("Error creating Copilot log file:",n),new qs.Notice("Failed to create Copilot log file.")}}),Dg(t,Nn.CLEAR_LOG_FILE,async()=>{try{await ey.clear(),new qs.Notice("Copilot log cleared.")}catch(n){ue("Error clearing Copilot log file:",n),new qs.Notice("Failed to clear Copilot log file.")}}),Dg(t,Nn.TOGGLE_AUTOCOMPLETE,()=>{let o=!ce().enableAutocomplete;et("enableAutocomplete",o),new qs.Notice(`Copilot autocomplete ${o?"enabled":"disabled"}`)}),PHr(t,Nn.ADD_SELECTION_TO_CHAT_CONTEXT,async n=>{let o=n.getSelection();if(!o){new qs.Notice("No text selected");return}let i=t.app.workspace.getActiveFile();if(!i){new qs.Notice("No active file");return}let a=n.listSelections()[0];if(!a){new qs.Notice("Could not determine selection range");return}let s=a.anchor.line+1,u=a.head.line+1,l={id:H0(),content:o,noteTitle:i.basename,notePath:i.path,startLine:Math.min(s,u),endLine:Math.max(s,u)};sIt(l),t.activateView()}),Dg(t,Nn.ADD_CUSTOM_COMMAND,async()=>{let n=K_(),o={...CI};new AB(t.app,n,o,async a=>{await jg.getInstance().createCommand(a)}).open()}),Dg(t,Nn.APPLY_CUSTOM_COMMAND,()=>{new wje(t.app).open()}),Dg(t,Nn.DOWNLOAD_YOUTUBE_SCRIPT,async()=>{if(!await jS()){new qs.Notice("Download YouTube Script (plus) is a Copilot Plus feature");return}new Cje(t.app).open()})}Tu();gd();gd();Tu();function xje(){let[t]=Ev(),[e]=rge(),[r]=nge();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"})()}Dt();Tu();hie();gd();Ro();var MHr=require("obsidian"),EJ=L(X()),RHr=L(wm());function hQo({content:t,onConfirm:e,onCancel:r,confirmButtonText:n,cancelButtonText:o}){return EJ.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-5"},EJ.default.createElement("div",{className:"tw-whitespace-pre-wrap"},t),EJ.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},o&&EJ.default.createElement(ve,{variant:"secondary",onClick:r},o),n&&EJ.default.createElement(ve,{variant:"default",onClick:e},n)))}var lm=class extends MHr.Modal{constructor(r,n,o,i,a="Continue",s="Cancel"){super(r);this.onConfirm=n;this.content=o;this.confirmButtonText=a;this.cancelButtonText=s;this.setTitle(i)}onOpen(){let{contentEl:r}=this;this.root=(0,RHr.createRoot)(r);let n=()=>{this.onConfirm(),this.close()},o=()=>{this.close()};this.root.render(EJ.default.createElement(hQo,{content:this.content,onConfirm:n,onCancel:o,confirmButtonText:this.confirmButtonText,cancelButtonText:this.cancelButtonText}))}onClose(){this.root.unmount()}};Ro();var $u=L(X());var Hm=L(X(),1);var xhs=!!(typeof window<"u"&&window.document&&window.document.createElement);function pce(t,e,{checkForDefaultPrevented:r=!0}={}){return function(o){if(t?.(o),r===!1||!o.defaultPrevented)return e?.(o)}}var gQo=L(X(),1);function AHr(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function IHr(...t){return e=>{let r=!1,n=t.map(o=>{let i=AHr(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():AHr(t[o],null)}}}}var t$=L(X(),1),NHr=L(
.`.concat(Zmt,` {
overflow: hidden `).concat(n,`;
padding-right: `).concat(s,"px ").concat(n,`;
}
body[`).concat(vZ,`] {
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(Mx,` {
right: `).concat(s,"px ").concat(n,`;
}
.`).concat(Rx,` {
margin-right: `).concat(s,"px ").concat(n,`;
}
.`).concat(Mx," .").concat(Mx,` {
right: 0 `).concat(n,`;
}
.`).concat(Rx," .").concat(Rx,` {
margin-right: 0 `).concat(n,`;
}
body[`).concat(vZ,`] {
`).concat(Xmt,": ").concat(s,`px;
}
`)},WJr=function(){var t=parseInt(document.body.getAttribute(vZ)||"0",10);return isFinite(t)?t:0},vti=function(){wZ.useEffect(function(){return document.body.setAttribute(vZ,(WJr()+1).toString()),function(){var t=WJr()-1;t<=0?document.body.removeAttribute(vZ):document.body.setAttribute(vZ,t.toString())}},[])},FJ=function(t){var e=t.noRelative,r=t.noImportant,n=t.gapMode,o=n===void 0?"margin":n;vti();var i=wZ.useMemo(function(){return rht(o)},[o]);return wZ.createElement(bti,{styles:_ti(i,!e,o,r?"":"!important")})};var nht=!1;if(typeof window<"u")try{Sce=Object.defineProperty({},"passive",{get:function(){return nht=!0,!0}}),window.addEventListener("test",Sce,Sce),window.removeEventListener("test",Sce,Sce)}catch{nht=!1}var Sce,kJ=nht?{passive:!1}:!1;var wti=function(t){return t.tagName==="TEXTAREA"},GJr=function(t,e){if(!(t instanceof Element))return!1;var r=window.getComputedStyle(t);return r[e]!=="hidden"&&!(r.overflowY===r.overflowX&&!wti(t)&&r[e]==="visible")},Sti=function(t){return GJr(t,"overflowY")},Cti=function(t){return GJr(t,"overflowX")},oht=function(t,e){var r=e.ownerDocument,n=e;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var o=ZJr(t,n);if(o){var i=XJr(t,n),a=i[1],s=i[2];if(a>s)return!0}n=n.parentNode}while(n&&n!==r.body);return!1},xti=function(t){var e=t.scrollTop,r=t.scrollHeight,n=t.clientHeight;return[e,r,n]},Oti=function(t){var e=t.scrollLeft,r=t.scrollWidth,n=t.clientWidth;return[e,r,n]},ZJr=function(t,e){return t==="v"?Sti(e):Cti(e)},XJr=function(t,e){return t==="v"?xti(e):Oti(e)},Tti=function(t,e){return t==="h"&&e==="rtl"?-1:1},YJr=function(t,e,r,n,o){var i=Tti(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=XJr(t,s),m=p[0],h=p[1],g=p[2],y=h-g-i*m;(m||y)&&ZJr(t,s)&&(d+=y,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 eDe=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},QJr=function(t){return[t.deltaX,t.deltaY]},e3r=function(t){return t&&"current"in t?t.current:t},Eti=function(t,e){return t[0]===e[0]&&t[1]===e[1]},Pti=function(t){return`
.block-interactivity-`.concat(t,` {pointer-events: none;}
.allow-interactivity-`).concat(t,` {pointer-events: all;}
`)},Mti=0,SZ=[];function t3r(t){var e=yl.useRef([]),r=yl.useRef([0,0]),n=yl.useRef(),o=yl.useState(Mti++)[0],i=yl.useState(a$)[0],a=yl.useRef(t);yl.useEffect(function(){a.current=t},[t]),yl.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var h=_Z([t.lockRef.current],(t.shards||[]).map(e3r),!0).filter(Boolean);return h.forEach(function(g){return g.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),h.forEach(function(g){return g.classList.remove("allow-interactivity-".concat(o))})}}},[t.inert,t.lockRef.current,t.shards]);var s=yl.useCallback(function(h,g){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!a.current.allowPinchZoom;var y=eDe(h),b=r.current,_="deltaX"in h?h.deltaX:b[0]-y[0],w="deltaY"in h?h.deltaY:b[1]-y[1],x,O=h.target,E=Math.abs(_)>Math.abs(w)?"h":"v";if("touches"in h&&E==="h"&&O.type==="range")return!1;var T=oht(E,O);if(!T)return!0;if(T?x=E:(x=E==="v"?"h":"v",T=oht(E,O)),!T)return!1;if(!n.current&&"changedTouches"in h&&(_||w)&&(n.current=x),!x)return!0;var R=n.current||x;return YJr(R,g,h,R==="h"?_:w,!0)},[]),u=yl.useCallback(function(h){var g=h;if(!(!SZ.length||SZ[SZ.length-1]!==i)){var y="deltaY"in g?QJr(g):eDe(g),b=e.current.filter(function(x){return x.name===g.type&&(x.target===g.target||g.target===x.shadowParent)&&Eti(x.delta,y)})[0];if(b&&b.should){g.cancelable&&g.preventDefault();return}if(!b){var _=(a.current.shards||[]).map(e3r).filter(Boolean).filter(function(x){return x.contains(g.target)}),w=_.length>0?s(g,_[0]):!a.current.noIsolation;w&&g.cancelable&&g.preventDefault()}}},[]),l=yl.useCallback(function(h,g,y,b){var _={name:h,delta:g,target:y,should:b,shadowParent:Rti(y)};e.current.push(_),setTimeout(function(){e.current=e.current.filter(function(w){return w!==_})},1)},[]),c=yl.useCallback(function(h){r.current=eDe(h),n.current=void 0},[]),d=yl.useCallback(function(h){l(h.type,QJr(h),h.target,s(h,t.lockRef.current))},[]),f=yl.useCallback(function(h){l(h.type,eDe(h),h.target,s(h,t.lockRef.current))},[]);yl.useEffect(function(){return SZ.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,kJ),document.addEventListener("touchmove",u,kJ),document.addEventListener("touchstart",c,kJ),function(){SZ=SZ.filter(function(h){return h!==i}),document.removeEventListener("wheel",u,kJ),document.removeEventListener("touchmove",u,kJ),document.removeEventListener("touchstart",c,kJ)}},[]);var p=t.removeScrollBar,m=t.inert;return yl.createElement(yl.Fragment,null,m?yl.createElement(i,{styles:Pti(o)}):null,p?yl.createElement(FJ,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function Rti(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var r3r=LJ(Qje,t3r);var n3r=tDe.forwardRef(function(t,e){return tDe.createElement(wce,Ws({},t,{ref:e,sideCar:r3r}))});n3r.classNames=wce.classNames;var iht=n3r;var vo=L(mt(),1),aht=["Enter"," "],Ati=["ArrowDown","PageUp","Home"],i3r=["ArrowUp","PageDown","End"],Iti=[...Ati,...i3r],Nti={ltr:[...aht,"ArrowRight"],rtl:[...aht,"ArrowLeft"]},jti={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Tce="Menu",[xce,Dti,$ti]=VHr(Tce),[qJ,sht]=dZ(Tce,[$ti,qmt,Wmt]),Ece=qmt(),a3r=Wmt(),[s3r,WB]=qJ(Tce),[Lti,Pce]=qJ(Tce),u3r=t=>{let{__scopeMenu:e,open:r=!1,children:n,dir:o,onOpenChange:i,modal:a=!0}=t,s=Ece(e),[u,l]=Lr.useState(null),c=Lr.useRef(!1),d=W_(i),f=JHr(o);return Lr.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,vo.jsx)(Umt,{...s,children:(0,vo.jsx)(s3r,{scope:e,open:r,onOpenChange:d,content:u,onContentChange:l,children:(0,vo.jsx)(Lti,{scope:e,onClose:Lr.useCallba
.block-interactivity-`.concat(t,` {pointer-events: none;}
.allow-interactivity-`).concat(t,` {pointer-events: all;}
`)},yoi=0,MZ=[];function o5r(t){var e=bl.useRef([]),r=bl.useRef([0,0]),n=bl.useRef(),o=bl.useState(yoi++)[0],i=bl.useState(a$)[0],a=bl.useRef(t);bl.useEffect(function(){a.current=t},[t]),bl.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var h=_Z([t.lockRef.current],(t.shards||[]).map(n5r),!0).filter(Boolean);return h.forEach(function(g){return g.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),h.forEach(function(g){return g.classList.remove("allow-interactivity-".concat(o))})}}},[t.inert,t.lockRef.current,t.shards]);var s=bl.useCallback(function(h,g){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!a.current.allowPinchZoom;var y=vDe(h),b=r.current,_="deltaX"in h?h.deltaX:b[0]-y[0],w="deltaY"in h?h.deltaY:b[1]-y[1],x,O=h.target,E=Math.abs(_)>Math.abs(w)?"h":"v";if("touches"in h&&E==="h"&&O.type==="range")return!1;var T=ngt(E,O);if(!T)return!0;if(T?x=E:(x=E==="v"?"h":"v",T=ngt(E,O)),!T)return!1;if(!n.current&&"changedTouches"in h&&(_||w)&&(n.current=x),!x)return!0;var R=n.current||x;return t5r(R,g,h,R==="h"?_:w,!0)},[]),u=bl.useCallback(function(h){var g=h;if(!(!MZ.length||MZ[MZ.length-1]!==i)){var y="deltaY"in g?r5r(g):vDe(g),b=e.current.filter(function(x){return x.name===g.type&&(x.target===g.target||g.target===x.shadowParent)&&hoi(x.delta,y)})[0];if(b&&b.should){g.cancelable&&g.preventDefault();return}if(!b){var _=(a.current.shards||[]).map(n5r).filter(Boolean).filter(function(x){return x.contains(g.target)}),w=_.length>0?s(g,_[0]):!a.current.noIsolation;w&&g.cancelable&&g.preventDefault()}}},[]),l=bl.useCallback(function(h,g,y,b){var _={name:h,delta:g,target:y,should:b,shadowParent:boi(y)};e.current.push(_),setTimeout(function(){e.current=e.current.filter(function(w){return w!==_})},1)},[]),c=bl.useCallback(function(h){r.current=vDe(h),n.current=void 0},[]),d=bl.useCallback(function(h){l(h.type,r5r(h),h.target,s(h,t.lockRef.current))},[]),f=bl.useCallback(function(h){l(h.type,vDe(h),h.target,s(h,t.lockRef.current))},[]);bl.useEffect(function(){return MZ.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,UJ),document.addEventListener("touchmove",u,UJ),document.addEventListener("touchstart",c,UJ),function(){MZ=MZ.filter(function(h){return h!==i}),document.removeEventListener("wheel",u,UJ),document.removeEventListener("touchmove",u,UJ),document.removeEventListener("touchstart",c,UJ)}},[]);var p=t.removeScrollBar,m=t.inert;return bl.createElement(bl.Fragment,null,m?bl.createElement(i,{styles:goi(o)}):null,p?bl.createElement(FJ,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function boi(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var i5r=LJ(_De,o5r);var a5r=wDe.forwardRef(function(t,e){return wDe.createElement(Dce,Ws({},t,{ref:e,sideCar:i5r}))});a5r.classNames=Dce.classNames;var ogt=a5r;var fm=L(mt(),1),SDe="Popover",[s5r,qws]=mDe(SDe,[Xht]),Lce=Xht(),[_oi,YB]=s5r(SDe),u5r=t=>{let{__scopePopover:e,children:r,open:n,defaultOpen:o,onOpenChange:i,modal:a=!1}=t,s=Lce(e),u=Zl.useRef(null),[l,c]=Zl.useState(!1),[d,f]=XKr({prop:n,defaultProp:o??!1,onChange:i,caller:SDe});return(0,fm.jsx)(VKr,{...s,children:(0,fm.jsx)(_oi,{scope:e,contentId:RKr(),triggerRef:u,open:d,onOpenChange:f,onOpenToggle:Zl.useCallback(()=>f(p=>!p),[f]),hasCustomAnchor:l,onCustomAnchorAdd:Zl.useCallback(()=>c(!0),[]),onCustomAnchorRemove:Zl.useCallback(()=>c(!1),[]),modal:a,children:r})})};u5r.displayName=SDe;var l5r="PopoverAnchor",voi=Zl.forwardRef((t,e)=>{let{__scopePopover:r,...n}=t,o=YB(l5r,r),i=Lce(r),{onCustomAnchorAdd:a,onCustomAnchorRemove:s}=o;return Zl.useEffect(()=>(a(),()=>s()),[a,s]),(0,fm.jsx)(Qht,{...i,...n,ref:e})});voi.displayName=l5r;var c5r="PopoverTrigger",d5r=Zl.forwardRef((t,e)=>{let{__scopePopover:r,...n}=t,o=YB(c5r,r),i=Lce(r),a=_w(e,o.triggerRef),s=(0,fm.jsx)(Db.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"dat
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function hii(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function gii(t){if(Array.isArray(t))return ggt(t)}function fWr(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),r.push.apply(r,n)}return r}function pWr(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?fWr(Object(r),!0).forEach(function(n){gWr(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):fWr(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}function gWr(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function qce(t,e){return _ii(t)||bii(t,e)||yWr(t,e)||yii()}function yii(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function yWr(t,e){if(t){if(typeof t=="string")return ggt(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return ggt(t,e)}}function ggt(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function bii(t,e){var r=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(r!=null){var n=[],o=!0,i=!1,a,s;try{for(r=r.call(t);!(o=(a=r.next()).done)&&(n.push(a.value),!(e&&n.length===e));o=!0);}catch(u){i=!0,s=u}finally{try{!o&&r.return!=null&&r.return()}finally{if(i)throw s}}return n}}function _ii(t){if(Array.isArray(t))return t}var vii=typeof jDe.default=="function"?jDe.default:jDe.default.default,wii="file-invalid-type",Sii="file-too-large",Cii="file-too-small",xii="too-many-files";var Oii=function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",r=e.split(","),n=r.length>1?"one of ".concat(r.join(", ")):r[0];return{code:wii,message:"File type must be ".concat(n)}},mWr=function(e){return{code:Sii,message:"File is larger than ".concat(e," ").concat(e===1?"byte":"bytes")}},hWr=function(e){return{code:Cii,message:"File is smaller than ".concat(e," ").concat(e===1?"byte":"bytes")}},bWr={code:xii,message:"Too many files"};function ygt(t,e){var r=t.type==="application/x-moz-file"||vii(t,e);return[r,r?null:Oii(e)]}function bgt(t,e,r){if(JJ(t.size))if(JJ(e)&&JJ(r)){if(t.size>r)return[!1,mWr(r)];if(t.size<e)return[!1,hWr(e)]}else{if(JJ(e)&&t.size<e)return[!1,hWr(e)];if(JJ(r)&&t.size>r)return[!1,mWr(r)]}return[!0,null]}function JJ(t){return t!=null}function _Wr(t){var e=t.files,r=t.accept,n=t.minSize,o=t.maxSize,i=t.multiple,a=t.maxFiles,s=t.validator;return!i&&e.length>1||i&&a>=1&&e.length>a?!1:e.every(function(u){var l=ygt(u,r),c=qce(l,1),d=c[0],f=bgt(u,n,o),p=qce(f,1),m=p[0],h=s?s(u):null;return d&&m&&!h})}function Bce(t){return typeof t.isPropagationStopped=="function"?t.isPropagationStopped():typeof t.cancelBubble<"u"?t.cancelBubble:!1}function Uce(t){return t.dataTransfer?Array.prototype.some.call(t.dataTransfer.types,function(e){return e==="Files"||e==="application/x-moz-file"}):!!t.target&&!!t.target.files}function _gt(t){t.preventDefault()}function Tii(t){return t.indexOf("MSIE")!==-1||t.indexOf("Trident/")!==-1}function Eii(t){return t.indexOf("Edge/")!==-1}function vWr(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.navigator.userAgent;return Tii(t)||Eii(t)}function Nx(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return function(n){for(var o=arguments.length,i=new Array(o>1?o-1:0),a=1;a<o;a++)i[a-1]=arguments[a];return e.some(function(s){return!Bce(n)&&s&&s.apply(void 0,[n].concat(i)),Bce(n)})}}function wWr(){return"showOpenFilePicker"in window}function SWr(t){if(JJ(t)){var e=Object.entries(t).filter(function(r){var n=qce(r,2),o=n[0],i=n[1],a=!0;return TWr(o)||(console.warn('Skipped "'.concat(o,'" because it is not a valid MIME type. Check https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for a list of valid MIME types.')),a=!1),(!Array.isArray(i)||!i.every(EWr))&&(console.warn('Skipped "'.concat(o,'" because an invalid file extension was provided.')),a=!1),a}).reduce(function(r,n){var o=qce(n,2),i=o[0],a=o[1];return pWr(pWr({},r),{},gWr({},i,a))},{});return[{description:"Files",accept:e}]}return t}function CWr(t){if(JJ(t))return Object.entries(t).reduce(function(e,r){var n=qce(r,2),o=n[0],i=n[1];return[].concat(dWr(e),[o],dWr(i))},[]).filter(function(e){return TWr(e)||EWr(e)}).join(",")}function xWr(t){return t instanceof DOMException&&(t.name==="AbortError"||t.code===t.ABORT_ERR)}function OWr(t){return t instanceof DOMException&&(t.name==="SecurityError"||t.code===t.SECURITY_ERR)}function TWr(t){return t==="audio/*"||t==="video/*"||t==="image/*"||t==="text/*"||t==="application/*"||/\w+\/[-+.\w]+/g.test(t)}
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function jii(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function Dii(t){if(Array.isArray(t))return wgt(t)}function vgt(t,e){return Fii(t)||Lii(t,e)||RWr(t,e)||$ii()}function $ii(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function RWr(t,e){if(t){if(typeof t=="string")return wgt(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return wgt(t,e)}}function wgt(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function Lii(t,e){var r=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(r!=null){var n=[],o=!0,i=!1,a,s;try{for(r=r.call(t);!(o=(a=r.next()).done)&&(n.push(a.value),!(e&&n.length===e));o=!0);}catch(u){i=!0,s=u}finally{try{!o&&r.return!=null&&r.return()}finally{if(i)throw s}}return n}}function Fii(t){if(Array.isArray(t))return t}function PWr(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),r.push.apply(r,n)}return r}function wc(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?PWr(Object(r),!0).forEach(function(n){Sgt(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):PWr(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}function Sgt(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function DDe(t,e){if(t==null)return{};var r=kii(t,e),n,o;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(o=0;o<i.length;o++)n=i[o],!(e.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function kii(t,e){if(t==null)return{};var r={},n=Object.keys(t),o,i;for(i=0;i<n.length;i++)o=n[i],!(e.indexOf(o)>=0)&&(r[o]=t[o]);return r}var xgt=(0,fi.forwardRef)(function(t,e){var r=t.children,n=DDe(t,Pii),o=Ogt(n),i=o.open,a=DDe(o,Mii);return(0,fi.useImperativeHandle)(e,function(){return{open:i}},[i]),fi.default.createElement(fi.Fragment,null,r(wc(wc({},a),{},{open:i})))});xgt.displayName="Dropzone";var AWr={disabled:!1,getFilesFromEvent:mgt,maxSize:1/0,minSize:0,multiple:!0,maxFiles:0,preventDropOnDocument:!0,noClick:!1,noKeyboard:!1,noDrag:!1,noDragEventsBubbling:!1,validator:null,useFsAccessApi:!1,autoFocus:!1};xgt.defaultProps=AWr;xgt.propTypes={children:yu.default.func,accept:yu.default.objectOf(yu.default.arrayOf(yu.default.string)),multiple:yu.default.bool,preventDropOnDocument:yu.default.bool,noClick:yu.default.bool,noKeyboard:yu.default.bool,noDrag:yu.default.bool,noDragEventsBubbling:yu.default.bool,minSize:yu.default.number,maxSize:yu.default.number,maxFiles:yu.default.number,disabled:yu.default.bool,getFilesFromEvent:yu.default.func,onFileDialogCancel:yu.default.func,onFileDialogOpen:yu.default.func,useFsAccessApi:yu.default.bool,autoFocus:yu.default.bool,onDragEnter:yu.default.func,onDragLeave:yu.default.func,onDragOver:yu.default.func,onDrop:yu.default.func,onDropAccepted:yu.default.func,onDropRejected:yu.default.func,onError:yu.default.func,validator:yu.default.func};var Cgt={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function Ogt(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=wc(wc({},AWr),t),r=e.accept,n=e.disabled,o=e.getFilesFromEvent,i=e.maxSize,a=e.minSize,s=e.multiple,u=e.maxFiles,l=e.onDragEnter,c=e.onDragLeave,d=e.onDragOver,f=e.onDrop,p=e.onDropAccepted,m=e.onDropRejected,h=e.onFileDialogCancel,g=e.onFileDialogOpen,y=e.useFsAccessApi,b=e.autoFocus,_=e.preventDropOnDocument,w=e.noClick,x=e.noKeyboard,O=e.noDrag,E=e.noDragEventsBubbling,T=e.onError,R=e.validator,N=(0,fi.useMemo)(function(){return CWr(r)},[r]),D=(0,fi.useMemo)(function(){return SWr(r)},[r]),F=(0,fi.useMemo)(function(){return typeof g=="function"?g:MWr},[g]),B=(0,fi.useMemo)(function(){return typeof h=="function"?h:MWr},[h]),U=(0,fi.useRef)(null),H=(0,fi.useRef)(null),G=(0,fi
`,tai=ZJ?"\xA0":d$e,T8r="\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC",E8r="A-Za-z\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u0300-\u0590\u0800-\u1FFF\u200E\u2C00-\uFB1C\uFE00-\uFE6F\uFEFD-\uFFFF",rai=new RegExp("^[^"+E8r+"]*["+T8r+"]"),nai=new RegExp("^[^"+T8r+"]*["+E8r+"]"),Ly={bold:1,capitalize:1024,code:16,highlight:c$e,italic:2,lowercase:256,strikethrough:Qce,subscript:32,superscript:64,underline:ede,uppercase:512},oai={directionless:1,unmergeable:2},NWr={center:pyt,end:yyt,justify:hyt,left:fyt,right:myt,start:gyt},iai={[pyt]:"center",[yyt]:"end",[hyt]:"justify",[fyt]:"left",[myt]:"right",[gyt]:"start"},aai={normal:0,segmented:2,token:1},sai={[Kii]:"normal",[Gii]:"segmented",[Wii]:"token"},uai="$",jWr="$config";function P8r(t,e,r,n,o,i){let a=t.getFirstChild();for(;a!==null;){let s=a.__key;a.__parent===e&&(Je(a)&&P8r(a,s,r,n,o,i),r.has(s)||i.delete(s),o.push(s)),a=a.getNextSibling()}}var lai=100,kgt=!1,byt=0;function cai(t){byt=t.timeStamp}function Tgt(t,e,r){let n=t.nodeName==="BR",o=e.__lexicalLineBreak;return o&&(t===o||n&&t.previousSibling===o)||n&&b$e(t,r)!==void 0}function dai(t,e,r){let n=LI(P0(r)),o=null,i=null;n!==null&&n.anchorNode===t&&(o=n.anchorOffset,i=n.focusOffset);let a=t.nodeValue;a!==null&&Fyt(e,a,o,i,!1)}function fai(t,e,r){if(nn(t)){let n=t.anchor.getNode();if(n.is(r)&&t.format!==n.getFormat())return!1}return FI(e)&&r.isAttached()}function pai(t,e,r,n){for(let o=t;o&&!XGr(o);o=dde(o)){let i=b$e(o,e);if(i!==void 0){let a=Jm(i,r);if(a)return Lu(a)||!kb(o)?void 0:[o,a]}else if(o===n)return[n,DGr(r)]}}function M8r(t,e,r){kgt=!0;let n=performance.now()-byt>lai;try{vw(t,()=>{let o=Ns()||function(f){return f.getEditorState().read(()=>{let p=Ns();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,g=pai(h,t,s,a);if(!g)continue;let[y,b]=g;if(m==="characterData")n&&xr(b)&&FI(h)&&fai(o,h,b)&&dai(h,b,t);else if(m==="childList"){l=!0;let _=p.addedNodes;for(let O=0;O<_.length;O++){let E=_[O],T=NGr(E),R=E.parentNode;if(R!=null&&E!==u&&T===null&&!Tgt(E,R,t)){if(ZJ){let N=(kb(E)?E.innerText:null)||E.nodeValue;N&&(c+=N)}R.removeChild(E)}}let w=p.removedNodes,x=w.length;if(x>0){let O=0;for(let E=0;E<x;E++){let T=w[E];(Tgt(T,h,t)||u===T)&&(h.appendChild(T),O++)}x!==O&&i.set(y,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 g=0;g<m.length;g++){let y=m[g],b=y.parentNode;b==null||y.nodeName!=="BR"||Tgt(y,h,t)||b.removeChild(y)}}r.takeRecords()}o!==null&&(l&&cv(o),ZJ&&BGr(t)&&o.insertRawText(c))})}finally{kgt=!1}}function R8r(t){let e=t._observer;e!==null&&M8r(t,e.takeRecords(),e)}function A8r(t){(function(e){byt===0&&P0(e).addEventListener("textInput",cai,!0)})(t),t._observer=new MutationObserver((e,r)=>{M8r(t,e,r)})}var qgt=class{constructor(e,r){this.key=e,this.parse=r.parse.bind(r),this.unparse=(r.unparse||yai).bind(r),this.isEqual=(r.isEqual||Object.is).bind(r),this.defaultValue=this.parse(void 0)}};function mai(t,e){return new qgt(t,e)}function WDe(t,e,r="latest"){let n=(r==="latest"?t.getLatest():t).__state;return n?n.getValue(e):e.defaultValue}function hai(t,e,r){let n=WDe(t,r,"direct"),o=WDe(e,r,"direct");return r.isEqual(n,o)?null:[n,o]}function gai(t,e,r){let n;if(Lh(),typeof r=="function"){let i=t.getLatest(),a=WDe(i,e);if(n=r(a),e.isEqual(a,n))return i}else n=r;let o=t.getWritable();return _yt(o).updateFromKnown(e,n),o}function I8r(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}=Hyt(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 Bgt=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(),lr(n,Jce,!1);else if(u===v$)r.preventDefault(),lr(n,Wgt,void 0);else if(u==null&&r.dataTransfer){let p=r.dataTransfer.getData("text/plain");r.preventDefault(),a.insertRawText(p)}else u!=null&&lGr(a,i,u,r.timeStamp,!0)?(r.preventDefault(),lr(n,qZ,u)):FZ=u;sGr=r.timeStamp}})}(t,e)]);var Kce=0,aGr=null,sGr=0,FZ=null,e$e=new WeakMap,Qgt=!1,eyt=!1,Wce=!1,zce=!1,Pgt=!1,Mgt="",WJ=null,uGr=[0,"",0,"root",0];function lGr(t,e,r,n,o){let i=t.anchor,a=t.focus,s=i.getNode(),u=Xl(),l=LI(P0(u)),c=l!==null?l.anchorNode:null,d=i.key,f=u.getElementByKey(d),p=r.length;return d!==a.key||!xr(s)||(!o&&(!VDe||sGr<n+50)||s.isDirty()&&p<2||$Gr(r))&&i.offset!==a.offset&&!s.isComposing()||m$(s)||s.isDirty()&&p>1||(o||!VDe)&&f!==null&&!s.isComposing()&&c!==t3(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 g=m.anchor.offset,y=h.getParentOrThrow(),b=oU(h);return g===0?!h.canInsertTextBefore()||!y.canInsertTextBefore()&&!h.isComposing()||b||function(_){let w=_.getPreviousSibling();return(xr(w)||Je(w)&&w.isInline())&&!w.canInsertTextAfter()}(h):g===h.getTextContentSize()&&(!h.canInsertTextAfter()||!y.canInsertTextAfter()&&!h.isComposing()||b)}(t,s)}function HWr(t,e){return FI(t)&&t.nodeValue!==null&&e!==0&&e!==t.nodeValue.length}function VWr(t,e,r){let{anchorNode:n,anchorOffset:o,focusNode:i,focusOffset:a}=t;Qgt&&(Qgt=!1,HWr(n,o)&&HWr(i,a)&&!WJ)||vw(e,()=>{if(!r)return void cv(null);if(!lde(e,n,i))return;let s=Ns();if(WJ&&nn(s)&&s.isCollapsed()){let u=s.anchor,l=WJ.anchor;(u.key===l.key&&u.offset===l.offset+1||u.offset===1&&l.getNode().is(u.getNode().getPreviousSibling()))&&(s=WJ.clone(),cv(s))}if(WJ=null,nn(s)){let u=s.anchor,l=u.getNode();if(s.isCollapsed()){t.type==="Range"&&t.anchorNode===t.focusNode&&(s.dirty=!0);let c=P0(e).event,d=c?c.timeStamp:performance.now(),[f,p,m,h,g]=uGr,y=lv(),b=e.isComposing()===!1&&y.getTextContent()==="";if(d<g+200&&u.offset===m&&u.key===h)UDe(s,f,p);else if(u.type==="text")xr(l)||We(141),cGr(s,l);else if(u.type==="element"&&!b){Je(l)||We(259);let _=u.getNode();_.isEmpty()?function(w,x){let O=x.getTextFormat(),E=x.getTextStyle();UDe(w,O,E)}(s,_):UDe(s,0,"")}}else{let c=u.key,d=s.focus.key,f=s.getNodes(),p=f.length,m=s.isBackward(),h=m?a:o,g=m?o:a,y=m?d:c,b=m?c:d,_=O8r,w=!1;for(let x=0;x<p;x++){let O=f[x],E=O.getTextContentSize();if(xr(O)&&E!==0&&!(x===0&&O.__key===y&&h===E||x===p-1&&O.__key===b&&g===0)&&(w=!0,_&=O.getFormat(),_===0))break}s.format=w?_:0}}lr(e,vyt,void 0)})}function UDe(t,e,r){t.format===e&&t.style===r||(t.format=e,t.style=r,t.dirty=!0)}function cGr(t,e){UDe(t,e.getFormat(),e.getStyle())}function dGr(t){if(!t.getTargetRanges)return null;let e=t.getTargetRanges();return e.length===0?null:e[0]}function $De(t,e){let r=t._compositionKey;if(Fh(null),r!==null&&e!=null){if(e===""){let n=Jm(r),o=t3(t.getElementByKey(r));return void(o!==null&&o.nodeValue!==null&&xr(n)&&Fyt(n,o.nodeValue,null,null,!0))}if(e[e.length-1]===`
`){let n=Ns();if(nn(n)){let o=n.focus;return n.anchor.set(o.key,o.offset,o.type),void lr(t,QDe,null)}}}Lyt(!0,t,e)}function fGr(t){let e=t.__lexicalEventHandles;return e===void 0&&(e=[],t.__lexicalEventHandles=e),e}var BZ=new Map;function pGr(t){let e=JGr(t.target);if(e===null)return;let r=Dyt(e.anchorNode);if(r===null)return;eyt&&(eyt=!1,vw(r,()=>{let u=n3(),l=e.anchorNode;(kb(l)||FI(l))&&cv(h$e(u,e,r,t))}));let n=$yt(r),o=n[n.length-1],i=o._key,a=BZ.get(i),s=a||o;s!==r&&VWr(e,s,!1),VWr(e,r,!0),r!==o?BZ.set(i,r):a&&BZ.delete(i)}function JWr(t){t._lexicalHandled=!0}function KWr(t){return t._lexicalHandled===!0}var Rai=()=>{};function Aai(t){let e=t.ownerDocument,r=e$e.get(e);if(r===void 0)return void Rai();let n=r-1;n>=0||We(164),e$e.set(e,n),n===0&&e.removeEventListener("selectionchange",pGr);let o=cde(t);y$e(o)?(function(a){if(a._parentEditor!==null){let s=$yt(a),u=s[s.length-1]._key;BZ.get(u)===a&&BZ.delete(u)}else BZ.delete(a._key)}(o),t.__lexicalEditor=null):o&&We(198);let i=fGr(t);for(let a=0;a<i.length;a++)i[a]();t.__lexicalEventHandles=[]}function tyt(t,e,r){Lh();let n=t.__key,o=t.getParent();if(o===null)return;let i=function(s){let u=Ns();if(!nn(u)||!Je(s))return u;let{anchor:l,focus:c}=u,d=l.getNode(),f=c.getNode();return u$e(d,s)&&l.set(s.__key,0,"element"),u$e(f,s)&&c.set(s.__key,0,"element"),u}(t),a=!1;if(nn(i)&&e){let s=i.anchor,u=i.focus;s.key===n&&(n$e(s,t,o,t.getPreviousSibling(),t.getNextSibling()),a=!0),u.key===n&&(n$e(u,t,o,t.getPreviousSibling(),t.getNextSibling()),a=!0)}else m$e(i)&&e&&t.isSelected()&&t.selectPrevious();if(nn(i)&&e&&!a){let s=t.getIndexWithinParent();iU(t),r$e(i,o,s,-1)}else iU(t);r||kx(o)||o.canBeEmpty()||!o.isEmpty()||tyt(o,e),e&&i&&sv(o)&&o.isEmpty()&&o.selectEnd()}function Iai(t){return t}var sU=class{static getType(){let{ownNodeType:e}=Hyt(this);return e===void 0&&We(64,this.name),e}static clone(e){We(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}),IGr(this,e)}getType(){return this.__type}isInline(){We(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||Ns();if(r==null)return!1;let n=r.getNodes().some(o=>o.__key===this.__key);if(xr(this))return n;if(nn(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&&We(66,this.__key),e}getTopLevelElement(){let e=this;for(;e!==null;){let r=e.getParent();if(kx(r))return Je(e)||e===this&&Lu(e)||We(194),e;e=r}return null}getTopLevelElementOrThrow(){let e=this.getTopLevelElement();return e===null&&We(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&&syt(n)){let o=n.firstChild;if(o===r||o.nextSibling===r&&LDe(o)){let i=n.lastChild;if(i===r||i.previousSibling===r&&LDe(i))return!0}}return!1}(e)||function(r){let n=r.parentElement;if(n!==null&&syt(n)){let o=n.firstChild;if(o===r||o.nextSibling===r&&LDe(o))return!1;let i=n.lastChild;if(i===r||i.previousSibling===r&&LDe(i))return!0}return!1}(e)?null:{conversion:Nai,priority:0}}}static importJSON(e){return JZ().updateFromJSON(e)}};function Nai(t){return{node:JZ()}}function JZ(){return fde(new VZ)}function GJ(t){return t instanceof VZ}function LDe(t){return FI(t)&&/^( |\t|\r?\n)+$/.test(t.textContent||"")}function Rgt(t,e){return 16&e?"code":e&c$e?"mark":32&e?"sub":64&e?"sup":null}function Agt(t,e){return 1&e?"strong":2&e?"em":"span"}function mGr(t,e,r,n,o){let i=n.classList,a=UZ(o,"base");a!==void 0&&i.add(...a),a=UZ(o,"underlineStrikethrough");let s=!1,u=e&ede&&e&Qce;a!==void 0&&(r&ede&&r&Qce?(s=!0,u||i.add(...a)):u&&i.remove(...a));for(let l in Ly){let c=Ly[l];if(a=UZ(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 hGr(t,e,r){let n=e.firstChild,o=r.isComposing(),i=t+(o?d$e:"");if(n==null)e.textContent=i;else{let a=n.nodeValue;if(a!==i)if(o||ZJ){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 WWr(t,e,r,n,o,i){hGr(o,t,e);let a=i.theme.text;a!==void 0&&mGr(0,0,n,t,a)}function FDe(t,e){let r=document.createElement(e);return r.appendChild(t),r}var QJ=class t extends sU{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 sai[e.__mode]}getStyle(){return this.getLatest().__style}isToken(){return this.getLatest().__mode===1}isComposing(){return this.__key===nU()}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 a$e(this.getLatest().__format,e,r)}canHaveFormat(){return!0}isInline(){return!0}createDOM(e,r){let n=this.__format,o=Rgt(0,n),i=Agt(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)),WWr(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=Rgt(0,i),u=Rgt(0,a),l=Agt(0,i),c=Agt(0,a);if((s===null?l:s)!==(u===null?c:u))return!0;if(s===u&&l!==c){let h=r.firstChild;h==null&&We(48);let g=document.createElement(c);return WWr(g,this,0,a,o,n),r.replaceChild(g,h),!1}let d=r;u!==null&&s!==null&&(d=r.firstChild,d==null&&We(49)),hGr(o,d,this);let f=n.theme.text;f!==void 0&&i!==a&&mGr(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:Lai,priority:0}),b:()=>({conversion:Dai,priority:0}),code:()=>({conversion:f$,priority:0}),em:()=>({conversion:f$,priority:0}),i:()=>({conversion:f$,priority:0}),mark:()=>({conversion:f$,priority:0}),s:()=>({conversion:f$,priority:0}),span:()=>({conversion:jai,priority:0}),strong:()=>({conversion:f$,priority:0}),sub
`||s===`\r
`?o.push(JZ()):s===" "?o.push(p$e()):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=ZWr(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=ZWr(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 ZWr(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,kb(r)){let i=r.style.display;if(i===""&&!WGr(r)||i!==""&&!i.startsWith("inline"))return null}let o=r;for(;(o=e?r.firstChild:r.lastChild)!==null;)r=o;if(FI(r))return r;if(r.nodeName==="BR")return null}}var Fai={code:"code",em:"italic",i:"italic",mark:"highlight",s:"strikethrough",strong:"bold",sub:"subscript",sup:"superscript",u:"underline"};function f$(t){let e=Fai[t.nodeName.toLowerCase()];return e===void 0?{node:null}:{forChild:Tyt(t.style,e),node:null}}function $h(t=""){return fde(new QJ(t))}function xr(t){return t instanceof QJ}function Tyt(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=>(xr(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 KZ=class t extends QJ{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=UZ(e.theme,"tab");return n!==void 0&&r.classList.add(...n),r}static importJSON(e){return p$e().updateFromJSON(e)}setTextContent(e){return e!==" "&&e!==""&&We(126),super.setTextContent(" ")}spliceText(e,r,n,o){return n===""&&r===0||n===" "&&r===1||We(286),this}setDetail(e){return e!==2&&We(127),this}setMode(e){return e!=="normal"&&We(128),this}canInsertTextBefore(){return!1}canInsertTextAfter(){return!1}};function p$e(){return fde(new KZ)}function Eyt(t){return t instanceof KZ}var ryt=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:Wyt(jx(dU(this,"next")),jx(dU(e,"next")))<0}getNode(){let e=Jm(this.key);return e===null&&We(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,nX()||(nU()===a&&Fh(e),i!==null&&(i.setCachedNodes(null),i.dirty=!0)))}};function Fx(t,e,r){return new ryt(t,e,r)}function Igt(t,e){let r=e.__key,n=t.offset,o="element";if(xr(e)){o="text";let i=e.getTextContentSize();n>i&&(n=i)}else if(!Je(e)){let i=e.getNextSibling();if(xr(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 XWr(t,e){if(Je(e)){let r=e.getLastDescendant();Je(r)||xr(r)?Igt(t,r):Igt(t,e)}else Igt(t,e)}var t$e=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(!m$e(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,xr(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)&&!GJ(f)||f===n&&this.isCollapsed()||(l+=f.getTextContent())}return l}applyDOMRange(e){let r=Xl(),n=r.getEditorState()._selection,o=yGr(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),GDe(this)}clone(){let e=this.anchor,r=this.focus;return new t(Fx(e.key,e.offset,e.type),Fx(r.key,r.offset,r.type),this.format,this.style)}toggleFormat(e){this.format=a$e(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(JZ()):a===" "?n.push(p$e()):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(g,y,b,_){let w=g.getNode(),x=w.getChildAtIndex(g.offset),O=$h(),E=sv(w)?b$().append(O):O;O.setFormat(b),O.setStyle(_),x===null?w.append(E):x.insertBefore(E),g.is(y)&&y.set(O.__key,0,"text"),g.set(O.__key,0,"text")}(a,s,o,i),s.type==="element"&&rX(s,jx(dU(s,"next")));let u=a.offset,l=s.offset,c=this.getNodes(),d=c.length,f=c[0];xr(f)||We(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&&(m$(f)||!f.canInsertTextAfter()||!m.canInsertTextAfter()&&f.getNextSibling()===null)){let g=f.getNextSibling();if(xr(g)&&g.canInsertTextBefore()&&!m$(g)||(g=$h(),g.setFormat(o),g.setStyle(i),m.canInsertTextAfter()?f.insertAfter(g):m.insertAfter(g)),g.select(0,0),f=g,e!=="")return void this.insertText(e)}else if(this.isCollapsed()&&u===0&&(m$(f)||!f.canInsertTextBefore()||!m.canInsertTextBefore()&&f.getPreviousSibling()===null)){let g=f.getPreviousSibling();if(xr(g)&&!m$(g)||(g=$h(),g.setFormat(o),m.canInsertTextBefore()?f.insertBefore(g):m.insertBefore(g)),g.select(),f=g,e!=="")return void this.insertText(e)}else if(f.isSegmented()&&u!==p){let g=$h(f.getTextContent());g.setFormat(o),f.replace(g),f=g}else if(!this.isCollapsed()&&e!==""){let g=h.getParent();if(!m.canInsertTextBefore()||!m.canInsertTextAfter()||Je(g)&&(!g.canInsertTextBefore()||!g.canInsertTextAfter()))return this.insertText(""),gGr(this.anchor,this.focus,null),void this.insertText(e)}if(d===1){if(oU(f)){let _=$h(e);return _.select(),void f.replace(_)}let g=f.getFormat(),y=f.getStyle();if(u!==l||g===o&&y===i){if(Eyt(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=g,this.style=y))}else{let g=new Set([...f.getParentKeys(),...h.getParentKeys()]),y=Je(f)?f:f.getParentOrThrow(),b=Je(h)?h:h.getParentOrThrow(),_=h;if(!y.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(xr(h)&&!oU(h)&&l!==h.getTextContentSize()){if(h.isSegmented()){let T=$h(h.getTextContent());h.replace(T),h=T}sv(s.getNode())||s.type!=="text"||(h=h.spliceText(0,l,"")),g.add(h.__key)}else{let T=h.getParentOrThrow();T.canBeEmpty()||T.getChildrenSize()!==1?h.remove():T.remove()}else g.add(h.__key);let w=b.getChildren(),x=new Set(c),O=y.is(b),E=y.isInline()&&f.getNextSibling()===null?y:f;for(let T=w.length-1;T>=0;T--){let R=w[T];if(R.is(f)||Je(R)&&R.isParentOf(f))break;R.isAttached()&&(!x.has(R)||R.is(_)?O||E.insertAfter(R,!1):R.remove())}if(!O){let T=b,R=null;for(;T!==null;){let N=T.getChildren(),D=N.length;(D===0||N[D-1].is(R))&&(g.delete(T.__key),R=T),T=T.getParent()}}if(oU(f))if(u===p)f.select();else{let T=$h(e);T.select(),f.replace(T)}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 T=1;T<d;T++){let R=c[T],N=R.__key;g.has(N)||R.remove()}}}removeText(){let e=Ns()===this;Xce(this,t9r(dyt(this))),e&&Ns()!==this&&cv(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)xr(w)&&o.push(w);let i=w=>{n.forEach(x=>{if(Je(x)){let O=x.getFormatFlags(e,w);x.setTextFormat(O)}})},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(!Ui(n)||o>=u){let l=n.getParent();n.remove(),l==null||l.getChildrenSize()!==0||sX(l)||l.remove(),o-=u+a,n=i}else{let l=n.getKey(),c=t.getEditorState().read(()=>{let p=c9r(l);return Ui(p)&&p.isSimpleText()?p.getTextContent():null}),d=u-o,f=s.slice(0,d);if(c!==null&&c!==s){let p=mde(),m=n;if(n.isSimpleText())n.setTextContent(c);else{let h=ww(c);n.replace(h),m=h}if(Pr(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,g=p?m:d;if(p&&h===0){let[y]=n.splitText(h,g);y.remove()}else{let[,y]=n.splitText(h,g);y.remove()}}else{let p=ww(f);n.replace(p)}o=0}}}function _ui(t){let e=t.getStyle(),r=J7r(e);Z$e.set(e,r)}function wbt(t,e){(Pr(t)?t.isCollapsed():Ui(t)||ii(t))||xbt(280);let r=X$e(Pr(t)?t.style:Ui(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=K7r(n);Pr(t)||Ui(t)?t.setStyle(o):t.setTextStyle(o),Z$e.set(o,n)}function vui(t,e){if(Pr(t)&&t.isCollapsed()){wbt(t,e);let r=t.anchor.getNode();ii(r)&&r.isEmpty()&&wbt(r,e)}G7r(r=>{wbt(r,e)})}function G7r(t){let e=cn();if(!e)return;let r=new Map;if(Pr(e))for(let i of o9r(e).getTextSlices())i&&r.set(i.caret.origin.getKey(),i.getSliceIndices());let n=e.getNodes();for(let i of n){if(!Ui(i)||!i.canHaveFormat())continue;let[a,s]=(o=i,r.get(o.getKey())||[0,o.getTextContentSize()]);s!==a&&(tbt(i)||a===0&&s===i.getTextContentSize()?t(i):t(i.splitText(a,s)[a===0?0:1]))}var o;Pr(e)&&e.anchor.type==="text"&&e.focus.type==="text"&&e.anchor.key===e.focus.key&&Z7r(e)}function Z7r(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 X7r(t,e){let r=t.getFormatType(),n=t.getIndent();r!==e.getFormatType()&&e.setFormat(r),n!==e.getIndent()&&e.setIndent(n)}function wui(t,e,r=X7r){if(t===null)return;let n=t.getStartEndPoints(),o=new Map,i=null;if(n){let[a,s]=n;i=w$e(),i.anchor.set(a.key,a.offset,a.type),i.focus.set(s.key,s.offset,s.type);let u=Cbt(a.getNode(),bde),l=Cbt(s.getNode(),bde);ii(u)&&o.set(u.getKey(),u),ii(l)&&o.set(l.getKey(),l)}for(let a of t.getNodes())if(ii(a)&&bde(a))o.set(a.getKey(),a);else if(n===null){let s=Cbt(a,bde);ii(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(cn())&&i3(i)}function V7r(t){return t.getNode().isAttached()}function Sui(t){let e=t;for(;e!==null&&!o3(e);){let r=e.getLatest(),n=e.getParent();r.getChildrenSize()===0&&e.remove(!0),e=n}}function Cui(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];o3(c)?(Sbt(t,u,u.length,e,r),u=[],s=c):s===null||s!==null&&f9r(c,s)?u.push(c):(Sbt(t,u,u.length,e,r),u=[c])}Sbt(t,u,u.length,e,r)}function Sbt(t,e,r,n,o=null){if(e.length===0)return;let i=e[0],a=new Map,s=[],u=ii(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(),o3(u))break}let c=new Set;for(let m=0;m<r;m++){let h=e[m];ii(h)&&h.getChildrenSize()===0&&c.add(h.getKey())}let d=new Set;for(let m=0;m<r;m++){let h=e[m],g=h.getParent();if(g!==null&&g.isInline()&&(g=g.getParent()),g!==null&&m9r(h)&&!d.has(h.getKey())){let y=g.getKey();if(a.get(y)===void 0){let b=n();b.setFormat(g.getFormatType()),b.setIndent(g.getIndent()),s.push(b),a.set(y,b),g.getChildren().forEach(_=>{b.append(_),d.add(_.getKey()),ii(_)&&_.getChildrenKeys().forEach(w=>d.add(w))}),Sui(g)}}else if(c.has(h.getKey())){ii(h)||xbt(179);let y=n();y.setFormat(h.getFormatType()),y
`||c===`\r
`?l.insertParagraph():c===" "?l.insertNodes([i9r()]):l.insertText(c)}}}else e.insertRawText(a)}function $bt(t,e,r){t.dispatchCommand(K9r,{nodes:e,selection:r})||(r.insertNodes(e),function(n){if(Pr(n)&&n.isCollapsed()){let o=n.anchor,i=null,a=aX(o,"previous");if(a)if(O$e(a))i=a.origin;else{let s=s9r(a,hU(es(),"next").getFlipped());for(let u of s){if(Ui(u.origin)){i=u.origin;break}if(ii(u.origin)&&!u.origin.isInline())break}}if(i&&Ui(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 RZr(t,e,r,n=[]){let o=e===null||r.isSelected(e),i=ii(r)&&r.excludeFromCopy("html"),a=r;if(e!==null){let l=mU(r);l=Ui(l)&&e!==null?Y$e(e,l):l,a=l}let s=ii(a)?a.getChildren():[],u=function(l){let c=l.exportJSON(),d=l.constructor;if(c.type!==d.getType()&&eLe(58,d.name),ii(l)){let f=c.children;Array.isArray(f)||eLe(59,d.name)}return c}(a);if(Ui(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=RZr(t,e,c,u.children);!o&&ii(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 AZr(t,e){let r=[],n=es().getChildren();for(let o=0;o<n.length;o++)RZr(t,e,n[o],r);return{namespace:t._config.namespace,nodes:r}}function IZr(t){let e=[];for(let r=0;r<t.length;r++){let n=t[r],o=b9r(n);Ui(o)&&eZr(o),e.push(o)}return e}var bX=null;async function xli(t,e,r){if(bX!==null)return!1;if(e!==null)return new Promise((l,c)=>{t.update(()=>{l(EZr(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(P$e,f=>(Rde(f,ClipboardEvent)&&(d(),bX!==null&&(window.clearTimeout(bX),bX=null),l(EZr(t,f,r))),!0),E$e);bX=window.setTimeout(()=>{d(),bX=null,l(!1)},50),i.execCommand("copy"),s.remove()})}function EZr(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&&!r7r(t,i,a))return!1;let s=cn();if(s===null)return!1;r=NZr(s)}e.preventDefault();let n=e.clipboardData;return n!==null&&(jZr(n,r),!0)}var Oli=[["text/html",PZr],["application/x-lexical-editor",MZr]];function NZr(t=cn()){let e={"text/plain":t?t.getTextContent():""};if(t){let r=S$e();for(let[n,o]of Oli){let i=o(r,t);i!==null&&(e[n]=i)}}return e}function jZr(t,e){for(let r in e){let n=e[r];n!==void 0&&t.setData(r,n)}}var UI=Lbt,HPs=UI.$generateJSONFromSelectedNodes,VPs=UI.$generateNodesFromSerializedNodes,JPs=UI.$getClipboardDataFromSelection,DZr=UI.$getHtmlContent,KPs=UI.$getLexicalContent,Fbt=UI.$insertDataTransferForPlainText,WPs=UI.$insertDataTransferForRichText,GPs=UI.$insertGeneratedNodes,ZPs=UI.copyToClipboard,XPs=UI.setLexicalClipboardDataTransfer;var kbt={};Xn(kbt,{registerPlainText:()=>Ali});var _X=typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0,Tli=_X&&"documentMode"in document?document.documentMode:null,Eli=!(!_X||!("InputEvent"in window)||Tli)&&"getTargetRanges"in new window.InputEvent("input"),Pli=_X&&/Version\/[\d.]+.*Safari/.test(navigator.userAgent),$Zr=_X&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,Mli=_X&&/^(?=.*Chrome).*/i.test(navigator.userAgent),Rli=_X&&/AppleWebKit\/[\d.]+/.test(navigator.userAgent)&&!Mli;function LZr(t,e){e.update(()=>{if(t!==null){let r=Rde(t,KeyboardEvent)?null:t.clipboardData,n=cn();if(n!==null&&r!=null){t.preventDefault();let o=DZr(e);o!==null&&r.setData("text/html",o),r.setData("text/plain",n.getTextContent())}}})}function Ali(t){return T$(t.registerCommand(uX,e=>{let r=cn();return!!Pr(r)&&(r.deleteCharacter(e),!0)},Zu),t.registerCommand(A9r,e=>{let r=cn();return!!Pr(r)&&(r.deleteWord(e),!0)},Zu),t.registerCommand(R9r,e=>{let r=cn();return!!Pr(r)&&(r.deleteLine(e),!0)},Zu),t.registerCommand(P9r,e=>{let r=cn();if(!Pr(r))return!1;if(ty
.block-interactivity-`.concat(t,` {pointer-events: none;}
.allow-interactivity-`).concat(t,` {pointer-events: all;}
`)},$di=0,EX=[];function pQr(t){var e=_l.useRef([]),r=_l.useRef([0,0]),n=_l.useRef(),o=_l.useState($di++)[0],i=_l.useState(a$)[0],a=_l.useRef(t);_l.useEffect(function(){a.current=t},[t]),_l.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var h=_Z([t.lockRef.current],(t.shards||[]).map(fQr),!0).filter(Boolean);return h.forEach(function(g){return g.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),h.forEach(function(g){return g.classList.remove("allow-interactivity-".concat(o))})}}},[t.inert,t.lockRef.current,t.shards]);var s=_l.useCallback(function(h,g){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!a.current.allowPinchZoom;var y=PLe(h),b=r.current,_="deltaX"in h?h.deltaX:b[0]-y[0],w="deltaY"in h?h.deltaY:b[1]-y[1],x,O=h.target,E=Math.abs(_)>Math.abs(w)?"h":"v";if("touches"in h&&E==="h"&&O.type==="range")return!1;var T=E_t(E,O);if(!T)return!0;if(T?x=E:(x=E==="v"?"h":"v",T=E_t(E,O)),!T)return!1;if(!n.current&&"changedTouches"in h&&(_||w)&&(n.current=x),!x)return!0;var R=n.current||x;return cQr(R,g,h,R==="h"?_:w,!0)},[]),u=_l.useCallback(function(h){var g=h;if(!(!EX.length||EX[EX.length-1]!==i)){var y="deltaY"in g?dQr(g):PLe(g),b=e.current.filter(function(x){return x.name===g.type&&(x.target===g.target||g.target===x.shadowParent)&&jdi(x.delta,y)})[0];if(b&&b.should){g.cancelable&&g.preventDefault();return}if(!b){var _=(a.current.shards||[]).map(fQr).filter(Boolean).filter(function(x){return x.contains(g.target)}),w=_.length>0?s(g,_[0]):!a.current.noIsolation;w&&g.cancelable&&g.preventDefault()}}},[]),l=_l.useCallback(function(h,g,y,b){var _={name:h,delta:g,target:y,should:b,shadowParent:Ldi(y)};e.current.push(_),setTimeout(function(){e.current=e.current.filter(function(w){return w!==_})},1)},[]),c=_l.useCallback(function(h){r.current=PLe(h),n.current=void 0},[]),d=_l.useCallback(function(h){l(h.type,dQr(h),h.target,s(h,t.lockRef.current))},[]),f=_l.useCallback(function(h){l(h.type,PLe(h),h.target,s(h,t.lockRef.current))},[]);_l.useEffect(function(){return EX.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,b3),document.addEventListener("touchmove",u,b3),document.addEventListener("touchstart",c,b3),function(){EX=EX.filter(function(h){return h!==i}),document.removeEventListener("wheel",u,b3),document.removeEventListener("touchmove",u,b3),document.removeEventListener("touchstart",c,b3)}},[]);var p=t.removeScrollBar,m=t.inert;return _l.createElement(_l.Fragment,null,m?_l.createElement(i,{styles:Ddi(o)}):null,p?_l.createElement(FJ,{gapMode:t.gapMode}):null)}function Ldi(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var mQr=LJ(ELe,pQr);var hQr=MLe.forwardRef(function(t,e){return MLe.createElement(Nde,Ws({},t,{ref:e,sideCar:mQr}))});hQr.classNames=Nde.classNames;var Dde=hQr;var pn=L(mt(),1),Fdi=[" ","Enter","ArrowUp","ArrowDown"],kdi=[" ","Enter"],Lde="Select",[ALe,ILe,qdi]=xYr(Lde),[PX,yjs]=TB(Lde,[qdi,__t]),NLe=__t(),[Bdi,TU]=PX(Lde),[Udi,zdi]=PX(Lde),gQr=t=>{let{__scopeSelect:e,children:r,open:n,defaultOpen:o,onOpenChange:i,value:a,defaultValue:s,onValueChange:u,dir:l,name:c,autoComplete:d,disabled:f,required:p,form:m}=t,h=NLe(e),[g,y]=Ht.useState(null),[b,_]=Ht.useState(null),[w,x]=Ht.useState(!1),O=OYr(l),[E=!1,T]=GD({prop:n,defaultProp:o,onChange:i}),[R,N]=GD({prop:a,defaultProp:s,onChange:u}),D=Ht.useRef(null),F=g?m||!!g.closest("form"):!0,[B,U]=Ht.useState(new Set),H=Array.from(B).map(G=>G.props.value).join(";");return(0,pn.jsx)(QYr,{...h,children:(0,pn.jsxs)(Bdi,{required:p,scope:e,trigger:g,onTriggerChange:y,valueNode:b,onValueNodeChange:_,valueNodeHasChildren:w,onValueNodeHasChildrenChange:x,contentId:JI(),value:R,onValueChange:N,open:E,onOpenChange:T,dir:O,triggerPointerDownPosRef:D,disabled:f,children:[(0,pn.jsx)(ALe.Provider,{scope:e,children:(0,pn.jsx)(Udi,{scope:t.__scopeSelect,onNativeOptionAdd:Ht.useCallback(G=>{U(ie=>new Set(ie).add(G))},[]),onN
\u2026 (truncated ${(r.length-Fde).toLocaleString()} characters for display)`:r}catch{return e.length>Fde?`Tool '${t}' returned ${e.length.toLocaleString()} characters. The full output is preserved in chat history but omitted here to keep the UI responsive.`:e}},fen=({toolName:t,displayName:e,emoji:r,isExecuting:n,result:o,confirmationMessage:i,onAccept:a,onReject:s})=>{let[u,l]=(0,Xu.useState)(!1),c=(0,Xu.useMemo)(()=>bfi(t,o),[t,o]),d=!n&&c!==null;return Xu.default.createElement(Zx,{open:d?u:!1,onOpenChange:l,disabled:!d,"aria-disabled":!d,className:"tw-my-3 tw-w-full sm:tw-max-w-sm"},Xu.default.createElement("div",{className:Oe("tw-rounded-md tw-border tw-border-border tw-bg-secondary/50",n&&"tw-relative tw-overflow-hidden")},n&&Xu.default.createElement("div",{className:"tw-absolute tw-inset-0 tw-z-[1] tw-overflow-hidden"},Xu.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:yfi}})),Xu.default.createElement(D$,{className:Oe("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",d&&"hover:tw-bg-secondary/70",!d&&"tw-cursor-default")},Xu.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Xu.default.createElement("span",{className:"tw-text-base"},r),Xu.default.createElement("span",{className:"tw-font-medium"},t==="readNote"?`${n?"Reading":"Read"} ${e}`:`${n?"Calling":"Called"} ${e}`,n&&t!=="readNote"&&"..."),n&&i&&Xu.default.createElement("span",{className:"tw-text-xs tw-text-muted"},"\u2022 ",i,"...")),Xu.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},!n&&a&&s&&Xu.default.createElement(Xu.default.Fragment,null,Xu.default.createElement("button",{onClick:f=>{f.stopPropagation(),a()},className:"hover:tw-bg-green-rgb/20 tw-rounded tw-p-1",title:"Accept"},Xu.default.createElement(Uu,{className:"tw-size-4 tw-text-success"})),Xu.default.createElement("button",{onClick:f=>{f.stopPropagation(),s()},className:"hover:tw-bg-red-rgb/20 tw-rounded tw-p-1",title:"Reject"},Xu.default.createElement(pi,{className:"tw-size-4 tw-text-error"}))),d&&Xu.default.createElement(tg,{className:Oe("tw-size-4 tw-text-muted tw-transition-transform",u&&"tw-rotate-90")}))),Xu.default.createElement(Xx,null,Xu.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"},Xu.default.createElement("div",{className:"tw-text-sm tw-text-muted"},Xu.default.createElement("pre",{className:"tw-overflow-x-auto tw-whitespace-pre-wrap tw-font-mono tw-text-xs"},c??"No result available"))))))};Dt();var pen=60*60*1e3,kde=()=>(window.__copilotToolCallRoots||(window.__copilotToolCallRoots=new Map),window.__copilotToolCallRoots),qde=()=>(window.__copilotErrorBlocks||(window.__copilotErrorBlocks=new Map),window.__copilotErrorBlocks),men=(t,e,r)=>{if(e.size>0)return;r.get(t)===e&&r.delete(t)},Q_t=(t,e,r,n,o,i)=>{try{n.root.unmount()}catch(a){Ot(`Error unmounting tool call root during ${o}`,r,a)}n.isUnmounting=!1,e.get(r)===n&&e.delete(r),men(t,e,i)},AX=(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,men(t,e,i);return}Q_t(t,a,r,s,o,i)},0))},hen=(t,e,r,n,o)=>{let i=e.get(r);return i?.isUnmounting&&(Q_t(t,e,r,i,`${o} (finalizing stale root)`,kde()),i=void 0),i||(i={root:(0,Y_t.createRoot)(n),isUnmounting:!1},e.set(r,i)),i},gen=(t,e,r,n,o)=>{let i=e.get(r);return i?.isUnmounting&&(Q_t(t,e,r,i,`${o} (finalizing stale error root)`,qde()),i=void 0),i||(i={root:(0,Y_t.createRoot)(n),isUnmounting:!1},e.set(r,i)),i},yen=(t,e)=>{t.root.render(X_t.default.createElement(fen,{toolName:e.toolName,displayName:e.displayName,emoji:e.emoji,isExecuting:e.isExecuting,result:e.result||null,confirmationMessage:e.confirmationMessage}))},ben=(t,e)=>{t.root.render(X_t.default.createElement(ren,{errorContent:e.errorContent}))},_en=(t,e,r,n)=>{let o=e.get(r);o&&AX(t,e,r,o,n,kde())},ven=(t,e,r,n)=>{let o=e.get(r);o&&AX(t,e,r,o
<summary style="${V}">${j}</summary>
<div class="tw-text-muted" style="${se}">${Ze.trim()}</div>
</details>
`);let ht=new RegExp(`<${Y}>([\\s\\S]*)$`);return q=q.replace(ht,(Rt,Ze)=>`<div style="${W}">
<div style="${V}">${A}</div>
<div class="tw-text-muted" style="${se}">${Ze.trim()}</div>
</div>`),q}let Ee=new RegExp(`<${Y}>([\\s\\S]*?)<\\/${Y}>`,"g");return q.replace(Ee,(Ae,ht)=>`<details style="${W}">
<summary style="${V}">${j}</summary>
<div class="tw-text-muted" style="${se}">${ht.trim()}</div>
</details>
`)},U=q=>B(q,"think","Thought for a while","Thinking..."),H=q=>{let Y=W=>{let V=/```(?:xml)?\s*([\s\S]*?<writeToFile>[\s\S]*?<\/writeToFile>[\s\S]*?)\s*```/g;return W.replace(V,(se,be)=>be.trim())},j=W=>{if(!r)return W;let V=/```xml\s*([\s\S]*?<writeToFile>[\s\S]*?)$/g;return W.replace(V,(se,be)=>be.trim())},A=Y(q);return A=j(A),B(A,"writeToFile","Generated new content","Generating changes...")},G=(q,Y,j)=>q.split(/(```[\s\S]*?```|`[^`]*`)/g).map((W,V)=>V%2===0?W.replace(Y,(se,be)=>{let Ee=e.metadataCache.getFirstLinkpathDest(be,D);return Ee?j(Ee):se}):W).join(""),oe=F(R).replace(/\\\[\s*/g,"$$").replace(/\s*\\\]/g,"$$").replace(/\\\(\s*/g,"$").replace(/\s*\\\)/g,"$"),z=G(oe,/!\[\[(.*?)]]/g,q=>`![](${e.vault.getResourcePath(q)})`),Q=U(z),re=H(Q),Z=kqr(re,a.enableInlineCitations);return G(Z,/(?<!!)\[\[([^\]]+)]]/g,q=>`<a href="obsidian://open?file=${encodeURIComponent(q.path)}">${q.basename}</a>`)},[e,r,a.enableInlineCitations]);(0,Yr.useEffect)(()=>{if(p.current=!1,d.current&&t.sender!==Xs){f.current||(f.current=new w3.Component);let R=t.message,N=b(R),D=hot(N,m.current);if(!p.current){let F=new Set,B=new Set;d.current.querySelectorAll('[id^="tool-call-"]').forEach(Q=>{let re=Q.id.replace("tool-call-","");F.add(re)}),d.current.querySelectorAll('[id^="error-block-"]').forEach(Q=>{let re=Q.id.replace("error-block-","");B.add(re)}),d.current.querySelectorAll(".message-segment").forEach(Q=>Q.remove());let ie=0;D.segments.forEach(Q=>{if(Q.type==="text"&&Q.content.trim()){let re=d.current.children[ie],Z=document.createElement("div");Z.className="message-segment",re?d.current.insertBefore(Z,re):d.current.appendChild(Z),w3.MarkdownRenderer.renderMarkdown(Q.content,Z,"",f.current),vfi(Z),ie++}else if(Q.type==="toolCall"&&Q.toolCall){let re=Q.toolCall.id,Z=document.getElementById(`tool-call-${re}`);if(!Z){let q=d.current.children[ie],Y=document.createElement("div");Y.className="tool-call-container",Y.id=`tool-call-${re}`,q?d.current.insertBefore(Y,q):d.current.appendChild(Y),Z=Y}let $=hen(m.current,h.current,re,Z,"render refresh");!p.current&&!$.isUnmounting&&yen($,Q.toolCall),ie++}else if(Q.type==="error"&&Q.error){let re=Q.error.id,Z=document.getElementById(`error-block-${re}`);if(!Z){let q=d.current.children[ie],Y=document.createElement("div");Y.className="error-block-container",Y.id=`error-block-${re}`,q?d.current.insertBefore(Y,q):d.current.appendChild(Y),Z=Y}let $=gen(m.current,g.current,re,Z,"error render");!p.current&&!$.isUnmounting&&ben($,Q.error),ie++}});let oe=new Set(D.segments.filter(Q=>Q.type==="toolCall"&&Q.toolCall).map(Q=>Q.toolCall.id));F.forEach(Q=>{if(!oe.has(Q)){let re=document.getElementById(`tool-call-${Q}`);re&&(_en(m.current,h.current,Q,"tool call removal"),re.remove())}});let z=new Set(D.segments.filter(Q=>Q.type==="error"&&Q.error).map(Q=>Q.error.id));B.forEach(Q=>{if(!z.has(Q)){let re=document.getElementById(`error-block-${Q}`);re&&(ven(m.current,g.current,Q,"error block removal"),re.remove())}})}}return()=>{p.current=!0}},[t,e,f,r,b]),(0,Yr.useEffect)(()=>{let R=f,N=m.current,D=h.current,F=g.current;return(()=>{Cen(),xen()})(),()=>{p.current=!0,setTimeout(()=>{R.current&&(R.current.unload(),R.current=null),N.startsWith("temp-")&&(Oen(N,D,"component cleanup"),Ten(N,F,"component cleanup"))},0)}},[]);let _=()=>{c(!0)},w=()=>{c(!1)},x=R=>{c(!1),o&&o(R)},O=()=>{t.sources&&t.sources.length>0&&new fLe(e,t.sources).open()},E=()=>{let R=e.workspace.getMostRecentLeaf();if((!R||!(R.view instanceof w3.MarkdownView))&&(R=e.workspace.getLeaf(!1),!R||!(R.view instanceof w3.MarkdownView)))return;let D=R.view.editor.getSelection().length>0,F=Bhe(t.message);$z(F,D)},T=()=>t.content?Yr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-3"},t.content.map((R,N)=>R.type==="text"?Yr.default.createElement("div",{key:N},t.sender===Xs?Yr.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-break-words tw-text-[calc(var(--font-text-size)_-_2px)] tw-font-normal"},t.message):Yr.default.createElement("div",{ref:d,className:t.isErrorMessage?"tw-text-error":""})):R.type==="image_url"?Yr.default.createEl
`).map(b=>{if(!b.trim())return b;try{return new URL(b.trim()),b}catch{return b}});p("contextSource.webUrls",y.join(`
`))},placeholder:"Enter web URLs, one per line",className:"tw-min-h-20 tw-w-full"})),dn.default.createElement(ai,{label:"YouTube URLs"},dn.default.createElement(Cx,{value:u.contextSource?.youtubeUrls,onChange:h=>{let y=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",y.join(`
`))},placeholder:"Enter YouTube URLs, one per line",className:"tw-min-h-20 tw-w-full"})))),dn.default.createElement("div",{className:"tw-mt-4 tw-flex tw-items-center tw-justify-end tw-gap-2"},dn.default.createElement(ve,{variant:"ghost",onClick:r,disabled:o},"Cancel"),dn.default.createElement(ve,{onClick:m,disabled:o||!f()},o?"Saving...":"Save")))}var Zde=class extends zX.Modal{constructor(r,n,o){super(r);this.onSave=n;this.initialProject=o}onOpen(){let{contentEl:r}=this;this.root=(0,ptn.createRoot)(r);let n=async i=>{await this.onSave(i),this.close()},o=()=>{this.close()};this.root.render(dn.default.createElement(ppi,{initialProject:this.initialProject,onSave:n,onCancel:o}))}onClose(){this.root.unmount()}};Ro();jn();Dt();Pt();On();var htn=require("obsidian"),Ge=L(X());function mpi(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 mtn(t,e,r={}){return!t||t.length===0?[]:e.trim()?t.filter(n=>mpi(n,e,r)):t}function hpi({project:t,loadContext:e,onEdit:r,onDelete:n}){return Ge.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)},Ge.default.createElement("div",{className:"tw-flex tw-flex-1 tw-items-center tw-gap-2 tw-overflow-hidden"},Ge.default.createElement("div",{className:"tw-text-accent"},Ge.default.createElement(sh,{className:"tw-size-4"})),Ge.default.createElement("div",{className:"tw-flex tw-flex-1 tw-flex-col tw-gap-1.5 tw-overflow-hidden"},Ge.default.createElement("span",{className:"tw-w-full tw-truncate tw-text-[13px] tw-font-medium tw-text-normal"},t.name),t.description&&Ge.default.createElement("span",{className:"tw-w-full tw-truncate tw-text-[12px] tw-text-muted/80"},t.description))),Ge.default.createElement("div",{className:"tw-flex tw-flex-row tw-items-center tw-gap-1 tw-opacity-100 tw-transition-opacity tw-duration-200"},Ge.default.createElement(Kn,null,Ge.default.createElement(Wn,{asChild:!0},Ge.default.createElement(ve,{variant:"ghost2",size:"icon",onClick:o=>{o.stopPropagation(),r(t)}},Ge.default.createElement(lb,{className:"tw-size-4"}))),Ge.default.createElement(Mn,{side:"bottom"},"Edit Project")),Ge.default.createElement(Kn,null,Ge.default.createElement(Wn,{asChild:!0},Ge.default.createElement(ve,{variant:"ghost2",size:"icon",onClick:o=>{o.stopPropagation(),e(t)}},Ge.default.createElement(FK,{className:"tw-size-4"}))),Ge.default.createElement(Mn,{side:"bottom"},"Start Chat")),Ge.default.createElement(Kn,null,Ge.default.createElement(Wn,{asChild:!0},Ge.default.createElement(ve,{variant:"ghost2",size:"icon",onClick:o=>{o.stopPropagation(),new lm(app,()=>n(t),`Are you sure you want to delete project "${t.name}"?`,"Delete Project").open()}},Ge.default.createElement(cy,{className:"tw-size-4"}))),Ge.default.createElement(Mn,{side:"bottom"},"Delete Project"))))}var vvt=(0,Ge.memo)(({className:t,projects:e,defaultOpen:r=!1,app:n,onProjectAdded:o,onEditProject:i,hasMessages:a=!1,showChatUI:s,onClose:u,onProjectClose:l})=>{let[c,d]=(0,Ge.useState)(r),[f,p]=(0,Ge.useState)(!1),[m,h]=(0,Ge.useState)(null),[g,y]=(0,Ge.useState)(""),b=wU();(0,Ge.useEffect)(()=>{a&&d(!1)},[a]);let _=(0,Ge.useMemo)(()=>mtn(e,g),[e,g]),w=()=>{new Zde(n,async N=>{o(N)}).open()},x=R=>{new Zde(n,async D=>{i(R,D),m&&m.name===R.name&&h(D)},R).open()},O=R=>{let D=(e||[]).filter(F=>F.name!==R.name);m?.name===R.name&&E(!1),et("projectList",D),new htn.Notice(`Project "${R.name}" deleted successfully`)},E=(R,N)=>{if(R){if(!N){ue("Must be exist one project.");return}h(N),p(!0),d(!1)}else{h(null),p(!1),d(!0),s(!1),Vz(null);return}},T=R=>{h(R),p(!0),d(!1),s(!0),Vz(R),setTimeout(()=>{b.focusInput()},0)};return Ge.
- a positive number
- less than the value passed to \`max\` (or ${xvt} if no \`max\` prop is set)
- \`null\` or \`undefined\` if the progress is indeterminate.
Defaulting to \`null\`.`}var Ovt=Stn,Ttn=xtn;jn();var Tvt=Xde.forwardRef(({className:t,value:e,...r},n)=>Xde.createElement(Ovt,{ref:n,className:Oe("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},Xde.createElement(Ttn,{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)}%)`}})));Tvt.displayName=Ovt.displayName;On();Tu();Ro();Dt();function Pvt({plugin:t,setHiddenCard:e,onEditContext:r}){let[n]=nge(),o=n.total,i=n.success,a=n.failed,s=n.processingFiles,[u,l]=(0,Evt.useState)(!1),[c,d]=(0,Evt.useState)(!1),f=i.length+a.length,p=o.length>0?Math.round(f/o.length*100):0,m=g=>g.path,h=async g=>{if(!t?.projectManager){ue("ProjectManager not available");return}try{await t.projectManager.retryFailedItem(g)}catch(y){ue(`Error retrying failed item: ${y}`)}};return mn.createElement(S3,{className:"tw-w-full tw-border tw-border-solid tw-border-border tw-bg-transparent tw-shadow-none"},mn.createElement(C3,null,mn.createElement(Ude,{className:"tw-flex tw-items-center tw-justify-between tw-gap-2"},mn.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},mn.createElement(ic,{className:"tw-size-5"}),"Context Loading",mn.createElement(ve,{size:"sm",variant:"ghost2",className:"tw-size-6 tw-p-0 tw-text-muted",title:"Edit Context",onClick:()=>r?.()},mn.createElement(tg,{className:"tw-size-4"}),mn.createElement("span",{className:"tw-sr-only"},"Edit Context"))),mn.createElement("div",{className:"tw-flex tw-items-center tw-gap-2 tw-rounded tw-p-1"},mn.createElement(ve,{size:"sm",variant:"ghost2",className:"tw-size-6 tw-p-0 tw-text-muted",title:"Close Progress Bar",onClick:()=>e(!0)},mn.createElement(pi,{className:"tw-size-4"}))))),mn.createElement(x3,{className:"tw-space-y-6"},mn.createElement("div",{className:"tw-space-y-2"},mn.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-text-sm"},mn.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},mn.createElement("span",{className:"tw-text-muted"},"Total progress"),mn.createElement("span",{className:"tw-text-xs tw-text-muted"},"(Success:"," ",mn.createElement("span",{className:"tw-font-medium tw-text-success"},i.length),", Failed: ",mn.createElement("span",{className:"tw-font-medium tw-text-error"},a.length),")")),mn.createElement("span",{className:"tw-font-medium"},f,"/",o.length," (",p,"%)")),mn.createElement(Tvt,{value:p,className:"tw-h-2"})),s.length>0&&mn.createElement("div",{className:"tw-space-y-3"},mn.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)},mn.createElement(Zc,{className:"tw-size-4 tw-animate-spin tw-text-accent"}),mn.createElement("span",{className:"tw-text-sm tw-font-medium"},"Processing"),u?mn.createElement(Qs,{className:"tw-ml-auto tw-size-4"}):mn.createElement(tg,{className:"tw-ml-auto tw-size-4"})),u&&mn.createElement("div",{className:"tw-max-h-32 tw-space-y-2 tw-overflow-y-auto"},s.map((g,y)=>mn.createElement("div",{key:y,className:"tw-flex tw-items-center tw-gap-2 tw-rounded-md tw-p-2 tw-text-sm tw-bg-faint/10"},mn.createElement("div",{className:"tw-size-2 tw-animate-pulse tw-rounded-full tw-bg-interactive-accent"}),mn.createElement(pm,{className:"tw-flex-1",title:g},g))))),a.length>0&&mn.createElement("div",{className:"tw-space-y-3"},mn.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},mn.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)},mn.createElement(FO,{className:"tw-size-4 tw-text-error"}),mn.createElement("span",{className:"tw-text-sm tw-font-medium"},"Failed"),mn.createElement(qb,{variant:"destructive",className:"tw-text-xs"},a.length," files"),c?mn.createElement(Qs,{className:"tw-ml-auto tw-size-4"}):mn.createElement(tg,{className:"tw-ml-auto tw-size-4"}))),c&&mn.cr
`));let q0={notes:ui,urls:s_(f)?wt||[]:[],tags:Sl||[],folders:Vo||[],selectedTextContexts:q};g(""),H([]),$.setLoading(!0),$.setLoadingMessage(EO.DEFAULT);let Xt=await i.sendMessage(mv,q0,f,F,Wa.length>0?Wa:void 0);h&&r(h),s.autosaveChat&&Rt();let ct=i.getLLMMessage(Xt);ct&&await Mvt(ct,t,w,$.setCurrentAiMessage,x,{debug:s.debug,updateLoadingMessage:$.setLoadingMessage}),s.autosaveChat&&Rt()}catch(Wa){ue("Error sending message:",Wa),new vl.Notice("Failed to send message. Please try again.")}finally{$.setLoading(!1),$.setLoadingMessage(EO.DEFAULT)}},Rt=(0,br.useCallback)(async()=>{if(!Ae){ue("App instance is not available.");return}try{await i.saveChat(d)}catch(He){ue("Error saving chat as note:",Eo(He)),new vl.Notice("Failed to save chat as note. Check console for details.")}},[Ae,i,d]),Ze=(0,br.useCallback)(He=>{_.current&&(J(`stopping generation..., reason: ${He}`),_.current.abort(He),$.setLoading(!1),$.setLoadingMessage(EO.DEFAULT))},[$]);(0,br.useEffect)(()=>(Z.current=!0,()=>{Z.current=!1,_.current&&_.current.abort("component-unmount")}),[]);let Dr=(0,br.useCallback)(async He=>{if(He<=0){new vl.Notice("Cannot regenerate the first message.");return}let wt=l[He];if(!wt){new vl.Notice("Message not found.");return}$.setCurrentAiMessage(""),$.setLoading(!0);try{await i.regenerateMessage(wt.id,$.setCurrentAiMessage,w)?s.debug&&console.log("Message regenerated successfully"):new vl.Notice("Failed to regenerate message. Please try again."),s.autosaveChat&&Rt()}catch(_r){ue("Error regenerating message:",_r),new vl.Notice("Failed to regenerate message. Please try again.")}finally{$.setLoading(!1)}},[l,i,s.debug,s.autosaveChat,Rt,w,$]),Vt=(0,br.useCallback)(async(He,wt)=>{let _r=l[He];if(!(!_r||_r.message===wt))try{if(!await i.editMessage(_r.id,wt,f,F)){new vl.Notice("Failed to edit message. Please try again.");return}if(_r.sender===Xs){let Vo=He<l.length-1;if(await i.truncateAfterMessageId(_r.id),Vo){$.setLoading(!0);try{let Su=i.getLLMMessage(_r.id);Su&&await Mvt(Su,t,w,$.setCurrentAiMessage,x,{debug:s.debug,updateLoadingMessage:$.setLoadingMessage})}catch(Su){ue("Error regenerating AI response:",Su),new vl.Notice("Failed to regenerate AI response. Please try again.")}finally{$.setLoading(!1)}}}s.autosaveChat&&Rt()}catch(Sl){ue("Error editing message:",Sl),new vl.Notice("Failed to edit message. Please try again.")}},[l,i,f,F,w,t,s.debug,s.autosaveChat,Rt,$,x]);(0,br.useEffect)(()=>{e&&e(Rt)},[e,Rt]);let jt=(0,br.useCallback)(He=>{let wt=s.projectList||[];if(wt.findIndex(Su=>Su.name===He.name)>=0)throw new Error(`Project "${He.name}" already exists, please use a different name`);let Sl=[...wt,He];return et("projectList",Sl),tc()?.id===He.id?RDe().then(()=>{new vl.Notice(`${He.name} added and context loaded`)}).catch(Su=>{ue("Error loading project context:",Su),new vl.Notice(`${He.name} added but context loading failed`)}):new vl.Notice(`${He.name} added successfully`),!0},[s.projectList]),Fe=(0,br.useCallback)((He,wt)=>{let _r=s.projectList||[];if(!_r.find(Wa=>Wa.name===He.name))throw new Error(`Project "${He.name}" does not exist`);let Vo=_r.map(Wa=>Wa.name===He.name?wt:Wa);return et("projectList",Vo),tc()?.id===He.id?(Vz(wt),RDe().then(()=>{new vl.Notice(`${He.name} updated and context reloaded`)}).catch(Wa=>{ue("Error reloading project context:",Wa),new vl.Notice(`${He.name} updated but context reload failed`)})):new vl.Notice(`${He.name} updated successfully`),!0},[s.projectList]),hn=(0,br.useCallback)(He=>{uIt(He)},[]);(0,br.useEffect)(()=>{let He=()=>{a.focusInput()};return u?.addEventListener(Yw.CHAT_IS_VISIBLE,He),()=>{u?.removeEventListener(Yw.CHAT_IS_VISIBLE,He)}},[u,a]);let gt=(0,br.useCallback)(async He=>{let wt=l[He];if(!wt){new vl.Notice("Message not found.");return}try{await i.deleteMessage(wt.id)||new vl.Notice("Failed to delete message. Please try again.")}catch(_r){ue("Error deleting message:",_r),new vl.Notice("Failed to delete message. Please try again.")}},[l,i]),qe=(0,br.useCallback)(async()=>{if(K7(),Ze("new-chat"),s.enableRecentConversations)try{let He=t.chatModelManager.getChatModel();o.userMemoryMana
Original name: ${a.title}
${a.content}`}):e.push(a)}await jg.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 ${RB()}.`;r.length>0&&(await Mpi(r),i+=`
We found ${r.length} unsupported commands. They are saved in ${RB()}/unsupported. To fix them, please resolve the errors and move the note file out of the unsupported folder.`),et("inlineEditCommands",[]),new lm(app,()=>{},i,"\u{1F680} New Copilot Custom Commands","OK","").open()}async function Ivt(){let t=K_(),e=wHr.filter(n=>!t.some(o=>o.title===n.title)),r=[...t,...e];jg.getInstance().updateCommands(r)}async function $tn(){if(ce().suggestedDefaultCommands)return;K_().length===0&&(new lm(app,()=>{Ivt()},"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(),et("suggestedDefaultCommands",!0))}var Uc=L(X()),Qde=require("obsidian"),Ltn=L(wm());Ro();Tu();Pt();function Rpi({plugin:t,onRemove:e}){let[r,n]=(0,Uc.useState)(""),o=So(),[i,a]=(0,Uc.useState)(""),[s]=xL(),u=(0,Uc.useRef)(null),l=o.quickCommandModelKey??s,c=o.quickCommandIncludeNoteContext;(0,Uc.useEffect)(()=>{let g=t.app.workspace.getActiveViewOfType(Qde.MarkdownView);if(g&&g.editor){let y=g.editor.getSelection();a(y)}},[t.app]),(0,Uc.useEffect)(()=>{u.current&&u.current.focus()},[]);let d=async()=>{if(!r.trim()){new Qde.Notice("Please enter a prompt");return}let g=`
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).
`,y=r;if(c){let w=y.includes("{}"),x=/\{activenote\}/i.test(y),O=[];w||O.push("{}"),x||O.push("{activeNote}"),O.length>0&&(y+=`
${O.join(`
`)}`)}let b={title:"Quick Command",content:y,showInContextMenu:!1,showInSlashMenu:!1,order:0,modelKey:l,lastUsedMs:Date.now()};new IB(t.app,{selectedText:i,command:b,systemPrompt:g}).open(),e()},f=()=>{e()},p=g=>{g.key==="Escape"?(g.preventDefault(),f()):g.key==="Enter"&&!g.shiftKey&&(g.preventDefault(),d())},m=g=>{et("quickCommandModelKey",g)},h=g=>{et("quickCommandIncludeNoteContext",g)};return Uc.default.createElement("div",{className:"tw-rounded-lg tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-4",onKeyDown:p},Uc.default.createElement("div",{className:"tw-space-y-4"},Uc.default.createElement(Cx,{ref:u,value:r,onChange:g=>n(g.target.value),placeholder:"Ask me anything...",className:"tw-min-h-24 tw-resize-none",rows:3}),Uc.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-gap-4"},Uc.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-4"},Uc.default.createElement(IDe,{size:"sm",variant:"ghost",value:l,onChange:m}),Uc.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Uc.default.createElement(sd,{id:"includeActiveNote",checked:c,onCheckedChange:g=>h(!!g)}),Uc.default.createElement("label",{htmlFor:"includeActiveNote",className:"tw-cursor-pointer tw-text-sm tw-text-muted"},"Include note context"))),Uc.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Uc.default.createElement(ve,{variant:"secondary",onClick:f,size:"sm"},"Cancel"),Uc.default.createElement(ve,{onClick:d,size:"sm"},"Submit")))))}function Ftn({plugin:t,element:e}){let r=document.createElement("div");e.appendChild(r);let n=(0,Ltn.createRoot)(r),o=()=>{let i=t.app.workspace.getActiveViewOfType(Qde.MarkdownView);i&&i.editor&&vje(i.editor),n.unmount(),r.remove()};return n.render(Uc.default.createElement(Rpi,{plugin:t,onRemove:o})),{root:n,container:r}}zr();Pt();Dt();zr();async function ktn(t,e){await e.clearChatMemory();for(let r=0;r<t.length-1;r++){let n=t[r];if(n.sender===Xs){let o=t[r+1];o?.sender===TO&&await e.getMemory().saveContext({input:n.message},{output:o.message})}}}Tu();gd();Tu();zr();wr();var rFe=require("obsidian");zr();var tFe=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 rFe.TFile)try{let l=await n.parseFile(u,r);e=e.replace(a[0],`
<${uee}>
<name>${s}</name>
<content>
${l}
</content>
</${uee}>
`)}catch(l){console.error(`Error processing embedded PDF ${s}:`,l),e=e.replace(a[0],`
<${uee}>
<name>${s}</name>
<error>Could not process PDF</error>
</${uee}>
`)}}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,g)=>setTimeout(()=>g(new Error("Query timeout")),5e3))]),m=`
<${lee}>
<query_type>${l}</query_type>
<original_query>
${c}
</original_query>
<executed_result>
${p}
</executed_result>
</${lee}>
`;e=e.slice(0,d)+m+e.slice(f)}catch(p){console.error("Error executing Dataview query:",p);let m=`
<${lee}>
<query_type>${l}</query_type>
<original_query>
${c}
</original_query>
<error>${p instanceof Error?p.message:"Query execution failed"}</error>
</${lee}>
`;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 processContextNotes(e,r,n,o,i,a,s){let u="",l=async(d,f=aee)=>{try{if(e.has(d.path)){console.log(`Skipping note ${d.path} as it was included via custom prompt.`);return}if(console.log(`Processing note: ${d.path}, extension: ${d.extension}, chain: ${s}`),!r.supportsExtension(d.extension)){console.warn(`Unsupported file type: ${d.extension}`);return}if(!s_(s)&&d.extension!=="md"&&d.extension!=="canvas"){console.warn(`File type ${d.extension} requires Copilot Plus mode for context processing.`),new rFe.Notice(G6.NON_MARKDOWN_FILES_RESTRICTED);return}let p=await r.parseFile(d,n);d.extension==="md"&&(s_(s)&&(p=await this.processEmbeddedPDFs(p,n,r)),p=await this.processDataviewBlocks(p,d.path));let m=await n.adapter.stat(d.path),h=m?new Date(m.ctime).toISOString():"Unknown",g=m?new Date(m.mtime).toISOString():"Unknown";u+=`
<${f}>
<title>${d.basename}</title>
<path>${d.path}</path>
<ctime>${h}</ctime>
<mtime>${g}</mtime>
<content>
${p}
</content>
</${f}>`}catch(p){console.error(`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=Kz();if(!e||e.length===0)return"";let r="";for(let n of e)r+=`
<${u_}>
<title>${n.noteTitle}</title>
<path>${n.notePath}</path>
<start_line>${n.startLine.toString()}</start_line>
<end_line>${n.endLine.toString()}</end_line>
<content>
${n.content}
</content>
</${u_}>`;return r}};Dt();lot();wr();var nFe=class t{constructor(){this.contextProcessor=tFe.getInstance(),this.mention=eG.getInstance()}static getInstance(){return t.instance||(t.instance=new t),t.instance}async processMessageContext(e,r,n,o,i,a){try{J(`[ContextManager] Processing context for message ${e.id}`);let s=e.originalMessage||e.message,{processedPrompt:u,includedFiles:l}=await _mt(s,"",n,a),c=e.context?.urls||[],d=o==="copilot_plus"?await this.mention.processUrlList(c):{urlContext:"",imageUrls:[]},f=new Set(l.map(O=>O.path)),m=[...e.context?.notes||[]];i&&o!=="project"&&a&&!f.has(a.path)&&!m.some(O=>O.path===a.path)&&m.push(a);let h=await this.contextProcessor.processContextNotes(f,r,n,m,i,a,o);m.forEach(O=>f.add(O.path));let g=e.context?.tags||[],y="";if(g.length>0){let E=Fhe(n,g).filter(T=>!f.has(T.path));E.length>0&&(y=await this.contextProcessor.processContextNotes(new Set,r,n,E,!1,null,o),E.forEach(T=>f.add(T.path)))}let b=e.context?.folders||[],_="";if(b.length>0){let E=b.flatMap(T=>eee(n,T)).filter(T=>!f.has(T.path));E.length>0&&(_=await this.contextProcessor.processContextNotes(new Set,r,n,E,!1,null,o),E.forEach(T=>f.add(T.path)))}let w=this.contextProcessor.processSelectedTextContexts(),x=u+h+y+_+d.urlContext+w;return J(`[ContextManager] Successfully processed context for message ${e.id}`),x}catch(s){return J(`[ContextManager] Error processing context for message ${e.id}:`,s),e.originalMessage||e.message}}async reprocessMessageContext(e,r,n,o,i,a,s){let u=r.getMessage(e);if(!u||u.sender!=="user"||!u.id)return;J(`[ContextManager] Reprocessing context for message ${e}`);let l=await this.processMessageContext(u,n,o,i,a,s);r.updateProcessedText(u.id,l),J(`[ContextManager] Completed context reprocessing for message ${e}`)}createMessageContext(e,r,n=Kz()){return{notes:e,urls:r,selectedTextContexts:n}}async extractContextNotes(e,r,n=[]){return[...await xO(e,r),...n].filter((s,u,l)=>l.findIndex(c=>c.path===s.path)===u)}needsContextReprocessing(e){return e.needsContextReprocessing===!0}getSelectedTextContexts(){return Kz()}};wr();Dt();var HX=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||Zh(new Date),p={id:d,displayText:c.message,processedText:c.originalMessage||c.message,sender:c.sender,timestamp:f,context:c.context,isVisible:c.isVisible!==!1,isErrorMessage:c.isErrorMessage,sources:c.sources,content:c.content,responseMetadata:c.responseMetadata};return this.messages.push(p),J(`[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=Zh(new Date),l={id:s,displayText:a,processedText:r,sender:n,timestamp:u,context:o,isVisible:!0,isErrorMessage:!1,content:i};return this.messages.push(l),J(`[MessageRepository] Added message with ID: ${s}`),s}editMessage(e,r){let n=this.messages.find(o=>o.id===e);return n?n.displayText===r?(J(`[MessageRepository] No changes needed for message: ${e}`),!0):(n.displayText=r,n.sender==="user"||n.sender==="USER"?J(`[MessageRepository] Edited user message ${e}, needs context reprocessing`):(n.processedText=r,J(`[MessageRepository] Edited AI message ${e}`)),!0):(J(`[MessageRepository] Message not found for edit: ${e}`),!1)}updateProcessedText(e,r){let n=this.messages.find(o=>o.id===e);return n?(n.processedText=r,J(`[MessageRepository] Updated processed text for message ${e}`),!0):(J(`[MessageRepository] Message not found for processed text update: ${e}`),!1)}deleteMessage(e){let r=this.messages.findIndex(n=>n.id===e);return r===-1?(J(`[MessageRepository] Message not found for deletion: ${e}`),!1):(this.messages.splice(r,1),J(`[MessageRepository] Deleted message ${e}`),!0)}clear(){this.messages=[],J("[MessageRepository] Cleared all messages")}truncateAfter(e){this.messages=this.messages.slice(0,e+1),J(`[MessageRepository] Truncated messages after index ${e}`)}truncateAfterMessageId(e){le
[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"?Xs:TO,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 g=h[1];f=this.parseContextString(g),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:[]},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=>({basename:s.trim(),path:s.trim()})))}else if(i.startsWith("URLs: ")){let a=i.substring(6);a&&(r.urls=a.split(", ").map(s=>s.trim()))}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)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 Hhe(u).trim().replace(/^["']|["']$/g,"").replace(/[\\/:*?"<>|]/g,"").slice(0,50)||void 0}catch(r){ue("[ChatPersistenceManager] Error generating AI topic:",r);return}}generateFileName(e,r,n){let o=ce(),a=Zh(new Date(r)).fileName,s;if(n)s=n;else{let x=e.find(O=>O.sender===Xs);s=x&&x.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=200,c=tc(),d=c?`${c.id}__`:"",f=nee(".md"),p=nee(d),m=u.replace("{$topic}","").replace("{$date}",a.split("_")[0]).replace("{$time}",a.split("_")[1]),h=nee(m),g=Math.max(20,l-f-p-h),y=s.replace(/\s+/g,"_"),b=Q2e(y,g);u=u.replace("{$topic}",b).replace("{$date}",a.split("_")[0]).replace("{$time}",a.split("_")[1]);let _=u.replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/[{}[\]]/g,"_").replace(/[\\/:*?"<>|\x00-\x1F]/g,"_"),w=`${d}${_}.md`;if(nee(w)>l){let x=l-f-p,O=Q2e(_,x);return`${o.defaultSaveFolder}/${d}${O}.md`}return`${o.defaultSaveFolder}/${w}`}generateNoteContent(e,r,n,o){let i=ce(),a=tc();return`---
epoch: ${r}
modelKey: ${n}
${o?`topic: "${o}"`:""}
${a?`projectId: ${a.id}`:""}
${a?`projectName: ${a.name}`:""}
tags:
- ${i.defaultConversationTag}
---
${e}`}generateTopicAsyncIfNeeded(e,r,n){!ce().generateAIChatTitleOnSave||!r||n||(async()=>{try{let i=await this.generateAITopic(e);if(!i)return;await this.applyTopicToFrontmatter(r,i)}catch(i){ue("[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)}),J(`[ChatPersistenceManager] Applied AI topic to chat file: ${e.path}`)}catch(n){ue("[ChatPersistenceManager] Error applying AI topic to file:",n)}}isFileAlreadyExistsError(e){return e?(e instanceof Error?e.message:String(e)).toLowerCase().includes("already exists"):!1}};zr();var oFe=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=nFe.getInstance(),this.projectMessageRepos.set(this.defaultProjectKey,e),this.persistenceManager=new efe(o.app,e,r)}getCurrentMessageRepo(){let e=this.plugin.projectManager.getCurrentProjectId(),r=e??this.defaultProjectKey;if(this.lastKnownProjectId!==e&&(J(`[ChatManager] Project changed from ${this.lastKnownProjectId} to ${e}`),this.lastKnownProjectId=e),!this.projectMessageRepos.has(r)){J(`[ChatManager] Creating new message repository for project: ${r}`);let o=new HX;this.projectMessageRepos.set(r,o)}let n=this.projectMessageRepos.get(r);return this.persistenceManager=new efe(this.plugin.app,n,this.chainManager),n}setOnMessageCreatedCallback(e){this.onMessageCreatedCallback=e}async sendMessage(e,r,n,o=!1,i){try{J(`[ChatManager] Sending message: "${e}"`);let a=this.plugin.app.workspace.getActiveFile(),s={...r};if(o&&a){let f=r.notes||[],p=f.some(m=>m.path===a.path);s.notes=p?f:[...f,a]}let u=this.getCurrentMessageRepo(),l=u.addMessage(e,e,Xs,s,i);this.onMessageCreatedCallback&&this.onMessageCreatedCallback(l);let c=u.getMessage(l);if(!c)throw new Error(`Failed to retrieve message ${l}`);let d=await this.contextManager.processMessageContext(c,this.fileParserManager,this.plugin.app.vault,n,o,a);return u.updateProcessedText(l,d),J(`[ChatManager] Successfully sent message ${l}`),l}catch(a){throw J("[ChatManager] Error sending message:",a),a}}async editMessage(e,r,n,o=!1){try{J(`[ChatManager] Editing message ${e}: "${r}"`);let i=this.getCurrentMessageRepo();if(!i.editMessage(e,r))return!1;let s=this.plugin.app.workspace.getActiveFile();return await this.contextManager.reprocessMessageContext(e,i,this.fileParserManager,this.plugin.app.vault,n,o,s),await this.updateChainMemory(),J(`[ChatManager] Successfully edited message ${e}`),!0}catch(i){return J(`[ChatManager] Error editing message ${e}:`,i),!1}}async regenerateMessage(e,r,n,o){try{J(`[ChatManager] Regenerating message ${e}`);let i=this.getCurrentMessageRepo();if(!i.getMessage(e))return J(`[ChatManager] Message not found: ${e}`),!1;let s=i.getDisplayMessages(),u=s.findIndex(f=>f.id===e);if(u<=0)return J("[ChatManager] Cannot regenerate first message or no user message found"),!1;let l=s[u-1];if(l.sender!==Xs)return J("[ChatManager] Previous message is not from user"),!1;if(i.truncateAfter(u-1),o&&o(),await this.updateChainMemory(),!l.id)return J("[ChatManager] User message has no ID for regeneration"),!1;let c=i.getLLMMessage(l.id);if(!c)return J("[ChatManager] LLM message not found for regeneration"),!1;let d=new AbortController;return await this.chainManager.runChain(c,d,r,n,{debug:ce().debug}),J(`[ChatManager] Successfully regenerated message ${e}`),!0}catch(i){return J(`[ChatManager] Error regenerating message ${e}:`,i),!1}}async deleteMessage(e){try{return J(`[ChatManager] Deleting message ${e}`),this.getCurrentMessageRepo().deleteMessage(e)?(await this.updateChainMemory(),J(`[ChatManager] Successfully deleted message ${e}`),!0):!1}catch(r){return J(`[ChatManager] Error deleting message ${e}:`,r),!1}}addMessage(e){return this.getCurrentMessageRepo().addMessage(e)}clearMessages(){this.getCurrentMessageRepo().clear(),th
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.
`},Lpi={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 Fpi(t){let{announcements:e=Lpi,container:r,hiddenTextDescribedById:n,screenReaderInstructions:o=$pi}=t,{announce:i,announcement:a}=Xtn(),s=A3("DndLiveRegion"),[u,l]=(0,ze.useState)(!1);if((0,ze.useEffect)(()=>{l(!0)},[]),jpi((0,ze.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=ze.default.createElement(ze.default.Fragment,null,ze.default.createElement(Gtn,{id:n,value:o.draggable}),ze.default.createElement(Ztn,{id:s,announcement:a}));return r?(0,D3.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 fFe(){}function GX(t,e){return(0,ze.useMemo)(()=>({sensor:t,options:e??{}}),[t,e])}function mFe(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return(0,ze.useMemo)(()=>[...e].filter(n=>n!=null),[...e])}var Qx=Object.freeze({x:0,y:0});function drn(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}function frn(t,e){let{data:{value:r}}=t,{data:{value:n}}=e;return r-n}function kpi(t,e){let{data:{value:r}}=t,{data:{value:n}}=e;return n-r}function Ytn(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 zvt(t,e){if(!t||t.length===0)return null;let[r]=t;return e?r[e]:r}function Qtn(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 ZX=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=Qtn(e,e.left,e.top),i=[];for(let a of n){let{id:s}=a,u=r.get(s);if(u){let l=drn(Qtn(u),o);i.push({id:s,data:{droppableContainer:a,value:l}})}}return i.sort(frn)},prn=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=Ytn(e),i=[];for(let a of n){let{id:s}=a,u=r.get(s);if(u){let l=Ytn(u),c=o.reduce((f,p,m)=>f+drn(l[m],p),0),d=Number((c/4).toFixed(4));i.push({id:s,data:{droppableContainer:a,value:d}})}}return i.sort(frn)};function qpi(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 Bpi=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=qpi(s,e);u>0&&o.push({id:a,data:{droppableContainer:i,value:u}})}}return o.sort(kpi)};function Upi(t,e,r){return{...t,scaleX:e&&r?e.width/r.width:1,scaleY:e&&r?e.height/r.height:1}}function mrn(t,e){return t&&e?{x:t.left-e.left,y:t.top-e.top}:Qx}function zpi(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 Hpi=zpi(1);function Vpi(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 Qu.useEffect(()=>{t&&(document.getElementById(t)||console.error(r))},[r,t]),null},Ehi="DialogDescriptionWarning",Phi=({contentRef:t,descriptionId:e})=>{let n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${pnn(Ehi).contentName}}.`;return Qu.useEffect(()=>{let o=t.current?.getAttribute("aria-describedby");e&&o&&(document.getElementById(e)||console.warn(n))},[n,t,e]),null},mnn=Qrn,hnn=tnn,gnn=nnn,nwt=onn,owt=inn,iwt=snn,awt=lnn,ynn=dnn;On();jn();var OFe=mnn,bnn=hnn,Rhi=gnn;var _nn=Ug.forwardRef(({className:t,...e},r)=>Ug.createElement(nwt,{ref:r,className:Oe("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}));_nn.displayName=nwt.displayName;var mfe=Ug.forwardRef(({className:t,children:e,container:r,...n},o)=>Ug.createElement(Rhi,{container:r},Ug.createElement(_nn,null),Ug.createElement(owt,{ref:o,className:Oe("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(ynn,{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(pi,{className:"tw-size-4"}),Ug.createElement("span",{className:"tw-sr-only"},"Close")))));mfe.displayName=owt.displayName;var hfe=({className:t,...e})=>Ug.createElement("div",{className:Oe("tw-flex tw-flex-col tw-space-y-0.5 tw-text-center sm:tw-text-left",t),...e});hfe.displayName="DialogHeader";var Ahi=({className:t,...e})=>Ug.createElement("div",{className:Oe("tw-flex tw-flex-col-reverse sm:tw-flex-row sm:tw-justify-end sm:tw-space-x-2",t),...e});Ahi.displayName="DialogFooter";var gfe=Ug.forwardRef(({className:t,...e},r)=>Ug.createElement(iwt,{ref:r,className:Oe("tw-mt-0 tw-text-lg tw-font-semibold tw-leading-none tw-tracking-tight",t),...e}));gfe.displayName=iwt.displayName;var yfe=Ug.forwardRef(({className:t,...e},r)=>Ug.createElement(awt,{ref:r,className:Oe("tw-text-sm tw-text-muted",t),...e}));yfe.displayName=awt.displayName;wr();function on(t){let{title:e,description:r,className:n,disabled:o}=t,{modalContainer:i}=VX(),a="onChange"in t?t.onChange:void 0,s=(0,wl.useMemo)(()=>{if(a)return Uhe(l=>{a(l)},1e3)},[a]),u=()=>{switch(t.type){case"text":case"number":return wl.default.createElement(yi,{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 wl.default.createElement(HI,{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 wl.default.createElement(Cx,{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 wl.default.createElement(CZ,{checked:t.checked,onCheckedChange:t.onCheckedChange,disabled:o});case"select":return wl.default.createElement("div",{className:"tw-group tw-relative tw-w-full sm:tw-w-[200px]"},wl.default.createElement("select",{value:t.value?.toString(),onChange:l=>t.onChange?.(l.target.value),disabled:o,className:Oe("tw-w-full tw-appearance-none","tw-flex tw-h-9 tw-rounded-md tw-border tw-border-s
detail: `+H)}return U}finally{clearTimeout(B)}},T;try{T=await E(!1)}catch(D){console.log("First fetch attempt failed, trying with safeFetch...");try{T=await E(!0)}catch(F){let B=`
without CORS Error: `+Eo(D)+`
with CORS Error: `+Eo(F);throw new Error(B)}}let R=await T.json(),N=Onn(_,R);i(D=>({...D,[_]:N})),s(null)}catch(x){ue(`Error fetching models for ${_}:`,x),l(_),s(null),new GI.Notice(`Failed to load models for ${ib(_)}: ${Eo(x)}`,5e3)}},b=async()=>{if(!c){new GI.Notice("Please select a model first");return}p(!0);let _=!1,w="";try{let x=m(c.provider),O={name:c.name,provider:c.provider,apiKey:x,enabled:!0};try{await Rg.instance.getCurrentChainManager().chatModelManager.ping(O)}catch(T){_=!0,w=Eo(T),ue("Model verification failed:",T)}if(e.activeModels.find(T=>T.name===c.name&&T.provider===c.provider))_?new GI.Notice(`Model ${c.name} already exists in your models list (verification failed: ${w})`,1e4):new GI.Notice(`Model ${c.name} verified successfully! It already exists in your models list.`);else{let T=[...e.activeModels,{...O,apiKey:void 0}];et("activeModels",T),_?new GI.Notice(`Model ${c.name} added to your models list (verification failed: ${w})`,1e4):new GI.Notice(`Model ${c.name} verified successfully and added to your models list!`)}}catch(x){ue("Error adding model:",x),new GI.Notice(`Failed to add model: ${Eo(x)}`,1e4)}finally{p(!1)}};return An.default.createElement("div",{className:"tw-max-h-[600px] tw-overflow-y-auto tw-p-4 sm:tw-max-w-[500px]"},An.default.createElement("div",{className:"tw-mb-4"},An.default.createElement("h2",{className:"tw-text-xl tw-font-bold"},"AI Provider Settings"),An.default.createElement("p",{className:"tw-text-sm tw-text-muted"},"Configure your AI providers by adding their API keys.")),An.default.createElement("div",{className:"tw-space-y-6 tw-py-4"},An.default.createElement("div",{className:"tw-space-y-4"},h.map(_=>An.default.createElement(An.default.Fragment,{key:_.provider},An.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},An.default.createElement("div",{className:"tw-flex tw-items-end tw-gap-2 tw-font-medium"},An.default.createElement("div",{className:"tw-truncate"},ib(_.provider))),An.default.createElement("div",{className:"tw-flex tw-flex-row tw-items-center tw-gap-2"},An.default.createElement("div",{className:"tw-flex-1"},An.default.createElement(HI,{className:"tw-max-w-full",value:_.apiKey,onChange:w=>g(_.provider,w)})),An.default.createElement("div",{className:""},An.default.createElement(ve,{onClick:()=>{let w=r===_.provider?null:_.provider;n(w),w&&_.apiKey&&o[_.provider]===void 0&&a!==_.provider&&u!==_.provider&&y(_.provider,_.apiKey)},disabled:!_.apiKey,variant:"secondary",className:"tw-flex tw-w-full tw-items-center tw-justify-center tw-gap-2 tw-whitespace-nowrap tw-px-4 tw-py-2"},"Add Model",r===_.provider?An.default.createElement(sC,{className:"tw-ml-1 tw-size-4"}):An.default.createElement(Qs,{className:"tw-ml-1 tw-size-4"})))),An.default.createElement("div",null,RN(_.provider).keyManagementURL&&An.default.createElement("a",{href:RN(_.provider).keyManagementURL,target:"_blank",rel:"noopener noreferrer",className:"tw-text-[10px] tw-text-accent hover:tw-text-accent-hover sm:tw-text-xs"},"Get ",ib(_.provider)," Key"))),An.default.createElement(Zx,{open:r===_.provider,className:"tw-mt-2"},An.default.createElement(Xx,{className:"tw-rounded-md tw-p-3"},An.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},An.default.createElement(ai,{label:"Model",description:"Add the currently selected model to model List. After adding, please check the Model Tab."},An.default.createElement("div",null,An.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},An.default.createElement("div",{className:"tw-flex-1"},An.default.createElement(ZLe,{options:o[_.provider]?.sort((w,x)=>w.name.localeCompare(x.name)).map(w=>({label:w.name,value:w.id}))||[],onChange:w=>{let x=w.target.value,O=o[_.provider]?.find(E=>E.id===x);O&&d({id:O.id,name:O.name,provider:_.provider})},onClick:()=>{_.apiKey&&o[_.provider]===void 0&&a!==_.provider&&u!==_.provider&&y(_.provider,_.apiKey)},value:c?.provider===_.provider?c.id:"",placeholder:"Select Model",disabled:!_.apiKey||a===_.provider||u===_.provider&&o[_.provider]!==null})),An.default.createElement("div",
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")}};Ro();zr();Pt();var Lnn=require("obsidian"),Qr=L(X()),Fnn=()=>{let t=So(),e=async r=>{if(r!==t.embeddingModelKey){if(t.enableSemanticSearchV3){new DFe(app,async()=>{et("embeddingModelKey",r),await(await Promise.resolve().then(()=>(Dm(),vg))).default.getInstance().indexVaultToVectorStore(!1)}).open();return}et("embeddingModelKey",r),new Lnn.Notice("Embedding model saved. Enable Semantic Search to build the index.")}};return Qr.default.createElement("div",{className:"tw-space-y-4"},Qr.default.createElement("section",null,Qr.default.createElement("div",{className:"tw-space-y-4"},Qr.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=>et("enableInlineCitations",r)}),Qr.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 $Fe(app,async()=>{et("enableSemanticSearchV3",r),r&&await(await Promise.resolve().then(()=>(Dm(),vg))).default.getInstance().indexVaultToVectorStore(!1)},r).open()}}),Qr.default.createElement(on,{type:"select",title:"Embedding Model",description:Qr.default.createElement("div",{className:"tw-space-y-2"},Qr.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},Qr.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."),Qr.default.createElement(Ci,{content:Qr.default.createElement("div",{className:"tw-flex tw-max-w-96 tw-flex-col tw-gap-2"},Qr.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:"),Qr.default.createElement("ul",{className:"tw-pl-4 tw-text-sm tw-text-muted"},Qr.default.createElement("li",null,"Require rebuilding your vault's vector index"),Qr.default.createElement("li",null,"Affect semantic search quality"),Qr.default.createElement("li",null,"Impact Question Answering feature performance")))}))),value:t.embeddingModelKey,onChange:e,options:t.activeEmbeddingModels.map(r=>({label:oZ(r),value:Qn(r)})),placeholder:"Model"}),Qr.default.createElement(on,{type:"select",title:"Auto-Index Strategy",description:Qr.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},Qr.default.createElement("span",{className:"tw-leading-none"},"Decide when you want the vault to be indexed."),Qr.default.createElement(Ci,{content:Qr.default.createElement("div",{className:"tw-space-y-2 tw-py-2"},Qr.default.createElement("div",{className:"tw-space-y-1"},Qr.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Choose when to index your vault:"),Qr.default.createElement("ul",{className:"tw-list-disc tw-space-y-1 tw-pl-2 tw-text-sm"},Qr.default.createElement("li",null,Qr.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Qr.default.createElement("strong",{className:"tw-inline-block tw-whitespace-nowrap"},"NEVER:"),Qr.default.createElement("span",null,"Manual indexing via command or refresh only"))),Qr.default.createElement("li",null,Qr.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Qr.default.createElement("strong",{className:"tw-inline-block tw-whitespace-nowrap"},"ON STARTUP:"),Qr.default.createElement("span",null,"Index updates when plugin loads or reloads"))),Qr.default.createElement("li",null,Qr.default.
/*! 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-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/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/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 */