Files
my-vault/.obsidian/plugins/copilot/main.js
T

3063 lines
5.0 MiB
JavaScript
Raw Normal View History

2026-01-05 13:03:55 +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 Win=Object.create;var sY=Object.defineProperty;var Gin=Object.getOwnPropertyDescriptor;var Zin=Object.getOwnPropertyNames;var Xin=Object.getPrototypeOf,Yin=Object.prototype.hasOwnProperty;var nwt=t=>{throw TypeError(t)};var Qin=(t,e,r)=>e in t?sY(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),Jn=(t,e)=>{for(var r in e)sY(t,r,{get:e[r],enumerable:!0})},owt=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Zin(e))!Yin.call(t,o)&&o!==r&&sY(t,o,{get:()=>e[o],enumerable:!(n=Gin(e,o))||n.enumerable});return t};var L=(t,e,r)=>(r=t!=null?Win(Xin(t)):{},owt(e||!t||!t.__esModule?sY(r,"default",{value:t,enumerable:!0}):r,t)),Pfe=t=>owt(sY({},"__esModule",{value:!0}),t);var M=(t,e,r)=>Qin(t,typeof e!="symbol"?e+"":e,r),ean=(t,e,r)=>e.has(t)||nwt("Cannot "+r);var uY=(t,e,r)=>e.has(t)?nwt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r);var iwt=(t,e,r)=>(ean(t,e,"access private method"),r);function jFe(){if(!Mfe&&(Mfe=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Mfe))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Mfe(tan)}var Mfe,tan,awt=v(()=>{tan=new Uint8Array(16)});function swt(t,e=0){return Kh[t[e+0]]+Kh[t[e+1]]+Kh[t[e+2]]+Kh[t[e+3]]+"-"+Kh[t[e+4]]+Kh[t[e+5]]+"-"+Kh[t[e+6]]+Kh[t[e+7]]+"-"+Kh[t[e+8]]+Kh[t[e+9]]+"-"+Kh[t[e+10]]+Kh[t[e+11]]+Kh[t[e+12]]+Kh[t[e+13]]+Kh[t[e+14]]+Kh[t[e+15]]}var Kh,uwt=v(()=>{Kh=[];for(let t=0;t<256;++t)Kh.push((t+256).toString(16).slice(1))});var ran,DFe,lwt=v(()=>{ran=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),DFe={randomUUID:ran}});function nan(t,e,r){if(DFe.randomUUID&&!e&&!t)return DFe.randomUUID();t=t||{};let n=t.random||(t.rng||jFe)();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 swt(n)}var gv,cwt=v(()=>{lwt();awt();uwt();gv=nan});var kU=v(()=>{cwt()});var oan,Tt,Do=v(()=>{oan=Object.defineProperty,Tt=(t,e)=>{for(var r in e)oan(t,r,{get:e[r],enumerable:!0})}});function lY(t,e=qU){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 qU(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 cY=v(()=>{});function L$(t,e){return t.lc_error_code=e,t.message=`${t.message}
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
`,t}var dY=v(()=>{});var fwt=S((rmi,dwt)=>{"use strict";dwt.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 _wt=S((nmi,$Fe)=>{"use strict";var ian=/[\p{Lu}]/u,aan=/[\p{Ll}]/u,pwt=/^[\p{Lu}](?![\p{Lu}])/gu,gwt=/([\p{Alpha}\p{N}_]|$)/u,ywt=/[_.\- ]+/,san=new RegExp("^"+ywt.source),mwt=new RegExp(ywt.source+gwt.source,"gu"),hwt=new RegExp("\\d+"+gwt.source,"gu"),uan=(t,e,r)=>{let n=!1,o=!1,i=!1;for(let a=0;a<t.length;a++){let s=t[a];n&&ian.test(s)?(t=t.slice(0,a)+"-"+t.slice(a),n=!1,i=o,o=!0,a++):o&&i&&aan.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},lan=(t,e)=>(pwt.lastIndex=0,t.replace(pwt,r=>e(r))),can=(t,e)=>(mwt.lastIndex=0,hwt.lastIndex=0,t.replace(mwt,(r,n)=>e(n)).replace(hwt,r=>e(r))),bwt=(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=uan(t,r,n)),t=t.replace(san,""),e.preserveConsecutiveUppercase?t=lan(t,r):t=r(t),e.pascalCase&&(t=n(t.charAt(0))+t.slice(1)),can(t,n))};$Fe.exports=bwt;$Fe.exports.default=bwt});function wwt(t,e){return e?.[t]||(0,vwt.default)(t)}function Swt(t,e,r){let n={};for(let o in t)Object.hasOwn(t,o)&&(n[e(o,r)]=t[o]);return n}var vwt,dan,Cwt=v(()=>{vwt=L(fwt(),1),dan=L(_wt(),1)});function xwt(t){return Array.isArray(t)?[...t]:{...t}}function pan(t,e){let r=xwt(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]=xwt(s[u]),s=s[u]}s[i]!==void 0&&(s[i]={lc:1,type:"secret",id:[o]})}return r}function Rfe(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 fan,Wh,F$=v(()=>{Do();Cwt();fan={};Tt(fan,{Serializable:()=>Wh,get_lc_unique_name:()=>Rfe});Wh=class Owt{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,Rfe(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 Owt||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:Swt(Object.keys(r).length?pan(n,r):n,wwt,e)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}}});function k$(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="tool_call")}function Twt(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 G3,Afe=v(()=>{G3=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 UU(t,e);if(typeof t=="object"&&typeof e=="object")return _l(t,e);if(t===e)return t;throw new Error(`Can not merge objects of different types.
Left ${t}
Right ${e}`)}function kfe(t){return typeof t.role=="string"}function eh(t){return typeof t?._getType=="function"}function Y3(t){return eh(t)&&typeof t.concat=="function"}var UFe,kwt,Uc,Wb,Gg=v(()=>{F$();mY();FFe();kFe();qFe();BFe();UFe=Symbol.for("langchain.message");Uc=class extends Wh{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,kwt,!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[jwt,Dfe,Iwt].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&&UFe in e&&e[UFe]===!0&&$fe(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[(kwt=UFe,Symbol.toStringTag)](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;let r=wan(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${r}`}};Wb=class extends Uc{static isInstance(t){return super.isInstance(t)&&"concat"in t&&typeof t.concat=="function"}}});function hY(t){return t!=null&&typeof t=="object"&&"lc_direct_tool_output"in t&&t.lc_direct_tool_output===!0}function gY(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 yY(t){return typeof t=="object"&&t!==null&&"getType"in t&&typeof t.getType=="function"&&t.getType()==="tool"}function zFe(t){return t._getType()==="tool"}var San,Gb,Iw,Q3=v(()=>{Do();Gg();San={};Tt(San,{ToolMessage:()=>Gb,ToolMessageChunk:()=>Iw,defaultToolCallParser:()=>gY,isDirectToolOutput:()=>hY,isToolMessage:()=>yY,isToolMessageChunk:()=>zFe});Gb=class extends Uc{constructor(e,r,n){let o=typeof e=="string"||Array.isArray(e)?{content:e,name:n,tool_call_id:r}:e;super(o);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}}},Iw=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:_l(this.additional_kwargs,e.additional_kwargs),response_metadata:_l(this.response_metadata,e.response_metadata),artifact:Ffe(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]=gY(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=VFe(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"}};Nr=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=qU(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=VFe(this.response_metadata.model_provider);if(r)return r.translateContent(this)}le
Received: ${JSON.stringify(t,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Nw(t){if(typeof t=="string")return new au(t);if(eh(t))return t;if(Array.isArray(t)){let[e,r]=t;return KFe({type:e,content:r})}else if(kfe(t)){let{role:e,...r}=t;return KFe({...r,type:e})}else return KFe(t)}function Xu(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 Ran(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 wY(t){let e=Ran(t);switch(e.type){case"human":return new au(e.data);case"ai":return new li(e.data);case"system":return new th(e.data);case"function":if(e.data.name===void 0)throw new Error("Name must be defined for function messages");return new zU(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 ud(e.data);default:throw new Error(`Got unexpected type: ${e.type}`)}}function uSt(t){return t.map(wY)}function lSt(t){return t.map(e=>e.toDict())}function VU(t){let e=t._getType();if(e==="human")return new vv({...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 Nr({...r})}else{if(e==="system")return new Ky({...t});if(e==="function")return new _v({...t});if(ud.isInstance(t))return new bv({...t});throw new Error("Unknown message type.")}}var sSt,iO=v(()=>{Gg();Q3();z0();_Y();Ufe();U$();vY();dY();Afe();zfe();sSt=t=>t()});function ZFe(){return WFe===void 0&&(WFe={library:"langchain-js",runtime:GFe()}),WFe}function dn(t){try{return typeof process<"u"?process.env?.[t]:Hfe()?Deno?.env.get(t):void 0}catch{return}}var Aan,cSt,dSt,fSt,Hfe,pSt,GFe,WFe,Yu=v(()=>{Do();Aan={};Tt(Aan,{getEnv:()=>GFe,getEnvironmentVariable:()=>dn,getRuntimeEnvironment:()=>ZFe,isBrowser:()=>cSt,isDeno:()=>Hfe,isJsDom:()=>fSt,isNode:()=>pSt,isWebWorker:()=>dSt});cSt=()=>typeof window<"u"&&typeof window.document<"u",dSt=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",fSt=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),Hfe=()=>typeof Deno<"u",pSt=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Hfe(),GFe=()=>{let t;return cSt()?t="browser":pSt()?t="node":dSt()?t="webworker":fSt()?t="jsdom":Hfe()?t="deno":t="other",t}});var mSt,hSt=v(()=>{mSt=/^(?:[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 Ian(t){return typeof t=="string"&&mSt.test(t)}var e6,gSt=v(()=>{hSt();e6=Ian});function ySt(t,e=0){return(Gh[t[e+0]]+Gh[t[e+1]]+Gh[t[e+2]]+Gh[t[e+3]]+"-"+Gh[t[e+4]]+Gh[t[e+5]]+"-"+Gh[t[e+6]]+Gh[t[e+7]]+"-"+Gh[t[e+8]]+Gh[t[e+9]]+"-"+Gh[t[e+10]]+Gh[t[e+11]]+Gh[t[e+12]]+Gh[t[e+13]]+Gh[t[e+14]]+Gh[t[e+15]]).toLowerCase()}var Gh,Vfe,bSt=v(()=>{Gh=[];for(Vfe=0;Vfe<256;++Vfe)Gh.push((Vfe+256).toString(16).slice(1))});function XFe(){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(Nan)}var Jfe,Nan,_St=v(()=>{Nan=new Uint8Array(16)});var jan,YFe,vSt=v(()=>{jan=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),YFe={randomUUID:jan}});function Dan(t,e,r){if(YFe.randomUUID&&!e&&!t)return YFe.randomUUID();t=t||{};var n=t.random||(t.rng||XFe)();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 ySt(n)}var Zb,wSt=v(()=>{vSt();_St();bSt();Zb=Dan});var SY=v(()=>{wSt();gSt()});function CY(t){return"lc_prefer_streaming"in t&&t.lc_prefer_streaming}var Lan,Fan,JU,QFe,xY=v(()=>{Do();F$();Yu();SY();Lan={};Tt(Lan,{BaseCallbackHandler:()=>JU,callbackHandlerPrefersStreaming:()=>CY,isBaseCallbackHandler:()=>QFe});Fan=class{};JU=class extends Fan{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",dn("LANGCHAIN_CALLBA
Context: ${e}`:""}`),xpe("[Unserializable]");ld("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
Context: ${e}`:""}`),typeof o>"u"&&(o=Scn()),aqe(t,"",0,[],void 0,0,o);let a;try{r6.length===0?a=JSON.stringify(t,r,n):a=JSON.stringify(t,xcn(r),n)}catch{return xpe("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Ope.length!==0;){let s=Ope.pop();s.length===4?Object.defineProperty(s[0],s[1],s[3]):s[0][s[1]]=s[2]}}return xpe(a)}}function iqe(t,e,r,n){var o=Object.getOwnPropertyDescriptor(n,r);o.get!==void 0?o.configurable?(Object.defineProperty(n,r,{value:t}),Ope.push([n,r,e,o])):r6.push([e,r,t]):(n[r]=t,Ope.push([n,r,e]))}function aqe(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){iqe(vcn,t,e,o);return}if(typeof a.depthLimit<"u"&&i>a.depthLimit){iqe(Rxt,t,e,o);return}if(typeof a.edgesLimit<"u"&&r+1>a.edgesLimit){iqe(Rxt,t,e,o);return}if(n.push(t),Array.isArray(t))for(s=0;s<t.length;s++)aqe(t[s],s,s,n,t,i,a);else{t=Axt(t);var u=Object.keys(t);for(s=0;s<u.length;s++){var l=u[s];aqe(t[l],l,s,n,t,i,a)}}n.pop()}}function xcn(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(r6.length>0)for(var n=0;n<r6.length;n++){var o=r6[n];if(o[1]===e&&o[0]===r){r=o[2],r6.splice(n,1);break}}return t.call(this,e,r)}}var Rxt,vcn,Ope,r6,wcn,Ixt=v(()=>{oN();Rxt="[...]",vcn={result:"[Circular]"},Ope=[],r6=[],wcn=new TextEncoder});function Nxt(t,e){let r=Qfe(),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 Ecn(t){let e=[];for await(let r of t)e.push(r);return e}function Tpe(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}function jxt(t){return typeof t=="number"?Number(t.toFixed(4)):t}function $xt(t){return"dataset_id"in t||"dataset_name"in t}var Ocn,Tcn,Pcn,sqe,Mcn,Rcn,Acn,Dxt,KU,pke=v(()=>{ike();b0t();Tke();j0t();D0t();oN();Yfe();$0t();Lke();Ext();oqe();dke();Ixt();Ocn=t=>{let e=t?.toString()??ld("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},Tcn=t=>{let r=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"};Pcn=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};sqe=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())]}},Mcn=24*1024*1024,Rcn=1e4,Acn=100,Dxt="https://api.smith.langchain.com",KU=class t{get _fetch(){return this.fetchImplementation||p0t(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=tpe(),r=g0t();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=Nxt(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 $r(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 $r(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=f0t(),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 $r(p,"Failed to send multipart request",!0),p});try{let l,c=!1;!i&&!this.multipartStreamingDisabled&&yke()!=="bun"?(c=!0,l=await u(s)):l=await u(a),(!this.multipartStreamingDisabled||c)&&l.status===422&&(n?.apiUrl??this.apiUrl)!==Dxt&&(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){Po(e),r.inputs&&(r.inputs=await this.processInputs(r.inputs)),r.outputs&&(r.outputs=await this.processOutputs(r.outputs));let o={...r,id:e};if(!this._filterForSampling([o],!0).length)return;if(this.autoBatchTracing&&o.trace_id!==void 0&&o.dotted_order!==void 0){let s=this._cloneCurrentOTELContext();if(r.end_time!==void 0&&o.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:o,otelContext:s,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:o,otelContext:s,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}let i={...this.headers,"Content-Type":"application/json"};n?.apiKey!==void 0&&(i["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(i["x-tenant-id"]=n.workspaceId);let a=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 $r(s,"update run",!0),s})}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){Po(e);let n=await this._get(`/runs/${e}`);return r&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:r,projectOpts:n}){if(r!==void 0){let o;r.session_id?o=r.session_id:n?.projectName?o=(await this.readProject({projectName:n?.projectName})).id:n?.projectId?o=n?.projectId:o=(await this.readProject({projectName:ld("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 Ecn(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(I=>this.readProject({projectName:I}).then(j=>j.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")&&PY("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 $r(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 $r(f,"update project"),f})).json()}async hasProject({projectId:e,projectName:r}){let n="/sessions",o=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)Po(e),n+=`/${e}`;else if(r!==void 0)o.append("name",r);else throw new Error("Must provide projectName or projectId");let i=await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${n}?${o}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await $r(a,"has project"),a});try{let a=await i.json();return i.ok?Array.isArray(a)?a.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:r,includeStats:n}){let o="/sessions",i=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)Po(e),o+=`/${e}`;else if(r!==void 0)i.append("name",r);else throw new Error("Must provide projectName or projectId");n!==void 0&&i.append("include_stats",n.toString());let a=await this._get(o,i),s;if(Array.isArray(a)){if(a.length===0)throw new Error(`Project[id=${e}, name=${r}] not found`);s=a[0]}else s=a;return s}async getProjectUrl({projectId:e,projectName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either projectName or projectId");let n=await this.readProject({projectId:e,projectName:r}),o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");let n=await this.readDataset({datasetId:e,datasetName:r}),o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let e=new URLSearchParams({limit:"1"});for await(let r of this._getPaginated("/sessions",e))return this._tenantId=r[0].tenant_id,r[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:r,nameContains:n,referenceDatasetId:o,referenceDatasetName:i,includeStats:a,datasetVersion:s,referenceFree:u,metadata:l}={}){let c=new URLSearchParams;if(e!==void 0)for(let d of e)c.append("id",d);if(r!==void 0&&c.append("name",r),n!==void 0&&c.append("name_contains",n),o!==void 0)c.append("reference_dataset",o);else if(i!==void 0){let d=await this.readDataset({datasetName:i});c.append("reference_dataset",d.id)}a!==void 0&&c.append("include_stats",a.toString()),s!==void 0&&c.append("dataset_version",s),u!==void 0&&c.append("reference_free",u.toString()),l!==void 0&&c.append("metadata",JSON.stringify(l));for await(let d of this._getPaginated("/sessions",c))yield*d}async deleteProject({projectId:e,projectName:r}){let n;if(e===void 0&&r===void 0)throw new Error("Must provide projectNa
`).map(s=>JSON.parse(s))}async*listDatasets({limit:e=100,offset:r=0,datasetIds:n,datasetName:o,datasetNameContains:i,metadata:a}={}){let s="/datasets",u=new URLSearchParams({limit:e.toString(),offset:r.toString()});if(n!==void 0)for(let l of n)u.append("id",l);o!==void 0&&u.append("name",o),i!==void 0&&u.append("name_contains",i),a!==void 0&&u.append("metadata",JSON.stringify(a));for await(let l of this._getPaginated(s,u))yield*l}async updateDataset(e){let{datasetId:r,datasetName:n,...o}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let i=r??(await this.readDataset({datasetName:n})).id;Po(i);let a=JSON.stringify(o);return await(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await $r(u,"update dataset"),u})).json()}async updateDatasetTag(e){let{datasetId:r,datasetName:n,asOf:o,tag:i}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let a=r??(await this.readDataset({datasetName:n})).id;Po(a);let s=JSON.stringify({as_of:typeof o=="string"?o:o.toISOString(),tag:i});await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${a}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await $r(u,"update dataset tags",!0),u})}async deleteDataset({datasetId:e,datasetName:r}){let n="/datasets",o=e;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(o=(await this.readDataset({datasetName:r})).id),o!==void 0)Po(o),n+=`/${o}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{let i=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await $r(i,`delete ${n}`,!0),i})}async indexDataset({datasetId:e,datasetName:r,tag:n}){let o=e;if(!o&&!r)throw new Error("Must provide either datasetName or datasetId");if(o&&r)throw new Error("Must provide either datasetName or datasetId, not both");o||(o=(await this.readDataset({datasetName:r})).id),Po(o);let a=JSON.stringify({tag:n});await(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${o}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await $r(u,"index dataset"),u})).json()}async similarExamples(e,r,n,{filter:o}={}){let i={limit:n,inputs:e};o!==void 0&&(i.filter=o),Po(r);let a=JSON.stringify(i);return(await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${r}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:a});return await $r(l,"fetch similar examples"),l})).json()).examples}async createExample(e,r,n){if($xt(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;$xt(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]??nN())}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 $r(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]=iN(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 $r(u,`${r?"like":"unlike"} prompt`),u})).json()}async _getPromptUrl(e){let[r,n,o]=iN(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]=iN(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 $r(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]=iN(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 $r(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]=iN(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 $r(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 $r(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??nN()).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}=uqe(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=cqe(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=lqe(e,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=lqe(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=lqe(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 Npe(t){return typeof t=="function"&&"langsmith:traceable"in t}var hqe,mqe,zcn,gqe,Hcn,Jbi,Zxt=v(()=>{hqe=class{getStore(){}run(e,r){return r()}},mqe=Symbol.for("ls:tracing_async_local_storage"),zcn=new hqe,gqe=class{getInstance(){return globalThis[mqe]??zcn}initializeGlobalInstance(e){globalThis[mqe]===void 0&&(globalThis[mqe]=e)}},Hcn=new gqe;Jbi=Symbol.for("langsmith:traceable:root")});var yqe=v(()=>{Zxt()});var Vcn,$Y,Yxt=v(()=>{Do();XU();pqe();yqe();Mpe();Ape();Vcn={};Tt(Vcn,{LangChainTracer:()=>$Y});$Y=class Xxt extends V0{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??OY(),this.replicas=a,this.exampleId=n,this.client=i??Ipe();let s=Xxt.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 H0({...n,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return Gxt(!0)}catch{return}}}});var eOt=S((o_i,Dpe)=>{"use strict";var Jcn=Mke(),jpe=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},Qxt=(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 jpe(a);typeof t.cancel=="function"&&t.cancel(),o(s)},e);Jcn(t.then(n,o),()=>{clearTimeout(i)})});Dpe.exports=Qxt;Dpe.exports.default=Qxt;Dpe.exports.TimeoutError=jpe});var tOt=S(bqe=>{"use strict";Object.defineProperty(bqe,"__esModule",{value:!0});function Kcn(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=Kcn});var rOt=S(vqe=>{"use strict";Object.defineProperty(vqe,"__esModule",{value:!0});var Wcn=tOt(),_qe=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=Wcn.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}};vqe.default=_qe});var Cqe=S(Sqe=>{"use strict";Object.defineProperty(Sqe,"__esModule",{value:!0});var Gcn=Pke(),nOt=eOt(),Zcn=rOt(),$pe=()=>{},Xcn=new nOt.TimeoutError,wqe=class extends Gcn{constructor(e){var r,n,o,i;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=$pe,this._resolveIdle=$pe,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:Zcn.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 udn,Vpe,Jpe=v(()=>{udn=Object.prototype.hasOwnProperty;Vpe=class extends Error{constructor(t,e,r,n,o){super(hOt(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=hOt(t,{name:e,index:r,operation:n,tree:o})}}});function Kpe(t,e){if(e=="")return t;var r={op:"_get",path:e};return rz(t,r),r.value}function rz(t,e,r=!1,n=!0,o=!0,i=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):Wpe(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=Kpe(t,e.from),e.op==="move"&&(a.removed=t),a;if(e.op==="test"){if(a.test=qY(t,e.value),a.test===!1)throw new Sc("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return a.newDocument=t,a}else{if(e.op==="remove")return a.removed=t,a.newDocument=null,a;if(e.op==="_get")return e.value=t,a;if(r)throw new Sc("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return a}}else{n||(t=tb(t));let s=(e.path||"").split("/"),u=t,l=1,c=s.length,d,f,p;for(typeof r=="function"?p=r:p=Wpe;;){if(f=s[l],f&&f.indexOf("~")!=-1&&(f=Hpe(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&&!zpe(f))throw new Sc("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,t);zpe(f)&&(f=~~f)}if(l>=c){if(r&&e.op==="add"&&f>u.length)throw new Sc("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);let m=cdn[e.op].call(e,u,f,t);if(m.test===!1)throw new Sc("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return m}}else if(l>=c){let m=o6[e.op].call(e,u,f,t);if(m.test===!1)throw new Sc("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return m}if(u=u[f],r&&l<c&&(!u||typeof u!="object"))throw new Sc("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function K$(t,e,r,n=!0,o=!0){if(r&&!Array.isArray(e))throw new Sc("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=tb(t));let i=new Array(e.length);for(let a=0,s=e.length;a<s;a++)i[a]=rz(t,e[a],r,!0,o,a),t=i[a].newDocument;return i.newDocument=t,i}function ddn(t,e,r){let n=rz(t,e);if(n.test===!1)throw new Sc("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function Wpe(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new Sc("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(o6[t.op]){if(typeof t.path!="string")throw new Sc("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new Sc('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new Sc("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new Sc("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&qpe(t.value))throw new Sc("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,r);if(r){if(t.op=="add"){var o=t.path.split("/").length,i=n.split("/").length;if(o!==i+1&&o!==i)throw new Sc("Cannot pe
`)}var MOt,YY,l6,Xqe=v(()=>{a6();An();MOt=(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,qqe,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},YY=ve("$ZodError",MOt),l6=ve("$ZodError",MOt,{Parent:Error})});var eme,pO,tme,az,rme,Yqe,nme,Qqe,ome=v(()=>{a6();Xqe();An();eme=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=>Sv(u,i,cd())));throw Qpe(s,o?.callee),s}return a.value},pO=eme(l6),tme=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=>Sv(u,i,cd())));throw Qpe(s,o?.callee),s}return a.value},az=tme(l6),rme=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??YY)(i.issues.map(a=>Sv(a,o,cd())))}:{success:!0,data:i.value}},Yqe=rme(l6),nme=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=>Sv(a,o,cd())))}:{success:!0,data:i.value}},Qqe=nme(l6)});var uz={};Jn(uz,{_emoji:()=>AOt,base64:()=>mBe,base64url:()=>ime,bigint:()=>wBe,boolean:()=>xBe,browserEmail:()=>Hdn,cidrv4:()=>fBe,cidrv6:()=>pBe,cuid:()=>eBe,cuid2:()=>tBe,date:()=>yBe,datetime:()=>_Be,domain:()=>Vdn,duration:()=>aBe,e164:()=>gBe,email:()=>uBe,emoji:()=>lBe,extendedDuration:()=>Ldn,guid:()=>sBe,hostname:()=>hBe,html5Email:()=>Bdn,integer:()=>SBe,ipv4:()=>cBe,ipv6:()=>dBe,ksuid:()=>oBe,lowercase:()=>EBe,nanoid:()=>iBe,null:()=>OBe,number:()=>CBe,rfc5322Email:()=>Udn,string:()=>vBe,time:()=>bBe,ulid:()=>rBe,undefined:()=>TBe,unicodeEmail:()=>zdn,uppercase:()=>PBe,uuid:()=>sz,uuid4:()=>Fdn,uuid6:()=>kdn,uuid7:()=>qdn,xid:()=>nBe});function lBe(){return new RegExp(AOt,"u")}function NOt(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(`^${NOt(t)}$`)}function _Be(t){let e=NOt({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(`^${IOt}T(?:${n})$`)}var eBe,tBe,rBe,nBe,oBe,iBe,aBe,Ldn,sBe,sz,Fdn,kdn,qdn,uBe,Bdn,Udn,zdn,Hdn,AOt,cBe,dBe,fBe,pBe,mBe,ime,hBe,Vdn,gBe,IOt,yBe,vBe,wBe,SBe,CBe,xBe,OBe,TBe,EBe,PBe,ame=v(()=>{eBe=/^[cC][^\s-]{8,}$/,tBe=/^[0-9a-z]+$/,rBe=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,nBe=/^[0-9a-vA-V]{20}$/,oBe=/^[A-Za-z0-9]{27}$/,iBe=/^[a-zA-Z0-9_-]{21}$/,aBe=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Ldn=/^[-+]?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)?)??$/,sBe=/^([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})$/,sz=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)$/,Fdn=sz(4),kdn=sz(6),qdn=sz(7),uBe=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Bdn=/^[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])?)*$/,Udn=/^(([^<>()\[\]\\.,;:\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 WBe,GBe=v(()=>{WBe={major:4,minor:0,patch:0}});function gUe(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function WOt(t){if(!ime.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return gUe(r)}function GOt(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 LOt(t,e,r){t.issues.length&&e.issues.push(...Qb(r,t.issues)),e.value[r]=t.value}function cme(t,e,r){t.issues.length&&e.issues.push(...Qb(r,t.issues)),e.value[r]=t.value}function FOt(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 kOt(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=>Sv(i,n,cd())))}),e}function ZBe(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(u6(t)&&u6(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=ZBe(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=ZBe(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 qOt(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),iz(t))return t;let n=ZBe(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function dme(t,e,r){t.issues.length&&e.issues.push(...Qb(r,t.issues)),e.value[r]=t.value}function BOt(t,e,r,n,o,i,a){t.issues.length&&(GY.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=>Sv(s,a,cd()))})),e.issues.length&&(GY.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=>Sv(s,a,cd()))})),r.value.set(t.value,e.value)}function UOt(t,e){t.issues.length&&e.issues.push(...t.issues),e.value.add(t.value)}function zOt(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function HOt(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 VOt(t,e,r){return iz(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function JOt(t){return t.value=Object.freeze(t.value),t}function KOt(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(Wqe(o))}}var Yn,lz,vu,XBe,YBe,QBe,eUe,tUe,rUe,nUe,oUe,iUe,aUe,sUe,uUe,lUe,cUe,dUe,fUe,pUe,mUe,hUe,yUe,bUe,_Ue,vUe,wUe,fme,SUe,rQ,pme,CUe,xUe,OUe,TUe,EUe,G$,nQ,PUe,MUe,oQ,RUe,mme,AUe,IUe,cz,NUe,jUe,DUe,$Ue,LUe,FUe,iQ,d6,kUe,qUe,BUe,UUe,zUe,HUe,VUe,aQ,JUe,KUe,WUe,GUe,ZUe,sQ=v(()=>{lme();a6();KBe();ome();ame();An();GBe();An();Yn=ve("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=WBe;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=iz(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 ? [${oz(b)}, ...iss.path] : [${oz(b)}]
})));`),f.write(`newResult[${oz(b)}] = ${_}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let y=f.compile();return(b,_)=>y(d,b,_)},o,i=s6,a=!HY.jitless,u=a&&zqe.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?FOt(T,d,w,p):cme(T,d,w))):E?FOt(O,d,w,p):cme(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=>cme(x,d,_))):cme(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}});mme=ve("$ZodUnion",(t,e)=>{Yn.init(t,e),Ns(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Ns(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Ns(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Ns(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=>WY(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=>kOt(a,r,t,n)):kOt(i,r,t,n)}}),AUe=ve("$ZodDiscriminatedUnion",(t,e)=>{mme.init(t,e);let r=t._zod.parse;Ns(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=KY(()=>{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(!s6(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)}}),IUe=ve("$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])=>qOt(r,u,l)):qOt(r,i,a)}});cz=ve("$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=>dme(d,o,u))):dme(c,o,u)}if(e.rest){let l=a.slice(r.length);for(let c of l){u++;let d=e.rest._zod.run({value:c,issues:[]},i);d instanceof Promise?s.push(d.then(f=>dme(f,o,u))):dme(d,o,u)}}return s.length?Promise.all(s).then(()=>o):o}});NUe=ve("$ZodRecord",(t,e)=>{Yn.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!u6(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 CEt={};var xEt=v(()=>{});var pN={};Jn(pN,{$ZodAny:()=>EUe,$ZodArray:()=>oQ,$ZodAsyncError:()=>fO,$ZodBase64:()=>yUe,$ZodBase64URL:()=>bUe,$ZodBigInt:()=>pme,$ZodBigIntFormat:()=>CUe,$ZodBoolean:()=>rQ,$ZodCIDRv4:()=>mUe,$ZodCIDRv6:()=>hUe,$ZodCUID:()=>nUe,$ZodCUID2:()=>oUe,$ZodCatch:()=>HUe,$ZodCheck:()=>Zl,$ZodCheckBigIntFormat:()=>ABe,$ZodCheckEndsWith:()=>zBe,$ZodCheckGreaterThan:()=>ume,$ZodCheckIncludes:()=>BBe,$ZodCheckLengthEquals:()=>LBe,$ZodCheckLessThan:()=>sme,$ZodCheckLowerCase:()=>kBe,$ZodCheckMaxLength:()=>DBe,$ZodCheckMaxSize:()=>IBe,$ZodCheckMimeType:()=>VBe,$ZodCheckMinLength:()=>$Be,$ZodCheckMinSize:()=>NBe,$ZodCheckMultipleOf:()=>MBe,$ZodCheckNumberFormat:()=>RBe,$ZodCheckOverwrite:()=>JBe,$ZodCheckProperty:()=>HBe,$ZodCheckRegex:()=>FBe,$ZodCheckSizeEquals:()=>jBe,$ZodCheckStartsWith:()=>UBe,$ZodCheckStringFormat:()=>c6,$ZodCheckUpperCase:()=>qBe,$ZodCustom:()=>ZUe,$ZodCustomStringFormat:()=>wUe,$ZodDate:()=>MUe,$ZodDefault:()=>qUe,$ZodDiscriminatedUnion:()=>AUe,$ZodE164:()=>_Ue,$ZodEmail:()=>QBe,$ZodEmoji:()=>tUe,$ZodEnum:()=>$Ue,$ZodError:()=>YY,$ZodFile:()=>FUe,$ZodFunction:()=>Fme,$ZodGUID:()=>XBe,$ZodIPv4:()=>fUe,$ZodIPv6:()=>pUe,$ZodISODate:()=>lUe,$ZodISODateTime:()=>uUe,$ZodISODuration:()=>dUe,$ZodISOTime:()=>cUe,$ZodIntersection:()=>IUe,$ZodJWT:()=>vUe,$ZodKSUID:()=>sUe,$ZodLazy:()=>GUe,$ZodLiteral:()=>LUe,$ZodMap:()=>jUe,$ZodNaN:()=>VUe,$ZodNanoID:()=>rUe,$ZodNever:()=>nQ,$ZodNonOptional:()=>UUe,$ZodNull:()=>TUe,$ZodNullable:()=>kUe,$ZodNumber:()=>fme,$ZodNumberFormat:()=>SUe,$ZodObject:()=>RUe,$ZodOptional:()=>d6,$ZodPipe:()=>aQ,$ZodPrefault:()=>BUe,$ZodPromise:()=>WUe,$ZodReadonly:()=>JUe,$ZodRealError:()=>l6,$ZodRecord:()=>NUe,$ZodRegistry:()=>f6,$ZodSet:()=>DUe,$ZodString:()=>lz,$ZodStringFormat:()=>vu,$ZodSuccess:()=>zUe,$ZodSymbol:()=>xUe,$ZodTemplateLiteral:()=>KUe,$ZodTransform:()=>iQ,$ZodTuple:()=>cz,$ZodType:()=>Yn,$ZodULID:()=>iUe,$ZodURL:()=>eUe,$ZodUUID:()=>YBe,$ZodUndefined:()=>OUe,$ZodUnion:()=>mme,$ZodUnknown:()=>G$,$ZodVoid:()=>PUe,$ZodXID:()=>aUe,$brand:()=>Lqe,$constructor:()=>ve,$input:()=>eze,$output:()=>QUe,Doc:()=>tQ,JSONSchema:()=>CEt,JSONSchemaGenerator:()=>xQ,NEVER:()=>$qe,TimePrecision:()=>oze,_any:()=>Oze,_array:()=>CQ,_base64:()=>jme,_base64url:()=>Dme,_bigint:()=>bze,_boolean:()=>gze,_catch:()=>Gfn,_cidrv4:()=>Ime,_cidrv6:()=>Nme,_coercedBigint:()=>_ze,_coercedBoolean:()=>yze,_coercedDate:()=>Pze,_coercedNumber:()=>cze,_coercedString:()=>nze,_cuid:()=>Ome,_cuid2:()=>Tme,_custom:()=>Lze,_date:()=>Eze,_default:()=>Jfn,_discriminatedUnion:()=>Dfn,_e164:()=>$me,_email:()=>yme,_emoji:()=>Cme,_endsWith:()=>yQ,_enum:()=>qfn,_fil
`;return e}function DEt(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()??"",_=npn.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}",Vze(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+=` ${Vze(y)}${x}${Vze(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+=opn(i??{})),l}async function $Et(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 npn,LEt=v(()=>{npn=["*","_","`"]});var kEt,FEt,qEt,Ume=v(()=>{kEt=Symbol("Let zodToJsonSchema decide on which parser to use"),FEt={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"},qEt=t=>typeof t=="string"?{...FEt,name:t}:{...FEt,...t}});var BEt,Jze=v(()=>{Ume();BEt=t=>{let e=qEt(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 zme,Hme=v(()=>{zme=(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 wl(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?zme(e,t.currentPath):e.join("/")}}var Uw=v(()=>{Hme()});function Kze(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function $i(t,e,r,n,o){t[e]=r,Kze(t,e,n,o)}var nL=v(()=>{});var vi,Wze,rr,mO,TQ=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})})(Wze||(Wze={}));rr=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 rr.undefined;case"string":return rr.string;case"number":return Number.isNaN(t)?rr.nan:rr.number;case"boolean":return rr.boolean;case"function":return rr.function;case"bigint":return rr.bigint;case"symbol":return rr.symbol;case"object":return Array.isArray(t)?rr.array:t===null?rr.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?rr.promise:typeof Map<"u"&&t instanceof Map?rr.map:typeof Set<"u"&&t instanceof Set?rr.set:typeof Date<"u"&&t instanceof Date?rr.date:rr.object;default:return rr.unknown}}});var Xe,ipn,t_,Vme=v(()=>{TQ();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"]),ipn=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 c4e,K0,ymn,the=v(()=>{nL();K0={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:()=>(c4e===void 0&&(c4e=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),c4e),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-_]*$/};ymn=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function rhe(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===Me.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:Sn(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??wl(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Sn(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===Me.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=ehe(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===Me.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===Me.ZodBranded&&t.keyType._def.type._def.typeName===Me.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Yme(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var nhe=v(()=>{Uw();Qme();the();dd();yO()});function fPt(t,e){if(e.mapStrategy==="record")return rhe(t,e);let r=Sn(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||wl(e),n=Sn(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||wl(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var f4e=v(()=>{Uw();nhe();dd()});function pPt(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(ze)}let At=`${s}/$ref`,ke=Nu(t,Fe,r,n,o,i,a,At,u);if(ke.valid||Ie.push({instanceLocation:a,keyword:"$ref",keywordLocation:At,error:"A subschema had errors."},...ke.errors),r==="4"||r==="7")return{valid:Ie.length===0,errors:Ie}}if(Array.isArray(m)){let Ct=m.length,Fe=!1;for(let At=0;At<Ct;At++)if(c===m[At]||m[At]==="integer"&&c==="number"&&t%1===0&&t===t){Fe=!0;break}Fe||Ie.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)&&Ie.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m}".`}):m!==void 0&&c!==m&&Ie.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)||Ie.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):t!==h&&Ie.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(Ct=>bO(t,Ct))||Ie.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(Ct=>t===Ct)||Ie.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),b!==void 0){let Ct=`${s}/not`;Nu(t,b,r,n,o,i,a,Ct).valid&&Ie.push({instanceLocation:a,keyword:"not",keywordLocation:Ct,error:'Instance matched "not" schema.'})}let _n=[];if(_!==void 0){let Ct=`${s}/anyOf`,Fe=Ie.length,At=!1;for(let ke=0;ke<_.length;ke++){let ze=_[ke],$e=Object.create(u),Pt=Nu(t,ze,r,n,o,p===!0?i:null,a,`${Ct}/${ke}`,$e);Ie.push(...Pt.errors),At=At||Pt.valid,Pt.valid&&_n.push($e)}At?Ie.length=Fe:Ie.splice(Fe,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:Ct,error:"Instance does not match any subschemas."})}if(w!==void 0){let Ct=`${s}/allOf`,Fe=Ie.length,At=!0;for(let ke=0;ke<w.length;ke++){let ze=w[ke],$e=Object.create(u),Pt=Nu(t,ze,r,n,o,p===!0?i:null,a,`${Ct}/${ke}`,$e);Ie.push(...Pt.errors),At=At&&Pt.valid,Pt.valid&&_n.push($e)}At?Ie.length=Fe:Ie.splice(Fe,0,{instanceLocation:a,keyword:"allOf",keywordLocation:Ct,error:"Instance does not match every subschema."})}if(x!==void 0){let Ct=`${s}/oneOf`,Fe=Ie.length,At=x.filter((ke,ze)=>{let $e=Object.create(u),Pt=Nu(t,ke,r,n,o,p===!0?i:null,a,`${Ct}/${ze}`,$e);return Ie.push(...Pt.errors),Pt.valid&&_n.push($e),Pt.valid}).length;At===1?Ie.length=Fe:Ie.splice(Fe,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:Ct,error:`Instance does not match exactly one subschema (${At} matches).`})}if((c==="object"||c==="array")&&Object.assign(u,..._n),O!==void 0){let Ct=`${s}/if`;if(Nu(t,O,r,n,o,i,a,Ct,u).valid){if(E!==void 0){let At=Nu(t,E,r,n,o,i,a,`${s}/then`,u);At.valid||Ie.push({instanceLocation:a,keyword:"if",keywordLocation:Ct,error:'Instance does not match "then" schema.'},...At.errors)}}else if(T!==void 0){let At=Nu(t,T,r,n,o,i,a,`${s}/else`,u);At.valid||Ie.push({instanceLocation:a,keyword:"if",keywordLocation:Ct,error:'Instance does not match "else" schema.'},...At.errors)}}if(c==="object"){if(y!==void 0)for(let ke of y)ke in t||Ie.push({instanceLocation:a,keyword:"required",keywordLocation:`${s}/required`,error:`Instance does not have required property "${ke}".`});let Ct=Object.keys(t);if(U!==void 0&&Ct.length<U&&Ie.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${U} properties.`}),J!==void 0&&Ct.length>J&&Ie.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${J} properties.`}),G!==void 0){let ke=`${s}/propertyNames`;for(let ze in t){let $e=`${a}/${Cv(ze)}`,Pt=Nu(ze,G,r,n,o,i,$e,ke);Pt.valid||Ie.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:ke,error:`Property name "${ze}" does not
data: ${JSON.stringify(o)}
`));n.enqueue(e.encode(`event: end
`)),n.close()}});return Qy.fromReadableStream(r)}var zPt=v(()=>{cO()});function j4e(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}function che(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function*D4e(t,e){for(;;){let{value:r,done:n}=rh.runWithConfig(Yy(t),e.next.bind(e),!0);if(n)break;yield r}}async function*dhe(t,e){let r=e[Symbol.asyncIterator]();for(;;){let{value:n,done:o}=await rh.runWithConfig(Yy(t),r.next.bind(e),!0);if(o)break;yield n}}var HPt,VPt=v(()=>{QU();ez();uO();HPt=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function"});function fd(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function shn(t){if(Npe(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}function xv(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]=xv(n);return new uL({steps:e})}else throw new Error(`Expected a Runnable, function or object.
Instead got an unsupported type.`)}function uhn(t,e){let r=e.name??t.getName(),n=e.description??rL(e.schema);return y6(e.schema)?new fhe({name:r,description:n,schema:mt.object({input:mt.string()}).transform(o=>o.input),bound:t}):new fhe({name:r,description:n,schema:e.schema,bound:t})}var $4e,Lo,Jw,KPt,phe,Sl,uL,ahn,i_,YPt,L4e,NQ,F4e,fhe,Yh=v(()=>{F$();Afe();QU();ez();uO();kY();cO();vOt();OOt();nz();EOt();Dqe();mN();BPt();zPt();VPt();yO();$4e=L(ipe(),1);SY();yqe();Lo=class extends Wh{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 phe({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new Jw({bound:this,config:e,kwargs:{}})}withFallbacks(e){let r=Array.isArray(e)?e:e.fallbacks;return new L4e({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 kw({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 J$({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 Qg(o))?.handleChainStart(this.toJSON(),fd(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(fd(s,"output")),s}async _batchWithConfig(e,r,n,o){let i=this._getOptionsList(n??{},r.length),a=await Promise.all(i.map(Qg)),s=await Promise.all(a.map(async(l,c)=>{let d=await l?.handleChainStart(this.toJSON(),fd(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(fd(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 Qg(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 Mqe(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(COt),h=p.output;m!==void 0&&f!==void 0&&(h=m.tapOutputIterable(f.runId,h));let g=f?.handlers.find(Nqe);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:fd
${a.content}`),e.push(chn(s))}}return e}function lMt(t,e){if(Array.isArray(t)){let r=t;if(!e)throw new Error("Options parameter is required when providing messages.");return iMt(r,e)}else{let r=t;return i_.from(n=>iMt(n,r)).withConfig({runName:"trim_messages"})}}async function iMt(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=q4e;if(l&&("splitText"in l?d=l.splitText:d=async f=>l(f)),o==="first")return cMt(t,{maxTokens:r,tokenCounter:c,textSplitter:d,partialStrategy:i?"first":void 0,endOn:a});if(o==="last")return lhn(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 cMt(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=k4e(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&&!hhe(s[u-1],l);)u-=1}return s.slice(0,u)}async function lhn(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 k4e(c.getType(),d,Y3(c))});if(o){let c=Array.isArray(o)?o:[o];for(;s.length>0&&!hhe(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 cMt(l,{...a,partialStrategy:r?"last":void 0,endOn:i}),u?[l[0],...l.slice(1).reverse()]:l.reverse()}function k4e(t,e,r){let n,o;switch(t){case"human":r?n=new vv(e):o=new au(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 Nr(i)}else o=new li(e);break;case"system":r?n=new Ky(e):o=new th(e);break;case"developer":r?n=new Ky({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}}):o=new th({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in e)r?n=new Iw(e):o=new 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 _v(e);else{if(!e.name)throw new Error("FunctionMessage must have a 'name' field");o=new zU(e)}break;case"generic":if("role"in e)r?n=new bv(e):o=new ud(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 chn(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 hhe,aMt,dMt=v(()=>{Gg();Q3();z0();_Y();Ufe();U$();vY();zfe();iO();Yh();hhe=(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)};aMt={human:{message:au,messageChunk:vv},ai:{message:li,messageChunk:Nr},system:{message:th,messageChunk:Ky},developer:{message:th,messageChunk:Ky},tool:{message:Gb,messageChunk:Iw},function:{message:zU,messageChunk:_v},generic:{message:ud,messageChunk:bv},remove:{message:HU,messageChunk:HU}}});var fMt,pMt=v(()=>{fMt=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"]});var mMt,hMt=v(()=>{mMt=["image","video","audio","text-plain","file"]});var gMt,yMt=v(()=>{pMt();hMt();gMt=["text","reasoning",...fMt,...mMt]});var dhn,js=v(()=>{Do();mY();BFe();Gg();JFe();Q3();z0();_Y();Ufe();U$();vY();zfe();iO();dMt();yMt();dhn={};Tt(dhn,{AIMessage:()=>li,AIMessageChunk:()=>Nr,BaseMessage:()=>Uc,BaseMessageChunk:()=>Wb,ChatMessage:()=>ud,ChatMessageChunk:()=>bv,FunctionMessage:()=>zU,FunctionMessageChunk:()=>_v,HumanMessage:()=>au,HumanMessageChunk:()=>vv,KNOWN_BLOCK_TYPES:()=>gMt,RemoveMessage:()=>HU,SystemMessage:()=>th,SystemMessageChunk:()=>Ky,ToolMessage:()=>Gb,ToolMessageChunk:()=>Iw,_isMessageFieldWithRole:()=>kfe,_mergeDicts:()=>_l,_mergeLists:()=>UU,_mergeObj:()=>Ffe,_mergeStatus:()=>Lfe,coerceMessageLikeToMessage:()=>Nw,convertToChunk:()=>VU,convertToOpenAIImageBlock:()=>Nfe,convertToProviderContentBlock:()=>oO,defaultTextSplitter:()=>q4e,defaultToolCallParser:()=>gY,filterMessages:()=>sMt,getBufferString:()=>Xu,iife:()=>sSt,isAIMessage:()=>qs,isAIMessageChunk:()=>bY,isBase64ContentBlock:()=>X3,isBaseMessage:()=>eh,isBaseMessageChunk:()=>Y3,isChatMessage:()=>Qwt,isChatMessageChunk:()=>eSt,isDataContentBlock:()=>Qm,isDirectToolOutput:()=>hY,isFunctionMessage:()=>tSt,isFunctionMessageChunk:()=>rSt,isHumanMessage:()=>nSt,isHumanMessageChunk:()=>oSt,isIDContentBlock:()=>Ife,isMessage:()=>$fe,isOpenAIToolCallArray:()=>qwt,isPlainTextContentBlock:()=>Mwt,isSystemMessage:()=>iSt,isSystemMessageChunk:()=>aSt,isToolMessage:()=>yY,isToolMessageChunk:()=>zFe,isURLContentBlock:()=>Z3,mapChatMessagesToStoredMessages:()=>lSt,mapStoredMessageToChatMessage:()=>wY,mapStoredMessagesToChatMessages:()=>uSt,mergeContent:()=>Kb,mergeMessageRuns:()=>uMt,mergeResponseMetadata:()=>qfe,mergeUsageMetadata:()=>Bfe,parseBase64DataUrl:()=>Wg,parseMimeType:()=>pY,trimMessages:()=>lMt})});var bMt,_Mt=v(()=>{Gg();z0();U$();Yh();js();mhe();bMt=class extends Jw{constructor(e){let r=i_.from((a,s)=>this._enterHistory(a,s??{})).withConfig({runName:"loadHistory"}),n=e.historyMessagesKey??e.inputMessagesKey;n&&(r=wu.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)&&!eh(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 au(r)];if(Array.isArray(r))return r;if(eh(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)&&!eh(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(eh(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 fhn,Ov=v(()=>{Do();uO();Yh();mhe();eMt();rMt();_Mt();fhn={};Tt(fhn,{RouterRunnable:()=>QPt,Runnable:()=>Lo,RunnableAssign:()=>NQ,RunnableBinding:()=>Jw,RunnableBranch:()=>tMt,RunnableEach:()=>KPt,RunnableLambda:()=>i_,RunnableMap:()=>uL,RunnableParallel:()=>YPt,RunnablePassthrough:()=>wu,RunnablePick:()=>F4e,RunnableRetry:()=>phe,RunnableSequence:()=>Sl,RunnableToolLike:()=>fhe,RunnableWithFallbacks:()=>L4e,RunnableWithMessageHistory:()=>bMt,_coerceToRunnable:()=>xv,ensureConfig:()=>Jo,getCallbackManagerForConfig:()=>Qg,mergeConfigs:()=>tz,patchConfig:()=>Bs,pickRunnableConfigKeys:()=>Yy})});var Mz,_N,nh,E6=v(()=>{dY();Yh();Ov();Mz=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"})}},_N=class extends Mz{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")}},nh=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");L$(this,"OUTPUT_PARSING_FAILURE")}}});var vN,lL,cL=v(()=>{Gg();iO();gm();E6();uhe();vN=class extends _N{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"})}},lL=class extends vN{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(Y3(o)){if(typeof o.content!="string")throw new Error("Cannot handle non-string message output.");i=new Oi({message:o,text:o.content})}else if(eh(o)){if(typeof o.content!="string")throw new Error("Cannot handle non-string message output.");i=new Oi({message:VU(o),text:o.content})}else i=new Fw({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 vMt,wMt=v(()=>{cL();vMt=class extends vN{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 P6,SMt,CMt,xMt,OMt,TMt=v(()=>{E6();cL();P6=class extends vN{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]}},SMt=class extends P6{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 nh(`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])}},OMt=class extends P6{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 ghe,EMt=v(()=>{cL();ghe=class extends vN{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 Kw,B4e,PMt,MMt=v(()=>{mN();o_();E6();yO();Kw=class extends _N{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=mt.object(Object.fromEntries(Object.entries(e).map(([n,o])=>[n,mt.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(Hi(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 tL(this.schema,JSON.parse(o))}catch(r){throw new nh(`Failed to parse. Text: "${e}". Error: ${r}`,e)}}},B4e=class extends Kw{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(Hi(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=mt.object(Object.fromEntries(Object.entries(t).map(([r,n])=>[r,mt.string().describe(n)])));return new this(e)}},PMt=class extends _N{constructor({inputSchema:e}){super(...arguments);M(this,"structuredInputParser");this.structuredInputParser=new B4e(e)}async parse(e){let r;try{r=await this.structuredInputParser.parse(e)}catch(n){throw new nh(`Failed to parse. Text: "${e}". Error: ${n}`,e)}return this.outputProcessor(r)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}}});var phn,U4e=v(()=>{Do();BY();UY();Aqe();phn={};Tt(phn,{applyPatch:()=>K$,compare:()=>i6})});var Tv,z4e=v(()=>{cY();UY();cL();U4e();Tv=class extends lL{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?i6(e,r):[{op:"replace",path:"",value:r}]}async parsePartialResult(e){return lY(e[0].text)}async parse(e){return lY(e,JSON.parse)}getFormatInstructions(){return""}}});var mhn,RMt,AMt=v(()=>{mhn=function(){let t={};t.parser=function(D,A){return new r(D,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(D,A){if(!(this instanceof r))return new r(D,A);var V=this;o(V),V.q=V.c="",V.bufferCheckPosition=t.MAX_BUFFER_LENGTH,V.opt=A||{},V.opt.lowercase=V.opt.lowercase||V.opt.lowercasetags,V.looseCase=V.opt.lowercase?"toLowerCase":"toUpperCase",V.tags=[],V.closed=V.closedRoot=V.sawRoot=!1,V.tag=V.error=null,V.strict=!!D,V.noscript=!!(D||V.opt.noscript),V.state=T.BEGIN,V.strictEntities=V.opt.strictEntities,V.ENTITIES=V.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),V.attribList=[],V.opt.xmlns&&(V.ns=Object.create(m)),V.trackPosition=V.opt.position!==!1,V.trackPosition&&(V.position=V.line=V.column=0),I(V,"onready")}Object.create||(Object.create=function(D){function A(){}A.prototype=D;var V=new A;return V}),Object.keys||(Object.keys=function(D){var A=[];for(var V in D)D.hasOwnProperty(V)&&A.push(V);return A});function n(D){for(var A=Math.max(t.MAX_BUFFER_LENGTH,10),V=0,K=0,se=e.length;K<se;K++){var be=D[e[K]].length;if(be>A)switch(e[K]){case"textNode":F(D);break;case"cdata":j(D,"oncdata",D.cdata),D.cdata="";break;case"script":j(D,"onscript",D.script),D.script="";break;default:U(D,"Max buffer length exceeded: "+e[K])}V=Math.max(V,be)}var xe=t.MAX_BUFFER_LENGTH-V;D.bufferCheckPosition=xe+D.position}function o(D){for(var A=0,V=e.length;A<V;A++)D[e[A]]=""}function i(D){F(D),D.cdata!==""&&(j(D,"oncdata",D.cdata),D.cdata=""),D.script!==""&&(j(D,"onscript",D.script),D.script="")}r.prototype={end:function(){J(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(D){return D!=="error"&&D!=="end"});function u(D,A){return new l(D,A)}function l(D,A){if(!(this instanceof l))return new l(D,A);a.apply(this),this._parser=new r(D,A),this.writable=!0,this.readable=!0;var V=this;this._parser.onend=function(){V.emit("end")},this._parser.onerror=function(K){V.emit("error",K),V._parser.error=null},this._decoder=null,s.forEach(function(K){Object.defineProperty(V,"on"+K,{get:function(){return V._parser["on"+K]},set:function(se){if(!se)return V.removeAllListeners(K),V._parser["on"+K]=se,se;V.on(K,se)},enumerable:!0,configurable:!1})})}l.prototype=Object.create(a.prototype,{constructor:{value:l}}),l.prototype.write=function(D){return this._parse
`||D==="\r"||D===" "}function w(D){return D==='"'||D==="'"}function x(D){return D===">"||_(D)}function O(D,A){return D.test(A)}function E(D,A){return!O(D,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(D){var A=t.ENTITIES[D],V=typeof A=="number"?String.fromCharCode(A):A;t.ENTITIES[D]=V});for(var R in t.STATE)t.STATE[t.STATE[R]]=R;T=t.STATE;function I(D,A,V){D[A]&&D[A](V)}function j(D,A,V){D.textNode&&F(D),I(D,A,V)}function F(D){D.textNode=B(D.opt,D.textNode),D.textNode&&I(D,"ontext",D.textNode),D.textNode=""}function B(D,A){return D.trim&&(A=A.trim()),D.normalize&&(A=A.replace(/\s+/g," ")),A}function U(D,A){return F(D),D.trackPosition&&(A+=`
Line: `+D.line+`
Column: `+D.column+`
Char: `+D.c),A=new Error(A),D.error=A,I(D,"onerror",A),D}function J(D){return D.sawRoot&&!D.closedRoot&&G(D,"Unclosed root tag"),D.state!==T.BEGIN&&D.state!==T.BEGIN_WHITESPACE&&D.state!==T.TEXT&&U(D,"Unexpected end"),F(D),D.c="",D.closed=!0,I(D,"onend"),r.call(D,D.strict,D.opt),D}function G(D,A){if(typeof D!="object"||!(D instanceof r))throw new Error("bad call to strictFail");D.strict&&U(D,A)}function oe(D){D.strict||(D.tagName=D.tagName[D.looseCase]());var A=D.tags[D.tags.length-1]||D,V=D.tag={name:D.tagName,attributes:{}};D.opt.xmlns&&(V.ns=A.ns),D.attribList.length=0,j(D,"onopentagstart",V)}function ne(D,A){var V=D.indexOf(":"),K=V<0?["",D]:D.split(":"),se=K[0],be=K[1];return A&&D==="xmlns"&&(se="xmlns",be=""),{prefix:se,local:be}}function z(D){if(D.strict||(D.attribName=D.attribName[D.looseCase]()),D.attribList.indexOf(D.attribName)!==-1||D.tag.attributes.hasOwnProperty(D.attribName)){D.attribName=D.attribValue="";return}if(D.opt.xmlns){var A=ne(D.attribName,!0),V=A.prefix,K=A.local;if(V==="xmlns")if(K==="xml"&&D.attribValue!==f)G(D,"xml: prefix must be bound to "+f+`
Actual: `+D.attribValue);else if(K==="xmlns"&&D.attribValue!==p)G(D,"xmlns: prefix must be bound to "+p+`
Actual: `+D.attribValue);else{var se=D.tag,be=D.tags[D.tags.length-1]||D;se.ns===be.ns&&(se.ns=Object.create(be.ns)),se.ns[K]=D.attribValue}D.attribList.push([D.attribName,D.attribValue])}else D.tag.attributes[D.attribName]=D.attribValue,j(D,"onattribute",{name:D.attribName,value:D.attribValue});D.attribName=D.attribValue=""}function ee(D,A){if(D.opt.xmlns){var V=D.tag,K=ne(D.tagName);V.prefix=K.prefix,V.local=K.local,V.uri=V.ns[K.prefix]||"",V.prefix&&!V.uri&&(G(D,"Unbound namespace prefix: "+JSON.stringify(D.tagName)),V.uri=K.prefix);var se=D.tags[D.tags.length-1]||D;V.ns&&se.ns!==V.ns&&Object.keys(V.ns).forEach(function(_n){j(D,"onopennamespace",{prefix:_n,uri:V.ns[_n]})});for(var be=0,xe=D.attribList.length;be<xe;be++){var Pe=D.attribList[be],pt=Pe[0],Ht=Pe[1],Ze=ne(pt,!0),Yr=Ze.prefix,Vt=Ze.local,gt=Yr===""?"":V.ns[Yr]||"",Ie={name:pt,value:Ht,prefix:Yr,local:Vt,uri:gt};Yr&&Yr!=="xmlns"&&!gt&&(G(D,"Unbound namespace prefix: "+JSON.stringify(Yr)),Ie.uri=Yr),D.tag.attributes[pt]=Ie,j(D,"onattribute",Ie)}D.attribList.length=0}D.tag.isSelfClosing=!!A,D.sawRoot=!0,D.tags.push(D.tag),j(D,"onopentag",D.tag),A||(!D.noscript&&D.tagName.toLowerCase()==="script"?D.state=T.SCRIPT:D.state=T.TEXT,D.tag=null,D.tagName=""),D.attribName=D.attribValue="",D.attribList.length=0}function ie(D){if(!D.tagName){G(D,"Weird empty close tag."),D.textNode+="</>",D.state=T.TEXT;return}if(D.script){if(D.tagName!=="script"){D.script+="</"+D.tagName+">",D.tagName="",D.state=T.SCRIPT;return}j(D,"onscript",D.script),D.script=""}var A=D.tags.length,V=D.tagName;D.strict||(V=V[D.looseCase]());for(var K=V;A--;){var se=D.tags[A];if(se.name!==K)G(D,"Unexpected close tag");else break}if(A<0){G(D,"Unmatched closing tag: "+D.tagName),D.textNode+="</"+D.tagName+">",D.state=T.TEXT;return}D.tagName=V;for(var be=D.tags.length;be-- >A;){var xe=D.tag=D.tags.pop();D.tagName=D.tag.name,j(D,"onclosetag",D.tagName);var Pe={};for(var pt in xe.ns)Pe[pt]=xe.ns[pt];var Ht=D.tags[D.tags.length-1]||D;D.opt.xmlns&&xe.ns!==Ht.ns&&Object.keys(xe.ns).forEach(function(Ze){var Yr=xe.ns[Ze];j(D,"onclosenamespace",{prefix:Ze,uri:Yr})})}A===0&&(D.closedRoot=!0),D.tagName=D.attribValue=D.attribName="",D.attribList.length=0,D.state=T.TEXT}function Z(D){var A=D.entity,V=A.toLowerCase(),K,se="";return D.ENTITIES[A]?D.ENTITIES[A]:D.ENTITIES[V]?D.ENTITIES[V]:(A=V,A.charAt(0)==="#"&&(A.charAt(1)==="x"?(A=A.slice(2),K=parseInt(A,16),se=K.toString(16)):(A=A.slice(1),K=parseInt(A,10),se=K.toString(10))),A=A.replace(/^0+/,""),isNaN(K)||se.toLowerCase()!==A?(G(D,"Invalid character entity"),"&"+D.entity+";"):String.fromCodePoint(K))}function $(D,A){A==="<"?(D.state=T.OPEN_WAKA,D.startTagPosition=D.position):_(A)||(G(D,"Non-whitespace before first tag."),D.textNode=A,D.state=T.TEXT)}function q(D,A){var V="";return A<D.length&&(V=D.charAt(A)),V}function Y(D){var A=this;if(this.error)throw this.error;if(A.closed)return U(A,"Cannot write after close. Assign an onready handler.");if(D===null)return J(A);typeof D=="object"&&(D=D.toString());for(var V=0,K="";K=q(D,V++),A.c=K,!!K;)switch(A.trackPosition&&(A.position++,K===`
`?(A.line++,A.column=0):A.column++),A.state){case T.BEGIN:if(A.state=T.BEGIN_WHITESPACE,K==="\uFEFF")continue;$(A,K);continue;case T.BEGIN_WHITESPACE:$(A,K);continue;case T.TEXT:if(A.sawRoot&&!A.closedRoot){for(var se=V-1;K&&K!=="<"&&K!=="&";)K=q(D,V++),K&&A.trackPosition&&(A.position++,K===`
`?(A.line++,A.column=0):A.column++);A.textNode+=D.substring(se,V-1)}K==="<"&&!(A.sawRoot&&A.closedRoot&&!A.strict)?(A.state=T.OPEN_WAKA,A.startTagPosition=A.position):(!_(K)&&(!A.sawRoot||A.closedRoot)&&G(A,"Text data outside of root node."),K==="&"?A.state=T.TEXT_ENTITY:A.textNode+=K);continue;case T.SCRIPT:K==="<"?A.state=T.SCRIPT_ENDING:A.script+=K;continue;case T.SCRIPT_ENDING:K==="/"?A.state=T.CLOSE_TAG:(A.script+="<"+K,A.state=T.SCRIPT);continue;case T.OPEN_WAKA:if(K==="!")A.state=T.SGML_DECL,A.sgmlDecl="";else if(!_(K))if(O(h,K))A.state=T.OPEN_TAG,A.tagName=K;else if(K==="/")A.state=T.CLOSE_TAG,A.tagName="";else if(K==="?")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;K=new Array(be).join(" ")+K}A.textNode+="<"+K,A.state=T.TEXT}continue;case T.SGML_DECL:(A.sgmlDecl+K).toUpperCase()===c?(j(A,"onopencdata"),A.state=T.CDATA,A.sgmlDecl="",A.cdata=""):A.sgmlDecl+K==="--"?(A.state=T.COMMENT,A.comment="",A.sgmlDecl=""):(A.sgmlDecl+K).toUpperCase()===d?(A.state=T.DOCTYPE,(A.doctype||A.sawRoot)&&G(A,"Inappropriately located doctype declaration"),A.doctype="",A.sgmlDecl=""):K===">"?(j(A,"onsgmldeclaration",A.sgmlDecl),A.sgmlDecl="",A.state=T.TEXT):(w(K)&&(A.state=T.SGML_DECL_QUOTED),A.sgmlDecl+=K);continue;case T.SGML_DECL_QUOTED:K===A.q&&(A.state=T.SGML_DECL,A.q=""),A.sgmlDecl+=K;continue;case T.DOCTYPE:K===">"?(A.state=T.TEXT,j(A,"ondoctype",A.doctype),A.doctype=!0):(A.doctype+=K,K==="["?A.state=T.DOCTYPE_DTD:w(K)&&(A.state=T.DOCTYPE_QUOTED,A.q=K));continue;case T.DOCTYPE_QUOTED:A.doctype+=K,K===A.q&&(A.q="",A.state=T.DOCTYPE);continue;case T.DOCTYPE_DTD:A.doctype+=K,K==="]"?A.state=T.DOCTYPE:w(K)&&(A.state=T.DOCTYPE_DTD_QUOTED,A.q=K);continue;case T.DOCTYPE_DTD_QUOTED:A.doctype+=K,K===A.q&&(A.state=T.DOCTYPE_DTD,A.q="");continue;case T.COMMENT:K==="-"?A.state=T.COMMENT_ENDING:A.comment+=K;continue;case T.COMMENT_ENDING:K==="-"?(A.state=T.COMMENT_ENDED,A.comment=B(A.opt,A.comment),A.comment&&j(A,"oncomment",A.comment),A.comment=""):(A.comment+="-"+K,A.state=T.COMMENT);continue;case T.COMMENT_ENDED:K!==">"?(G(A,"Malformed comment"),A.comment+="--"+K,A.state=T.COMMENT):A.state=T.TEXT;continue;case T.CDATA:K==="]"?A.state=T.CDATA_ENDING:A.cdata+=K;continue;case T.CDATA_ENDING:K==="]"?A.state=T.CDATA_ENDING_2:(A.cdata+="]"+K,A.state=T.CDATA);continue;case T.CDATA_ENDING_2:K===">"?(A.cdata&&j(A,"oncdata",A.cdata),j(A,"onclosecdata"),A.cdata="",A.state=T.TEXT):K==="]"?A.cdata+="]":(A.cdata+="]]"+K,A.state=T.CDATA);continue;case T.PROC_INST:K==="?"?A.state=T.PROC_INST_ENDING:_(K)?A.state=T.PROC_INST_BODY:A.procInstName+=K;continue;case T.PROC_INST_BODY:if(!A.procInstBody&&_(K))continue;K==="?"?A.state=T.PROC_INST_ENDING:A.procInstBody+=K;continue;case T.PROC_INST_ENDING:K===">"?(j(A,"onprocessinginstruction",{name:A.procInstName,body:A.procInstBody}),A.procInstName=A.procInstBody="",A.state=T.TEXT):(A.procInstBody+="?"+K,A.state=T.PROC_INST_BODY);continue;case T.OPEN_TAG:O(g,K)?A.tagName+=K:(oe(A),K===">"?ee(A):K==="/"?A.state=T.OPEN_TAG_SLASH:(_(K)||G(A,"Invalid character in tag name"),A.state=T.ATTRIB));continue;case T.OPEN_TAG_SLASH:K===">"?(ee(A,!0),ie(A)):(G(A,"Forward-slash in opening tag not followed by >"),A.state=T.ATTRIB);continue;case T.ATTRIB:if(_(K))continue;K===">"?ee(A):K==="/"?A.state=T.OPEN_TAG_SLASH:O(h,K)?(A.attribName=K,A.attribValue="",A.state=T.ATTRIB_NAME):G(A,"Invalid attribute name");continue;case T.ATTRIB_NAME:K==="="?A.state=T.ATTRIB_VALUE:K===">"?(G(A,"Attribute without value"),A.attribValue=A.attribName,z(A),ee(A)):_(K)?A.state=T.ATTRIB_NAME_SAW_WHITE:O(g,K)?A.attribName+=K:G(A,"Invalid attribute name");continue;case T.ATTRIB_NAME_SAW_WHITE:if(K==="=")A.state=T.ATTRIB_VALUE;else{if(_(K))continue;G(A,"Attribute without value"),A.tag.attributes[A.attribName]="",A.attribValue="",j(A,"onattribute",{name:A.attribName,value:""}),A.attribName="",K===">"?ee(A):O(h,K)?(A.attribName=K,A.state=T.ATTRIB_NAME):(G(A,"Invalid attribute name"),A.state=T.ATTRIB)}continue;case T.ATTRIB_VALUE:if(_(K))continue;w(K)?(
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}
\`\`\``,IMt=class extends lL{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?i6(e,r):[{op:"replace",path:"",value:r}]}async parsePartialResult(e){return bhe(e[0].text)}async parse(e){return bhe(e)}getFormatInstructions(){return!!(this.tags&&this.tags.length>0)?yhe.replace("{tags}",this.tags?.join(", ")??""):yhe}},hhn=t=>t.split(`
`).map(e=>e.replace(/^\s+/,"")).join(`
`).trim(),NMt=t=>{if(Object.keys(t).length===0)return{};let e={};return t.children.length>0?(e[t.name]=t.children.map(NMt),e):(e[t.name]=t.text??void 0,e)}});var ghn,_O=v(()=>{Do();cY();E6();cL();wMt();TMt();EMt();MMt();z4e();jMt();ghn={};Tt(ghn,{AsymmetricStructuredOutputParser:()=>PMt,BaseCumulativeTransformOutputParser:()=>lL,BaseLLMOutputParser:()=>Mz,BaseOutputParser:()=>_N,BaseTransformOutputParser:()=>vN,BytesOutputParser:()=>vMt,CommaSeparatedListOutputParser:()=>SMt,CustomListOutputParser:()=>CMt,JsonMarkdownStructuredOutputParser:()=>B4e,JsonOutputParser:()=>Tv,ListOutputParser:()=>P6,MarkdownListOutputParser:()=>OMt,NumberedListOutputParser:()=>xMt,OutputParserException:()=>nh,StringOutputParser:()=>ghe,StructuredOutputParser:()=>Kw,XMLOutputParser:()=>IMt,XML_FORMAT_INSTRUCTIONS:()=>yhe,parseJsonMarkdown:()=>lY,parsePartialJson:()=>qU,parseXMLMarkdown:()=>bhe})});var Ww,M6=v(()=>{Yh();Ww=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 yhn,_he,jQ,DQ,H4e,$Q=v(()=>{Do();F$();U$();iO();yhn={};Tt(yhn,{BasePromptValue:()=>_he,ChatPromptValue:()=>DQ,ImagePromptValue:()=>H4e,StringPromptValue:()=>jQ});_he=class extends Wh{},jQ=class extends _he{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 au(this.value)]}},DQ=class extends _he{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 Xu(this.messages)}toChatMessages(){return this.messages}},H4e=class extends _he{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 au({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}}});var wN,LQ=v(()=>{$Q();M6();wN=class extends Ww{async formatPromptValue(t){let e=await this.format(t);return new jQ(e)}}});function J4e(t){return typeof t=="function"}function _hn(t){return A6(t)?"array":typeof t}function V4e(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function DMt(t,e){return t!=null&&typeof t=="object"&&e in t}function vhn(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}function Shn(t,e){return whn.call(t,e)}function xhn(t){return!Shn(Chn,t)}function Thn(t){return String(t).replace(/[&<>"'`=\/]/g,function(r){return Ohn[r]})}function Ahn(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(Phn,2)),!A6(T)||T.length!==2)throw new Error("Invalid tags: "+T);d=new RegExp(V4e(T[0])+"\\s*"),f=new RegExp("\\s*"+V4e(T[1])),p=new RegExp("\\s*"+V4e("}"+T[1]))}m(e||Gw.tags);for(var h=new kQ(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),xhn(
`&&(c(),u="",l=0,r=!1);if(!h.scan(d))break;if(a=!0,y=h.scan(Rhn)||"name",h.scan(Ehn),y==="="?(b=h.scanUntil($Mt),h.scan($Mt),h.scanUntil(f)):y==="{"?(b=h.scanUntil(p),h.scan(Mhn),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 Nhn(Ihn(o))}function Ihn(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 Nhn(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 kQ(t){this.string=t,this.tail=t,this.pos=0}function R6(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 bhn,A6,whn,Chn,Ohn,Ehn,Phn,$Mt,Mhn,Rhn,Gw,FQ,vhe,LMt=v(()=>{bhn=Object.prototype.toString,A6=Array.isArray||function(e){return bhn.call(e)==="[object Array]"};whn=RegExp.prototype.test;Chn=/\S/;Ohn={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};Ehn=/\s*/,Phn=/\s+/,$Mt=/\s*=/,Mhn=/\s*\}/,Rhn=/#|\^|\/|>|\{|&|=|!/;kQ.prototype.eos=function(){return this.tail===""};kQ.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};kQ.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};R6.prototype.push=function(e){return new R6(e,this)};R6.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=DMt(i,a[s])||vhn(i,a[s])),i=i[a[s++]];else i=o.view[e],u=DMt(o.view,e);if(u){n=i;break}o=o.parent}r[e]=n}return J4e(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||Gw.tags).join(":"),i=typeof n<"u",a=i?n.get(o):void 0;return a==null&&(a=Ahn(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 R6?r:new R6(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(A6(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(J4e(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||A6(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=J4e(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)||Gw.escape,i=r.lookup(e[1]);if(i!=null)return typeof i=="number"&&o===Gw.escape?String(i):o(i)};nb.prototype.rawValue=function(e){return e[1]};nb.prototype.getConfigTags=function(e){return A6(e)?e:e&&typeof e=="object"?e.tags:void 0};nb.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!A6(e))return e.escape};Gw={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){FQ.templateCache=t},get templateCache(){return FQ.templateCache}},FQ=new nb;Gw.clearCache=function(){return FQ.clearCache()};Gw.parse=function(e,r){return FQ.parse(e,r)};Gw.render=function(e,r,n,o){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+_hn(e)+'" was given as the first argument for mustache#render(template, view, partials)');return FQ.render(e,r,n,o)};Gw.escape=Thn;Gw.Scanner=kQ;Gw.Context=R6;Gw.Writer=nb;vhe=Gw});function FMt(){vhe.escape=t=>t}var Rz,kMt,I6,K4e,W4e,qQ,G4e,ry,Az,SN,Iz=v(()=>{dY();LMt();Rz=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},kMt=(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=kMt(n[4],o);r.push(...i)}}else r.push({type:"literal",text:n[1]});return r},I6=t=>{FMt();let e=vhe.parse(t);return kMt(e)},K4e=(t,e)=>Rz(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},""),W4e=(t,e)=>(FMt(),vhe.render(t,e)),qQ={"f-string":K4e,mustache:W4e},G4e={"f-string":Rz,mustache:I6},ry=(t,e,r)=>{try{return qQ[e](t,r)}catch(n){throw L$(n,"INVALID_PROMPT_INPUT")}},Az=(t,e)=>G4e[e](t),SN=(t,e,r)=>{if(!(e in qQ)){let n=Object.keys(qQ);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")ry(o.text,e,n);else if(o.type==="image_url"){if(typeof o.image_url=="string")ry(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;ry(i,e,n)}}else throw new Error(`Invalid message template received. ${JSON.stringify(o,null,2)}`)}):ry(t,e,n)}catch(n){throw new Error(`Invalid prompt schema: ${n.message}`)}}});var su,whe=v(()=>{LQ();Iz();su=class BQ extends wN{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))),SN(this.template,this.templateFormat,n)}}static lc_name(){return"PromptTemplate"}_getPromptType(){return"prompt"}async format(r){let n=await this.mergePartialAndUserVariables(r);return ry(this.template,this.templateFormat,n)}static fromExamples(r,n,o,i=`
`,a=""){let s=[a,...r,n].join(i);return new BQ({inputVariables:o,template:s})}static fromTemplate(r,n){let{templateFormat:o="f-string",...i}=n??{},a=new Set;return Az(r,o).forEach(s=>{s.type==="variable"&&a.add(s.name)}),new BQ({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 BQ(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 BQ({inputVariables:r.input_variables,template:r.template,templateFormat:r.template_format})}}});var N6,Z4e=v(()=>{$Q();M6();Iz();N6=class qMt extends Ww{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))),SN([{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 qMt(i)}async format(r){let n={};for(let[s,u]of Object.entries(this.template))typeof u=="string"?n[s]=ry(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 H4e(n)}}});function X4e(t,e){let r=[];for(let n of Object.values(t))if(typeof n=="string")Az(n,e).forEach(o=>{o.type==="variable"&&r.push(o.name)});else if(Array.isArray(n))for(let o of n)typeof o=="string"?Az(o,e).forEach(i=>{i.type==="variable"&&r.push(i.name)}):typeof o=="object"&&r.push(...X4e(o,e));else typeof n=="object"&&n!==null&&r.push(...X4e(n,e));return Array.from(new Set(r))}function Y4e(t,e,r){let n={};for(let[o,i]of Object.entries(t))if(typeof i=="string")n[o]=ry(i,r,e);else if(Array.isArray(i)){let a=[];for(let s of i)typeof s=="string"?a.push(ry(s,r,e)):typeof s=="object"&&a.push(Y4e(s,e,r));n[o]=a}else typeof i=="object"&&i!==null?n[o]=Y4e(i,e,r):n[o]=i;return n}var UQ,Q4e=v(()=>{Yh();Iz();UQ=class extends Lo{constructor(e){let r=e.templateFormat??"f-string",n=X4e(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 Y4e(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:"prompt"})}}});function jhn(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function Dhn(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 $hn(t){return typeof t.formatMessages=="function"}function Lhn(t,e){if($hn(t)||eh(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}},e2e=class extends zQ{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)]}},HQ=class extends Ww{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){let e=await this.formatMessages(t);return new DQ(e)}},t2e=class extends e2e{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 ud(await this.prompt.format(e),this.role)}static fromTemplate(e,r,n){return new this(su.fromTemplate(e,{templateFormat:n?.templateFormat}),r)}};r2e=class extends zQ{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(su.fromTemplate(e,r));let n=[];for(let o of e)if(typeof o=="string")n.push(su.fromTemplate(o,r));else if(o!==null)if(jhn(o)){let i="";typeof o.text=="string"&&(i=o.text??"");let a={...r,additionalContentFields:o};n.push(su.fromTemplate(i,a))}else if(Dhn(o)){let i=o.image_url??"",a,s=[];if(typeof i=="string"){let u;r?.templateFormat==="mustache"?u=I6(i):u=Rz(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 N6({template:i,inputVariables:s,templateFormat:r?.templateFormat,additionalContentFields:o})}else if(typeof i=="object"){if("url"in i){let u;r?.templateFormat==="mustache"?u=I6(i.url):u=Rz(i.url),s=u.flatMap(l=>l.type==="variable"?[l.name]:[])}else s=[];a=new N6({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 UQ({template:o,templateFormat:r?.templateFormat}));return new this({prompt:n,additionalOptions:r})}async format(e){if(this.prompt instanceof wN){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 wN){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 N6){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 UQ){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 r2e{static _messageClass(){return au}static lc_name(){return"HumanMessagePromptTemplate"}},Che=class extends r2e{static _messageClass(){return li}static lc_name(){return"AIMessagePromptTemplate"}},Zw=class extends r2e{static _messageClass(){return th}static lc_name(){return"SystemMessagePromptTemplate"}};pd=class She extends HQ{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 Uc))for(let l of u.inputVariables)n.add(l);let o=this.inputVariables,i=new Set(this.partialVariables?o.concat(Object.keys(this.partialVariables)):o),a=new Set([...i].filter(u=>!n.has(u)));if(a.size>0)throw new Error(`Input variables \`${[...a]}\` are not used in any of the prompt messages.`);let s=new Set([...n].filter(u=>!i.has(u)));if(s.size>0)throw new Error(`Input variables \`${[...s]}\` are used in prompt messages but not in the prompt template.`)}}static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}_getPromptType(){return"chat"}async _parseImagePrompts(r,n){if(typeof r.content=="string")return r;let o=await Promise.all(r.content.map(async i=>{if(i.type!=="image_url")return i;let a="";typeof i.image_url=="string"?a=i.image_url:typeof i.image_url=="object"&&i.image_url!==null&&"url"in i.image_url&&typeof i.image_url.url=="string"&&(a=i.image_url.url);let u=await su.fromTemplate(a,{templateFormat:this.templateFormat}).format(n);return typeof i.image_url=="object"&&i.image_url!==null&&"url"in i.image_url?i.image_url.url=u:i.image_url=u,i}));return r.content=o,r}async formatMessages(r){let n=await this.mergePartialAndUserVariables(r),o=[];for(let i of this.promptMessages)if(i instanceof Uc)o.push(await this._parseImagePrompts(i,n));else{let a;this.templateFormat==="mustache"?a={...n}:a=i.inputVariables.reduce((u,l)=>{if(!(l in n)&&!(Fhn(i)&&i.optional))throw L$(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 She(i)}static fromTemplate(r,n){let o=su.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 She?u.promptMessages:[Lhn(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))),SN(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 n2e(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 ry(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 su.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 n2e({inputVariables:r.input_variables,examplePrompt:o,examples:i,exampleSeparator:r.example_separator,prefix:r.prefix,suffix:r.suffix,templateFormat:r.template_format})}},UMt=class zMt extends HQ{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))),SN(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 ry(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 zMt(i)}}});var VMt,JMt=v(()=>{M6();VQ();VMt=class xhe extends Ww{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=xhe.extractRequiredInputValues(n,i.inputVariables);i instanceof pd?n[o]=await i.formatMessages(a):n[o]=await i.format(a)}return xhe.extractRequiredInputValues(n,this.finalPrompt.inputVariables)}async formatPromptValue(r){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(r))}async format(r){return this.finalPrompt.format(await this.formatPipelinePrompts(r))}async partial(r){let n={...this};return n.inputVariables=this.inputVariables.filter(o=>!(o in r)),n.partialVariables={...this.partialVariables??{},...r},new xhe(n)}serialize(){throw new Error("Not implemented.")}_getPromptType(){return"pipeline"}}});function KMt(t){return typeof t=="object"&&t!=null&&"withStructuredOutput"in t&&typeof t.withStructuredOutput=="function"}function khn(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 WMt,ZMt=v(()=>{Yh();VQ();WMt=class GMt extends pd{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(KMt(r))return super.pipe(r.withStructuredOutput(this.schema));if(khn(r)&&KMt(r.bound))return super.pipe(new Jw({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 GMt.fromMessages(r,{schema:n,method:o})}}});var qhn
`)});function oh(t,e){let r=`atom${++zhn}`,n={toString(){return(Cl.env?Cl.env.MODE:void 0)!=="production"&&this.debugLabel?r+":"+this.debugLabel:r}};return typeof t=="function"?n.read=t:(n.init=t,n.read=Hhn,n.write=Vhn),e&&(n.write=e),n}function Hhn(t){return t(this)}function Vhn(t,e,r){return e(this,typeof r=="function"?r(t(this)):r)}var Cl,zhn,XMt,i2e,a2e,Ehe,u2e,Jhn,Khn,l2e,YMt,The,tRt,QMt,D6,s2e,Whn,Ghn,eRt,dL,rRt,$6,KQ,nRt,c2e=v(()=>{Cl={},zhn=0;XMt=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,i2e=t=>"init"in t,a2e=t=>!!t.write,Ehe=new WeakMap,u2e=t=>{var e;return l2e(t)&&!((e=Ehe.get(t))!=null&&e[1])},Jhn=(t,e)=>{let r=Ehe.get(t);if(r)r[1]=!0,r[0].forEach(n=>n(e));else if((Cl.env?Cl.env.MODE:void 0)!=="production")throw new Error("[Bug] cancelable promise not found")},Khn=t=>{if(Ehe.has(t))return;let e=[new Set,!1];Ehe.set(t,e);let r=()=>{e[1]=!0};t.then(r,r),t.onCancel=n=>{e[0].add(n)}},l2e=t=>typeof t?.then=="function",YMt=t=>"v"in t||"e"in t,The=t=>{if("e"in t)throw t.e;if((Cl.env?Cl.env.MODE:void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},tRt=(t,e,r)=>{r.p.has(t)||(r.p.add(t),e.then(()=>{r.p.delete(t)},()=>{r.p.delete(t)}))},QMt=(t,e,r,n,o)=>{var i;if((Cl.env?Cl.env.MODE:void 0)!=="production"&&n===e)throw new Error("[Bug] atom cannot depend on itself");r.d.set(n,o.n),u2e(r.v)&&tRt(e,r.v,o),(i=o.m)==null||i.t.add(e),t&&Whn(t,n,e)},D6=()=>[new Map,new Map,new Set],s2e=(t,e,r)=>{t[0].has(e)||t[0].set(e,new Set),t[1].set(e,r)},Whn=(t,e,r)=>{let n=t[0].get(e);n&&n.add(r)},Ghn=(t,e)=>t[0].get(e),eRt=(t,e)=>{t[2].add(e)},dL=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},rRt=(...[t,e,r,n])=>{let o;(Cl.env?Cl.env.MODE:void 0)!=="production"&&(o=new Set);let i=(_,w,x)=>{let O="v"in w,E=w.v,T=u2e(w.v)?w.v:null;if(l2e(x)){Khn(x);for(let R of w.d.keys())tRt(_,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&&Jhn(T,x))},a=(_,w,x)=>{var O;let E=t(w);if(YMt(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(XMt(w,B)){let J=t(B);if(!YMt(J))if(i2e(B))i(B,J,B.init);else throw new Error("no atom init");return The(J)}let U=a(_,B,x);try{return The(U)}finally{if(T)QMt(_,w,E,B,U);else{let J=D6();QMt(J,w,E,B,U),p(J,w,E),dL(J)}}},I,j,F={get signal(){return I||(I=new AbortController),I.signal},get setSelf(){return(Cl.env?Cl.env.MODE:void 0)!=="production"&&!a2e(w)&&console.warn("setSelf function cannot be used with read-only atom"),!j&&a2e(w)&&(j=(...B)=>{if((Cl.env?Cl.env.MODE:void 0)!=="production"&&T&&console.warn("setSelf function cannot be called in sync"),!T)return f(w,...B)}),j}};try{let B=e(w,R,F);if(i(w,E,B),l2e(B)){(O=B.onCancel)==null||O.call(B,()=>I?.abort());let U=()=>{if(E.m){let J=D6();p(J,w,E),dL(J)}};B.then(U,U)}return E}catch(B){return delete E.v,E.e=B,++E.n,E}finally{T=!1}},s=_=>The(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=Ghn(_,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[I,j]=R[R.length-1];if(T.has(I)){R.pop();continue}if(E.has(I)){O.push([I,j,j.n]),T.add(I),R.pop();continue}E.add(I);for(let[F,B]of u(_,I,j))I!==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[I,j,F]=O[R],B=!1;for(let U of j.d.keys())if(U!==I&&T.has(U)){B=!0;break}B&&(a(_,I,E),p(_,I,j),F!==j.n&&(s2e(_,I,j),T.add(I))),E.delete(I)}},d=(_,w,...x)=>{let O=!0,E=R=>The(a(_,R)),T=(R,...I)=>{let j=t(R);try{if(XMt(w,R)){if(!i2e(R))throw new Error("atom not writable");let F=j.n,B=I[0];i(R,j,B),p(_,R,j),F!==j.n&&(s2e(_,R,j),c(_,R,j));return}else return d(_,R,...I)}finally{O||dL(_)}};try{return r(w,E,T,...x)}finally{O=!1}},f=(_,...w)=>{let x=D6();try{return d(
<user_custom_instructions>
${t}
</user_custom_instructions>`:e}async function ON(t){let e=jz();if(!t)return H("No UserMemoryManager provided to getSystemPromptWithMemory"),e;let r=await t.getUserMemoryPrompt();return r?`${r}
${e}`:e}function mgn(t){return t.activeModels=vRt(t.activeModels,SO),t.activeEmbeddingModels=vRt(t.activeEmbeddingModels,Dz),t}function Qn(t){return`${t.name}|${t.provider}`}function vRt(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 Kn,fL,jt=v(()=>{CN();kU();Zr();Bt();Kn=$6(),fL=oh(Ds)});function Mo(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 w2e=v(()=>{});var S2e,bm,$z=v(()=>{w2e();yr();jt();S2e=class t{constructor(){this.maxLines=500;this.maxLineChars=8e3;this.buffer=[];this.initialized=!1;this.flushing=!1}static getInstance(){return t.instance||(t.instance=new t),t.instance}getLogPath(){return"copilot/copilot-log.md"}async ensureInitialized(){this.initialized||(this.initialized=!0)}hasVault(){try{return typeof app<"u"&&!!app.vault?.adapter}catch{return!1}}sanitizeForSingleLine(e){if(e instanceof Error){let r=Mo(e,!0);return this.escapeAngleBrackets(this.collapseToSingleLine(r))}if(typeof e=="string")return this.escapeAngleBrackets(this.collapseToSingleLine(e));try{let r=JSON.stringify(e);return this.escapeAngleBrackets(this.collapseToSingleLine(r??String(e)))}catch{return this.escapeAngleBrackets(this.collapseToSingleLine(String(e)))}}collapseToSingleLine(e){let r=e.replace(/[\r\n]+/g,"\\n").replace(/\t/g," ");return r.length<=this.maxLineChars?r:r.slice(0,this.maxLineChars)+` \u2026 [truncated ${r.length-this.maxLineChars} chars]`}async append(e,...r){await this.ensureInitialized();let n=new Date().toISOString(),o=r.map(a=>this.sanitizeForSingleLine(a)),i=`${n} ${e} ${o.join(" ")}`.trim();this.buffer.push(i),this.buffer.length>this.maxLines&&this.buffer.splice(0,this.buffer.length-this.maxLines)}escapeAngleBrackets(e){return e.replace(/</g,"&lt;").replace(/>/g,"&gt;")}async appendMarkdownBlock(e){if(await this.ensureInitialized(),!(!Array.isArray(e)||e.length===0))for(let r of e){let n=typeof r=="string"?r:String(r??"");this.buffer.push(n),this.buffer.length>this.maxLines&&this.buffer.splice(0,this.buffer.length-this.maxLines)}}async flush(){if(this.hasVault()&&!this.flushing){this.flushing=!0;try{let e=this.getLogPath();if(await app.vault.adapter.exists(e)){let r=this.buffer.join(`
`)+(this.buffer.length?`
`:"");await app.vault.adapter.write(e,r)}}catch{}finally{this.flushing=!1}}}async clear(){if(this.buffer=[],!!this.hasVault())try{let e=this.getLogPath();await app.vault.adapter.exists(e)&&await app.vault.adapter.remove(e)}catch{}}sanitizeSettingsForLog(){let e=ce();return this.removeKeysRecursive(e)}removeKeysRecursive(e){if(e==null)return e;if(Array.isArray(e))return e.map(r=>this.removeKeysRecursive(r));if(typeof e=="object"&&e.constructor===Object){let r={},n=e;for(let[o,i]of Object.entries(n))/apiKey$/i.test(o)||/licenseKey$/i.test(o)||/_api_key$/i.test(o)||/_license_key$/i.test(o)||/orgId$/i.test(o)||/instanceName$/i.test(o)||/deploymentName$/i.test(o)||/apiVersion$/i.test(o)||(r[o]=this.removeKeysRecursive(i));return r}return e}async openLogFile(){if(!this.hasVault())return;let e=this.getLogPath(),r=[...this.buffer];try{let o=this.sanitizeSettingsForLog(),a=["","## Settings","```json",...JSON.stringify(o,null,2).split(`
`),"```"];r.push(...a)}catch{}try{let o=r.join(`
`)+(r.length?`
`:""),i=e.includes("/")?e.split("/").slice(0,-1).join("/"):"";i&&await Qh(i),await app.vault.adapter.exists(e)?await app.vault.adapter.write(e,o):await app.vault.create(e,o)}catch{}let n=app.vault.getAbstractFileByPath(e);try{n&&await app.workspace.getLeaf(!0).openFile(n)}catch{}}},bm=S2e.getInstance()});function H(...t){ce().debug&&console.log(...t),bm.append("INFO",...t)}function ue(...t){ce().debug&&console.error(...t),bm.append("ERROR",...t)}function it(...t){ce().debug&&console.warn(...t),bm.append("WARN",...t)}function Ihe(t){bm.appendMarkdownBlock(t)}function CRt(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{}H("Table:",JSON.stringify(t))}var Bt=v(()=>{jt();$z()});var xRt=S((C2e,F6)=>{(function(t,e){typeof C2e=="object"&&typeof F6<"u"?F6.exports=e():typeof define=="function"&&define.amd?define(e):t.moment=e()})(C2e,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 N=[],k,W=C.length;for(k=0;k<W;++k)N.push(P(C[k],k));return N}function d(C,P){for(var N in P)i(P,N)&&(C[N]=P[N]);return i(P,"toString")&&(C.toString=P.toString),i(P,"valueOf")&&(C.valueOf=P.valueOf),C}function f(C,P,N,k){return Dvt(C,P,N,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),N=P.length>>>0,k;for(k=0;k<N;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),N=h.call(P.parsedDateParts,function(W){return W!=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&&N);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 N,k,W,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(N=0;N<le;N++)k=b[N],W=P[k],s(W)||(C[k]=W);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 N=!0;return d(function(){if(e.deprecationHandler!=null&&e.deprecationHandler(null,C),N){var k=[],W,le,Ae,Gr=arguments.length;for(le=0;le<Gr;le++){if(W="",typeof arguments[le]=="object"){W+=`
[`+le+"] ";for(Ae in arguments[0])i(arguments[0],Ae)&&(W+=Ae+": "+arguments[0][Ae]+", ");W=W.slice(0,-2)}else W=arguments[le];k.push(W)}E(C+`
Arguments: `+Array.prototype.slice.call(k).join("")+`
`+new Error().stack),N=!1}return P.apply(this,arguments)},P)}var R={};function I(C,P){e.deprecationHandler!=null&&e.deprecationHandler(C,P),R[C]||(E(P),R[C]=!0)}e.suppressDeprecationWarnings=!1,e.deprecationHandler=null;function j(C){return typeof Function<"u"&&C instanceof Function||Object.prototype.toString.call(C)==="[object Function]"}function F(C){var P,N;for(N in C)i(C,N)&&(P=C[N],j(P)?this[N]=P:this["_"+N]=P);this._config=C,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)}function B(C,P){var N=d({},C),k;for(k in P)i(P,k)&&(o(C[k])&&o(P[k])?(N[k]={},d(N[k],C[k]),d(N[k],P[k])):P[k]!=null?N[k]=P[k]:delete N[k]);for(k in C)i(C,k)&&!i(P,k)&&o(C[k])&&(N[k]=d({},N[k]));return N}function U(C){C!=null&&this.set(C)}var J;Object.keys?J=Object.keys:J=function(C){var P,N=[];for(P in C)i(C,P)&&N.push(P);return N};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 oe(C,P,N){var k=this._calendar[C]||this._calendar.sameElse;return j(k)?k.call(P,N):k}function ne(C,P,N){var k=""+Math.abs(C),W=P-k.length,le=C>=0;return(le?N?"+":"":"-")+Math.pow(10,Math.max(0,W)).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,ee=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,ie={},Z={};function $(C,P,N,k){var W=k;typeof k=="string"&&(W=function(){return this[k]()}),C&&(Z[C]=W),P&&(Z[P[0]]=function(){return ne(W.apply(this,arguments),P[1],P[2])}),N&&(Z[N]=function(){return this.localeData().ordinal(W.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),N,k;for(N=0,k=P.length;N<k;N++)Z[P[N]]?P[N]=Z[P[N]]:P[N]=q(P[N]);return function(W){var le="",Ae;for(Ae=0;Ae<k;Ae++)le+=j(P[Ae])?P[Ae].call(W,C):P[Ae];return le}}function D(C,P){return C.isValid()?(P=A(P,C.localeData()),ie[P]=ie[P]||Y(P),ie[P](C)):C.localeData().invalidDate()}function A(C,P){var N=5;function k(W){return P.longDateFormat(W)||W}for(ee.lastIndex=0;N>=0&&ee.test(C);)C=C.replace(ee,k),ee.lastIndex=0,N-=1;return C}var V={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 K(C){var P=this._longDateFormat[C],N=this._longDateFormat[C.toUpperCase()];return P||!N?P:(this._longDateFormat[C]=N.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 xe="%d",Pe=/\d{1,2}/;function pt(C){return this._ordinal.replace("%d",C)}var Ht={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,N,k){var W=this._relativeTime[N];return j(W)?W(C,P,N,k):W.replace(/%d/i,C)}function Yr(C,P){var N=this._relativeTime[C>0?"future":"past"];return j(N)?N(P):N.replace(/%s/i,P)}var Vt={};function gt(C,P){var N=C.toLowerCase();Vt[N]=Vt[N+"s"]=Vt[P]=C}function Ie(C){return typeof C=="string"?Vt[C]||Vt[C.toLowerCase()]:void 0}function _n(C){var P={},N,k;for(k in C)i(C,k)&&(N=Ie(k),N&&(P[N]=C[k]));return P}var Ct={};function Fe(C,P){Ct[C]=P}function At(C){var P=[],N;for(N in C)i(C,N)&&P.push({unit:N,priority:Ct[N]});return P.sort(function(k,W){return k.priority-W.priority}),P}function ke(C){return C%4===0&&C%100!==0||C%400===0}function ze(C){return C<0?Math.ceil(C)||0:Math.floor(C)}function $e(C){var P=+C,N=0;return P!==0&&isFinite(P)&&(N=ze(P)),N}function Pt(C,P){return function(N){return N!=null?(Wl(this,C,N),e.updateOffset(this,P),this):To(this,C)}}function To(C,P){return C.isValid()?C._d["get"+(C._isUTC?"UTC":"")+P]():NaN}function Wl(C,P,N){C.isValid()&&!isNaN(N)&&(P==="FullYear"&
`),e=e.trim(),e}async function Fz(t,e=!1){let r=app.workspace.getMostRecentLeaf();if(!r){new oy.Notice("No active leaf found.");return}if(r.view instanceof oy.MarkdownView||(r=app.workspace.getLeaf(!1),await r.setViewState({type:"markdown",state:r.view.getState()})),!(r.view instanceof oy.MarkdownView)){new oy.Notice("Failed to open a markdown view.");return}let n=r.view.editor,o=n.getCursor("from"),i=n.getCursor("to"),a=Dhe(t);e?n.replaceRange(a,o,i):n.replaceRange(a,i),new oy.Notice("Message inserted into the active note.")}function $he(t,e){let r;return(...n)=>{clearTimeout(r),r=setTimeout(()=>t(...n),e)}}function Lhe(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 FRt(){try{return{version:(await(0,oy.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 tee(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 Cgn(t){return typeof t=="string"?t.startsWith("gpt-5"):(t.modelName||t.model||"").startsWith("gpt-5")}function H6(t){let e=typeof t=="string"?t:t.modelName||t.model||"",r=tee(e),n=Cgn(e),o=e.startsWith("claude-3-7-sonnet")||e.startsWith("claude-sonnet-4");return{isOSeries:r,isGPT5:n,isThinkingEnabled:o}}function kz(t,e="system"){return tee(t)?"human":e}function E2e(){let t=["3rd party (openai-format)","ollama","lm-studio","azure openai","copilot-plus","copilot-plus-jina"];return Object.entries(TN).filter(([e])=>!t.includes(e)).map(([e])=>e)}function V6(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=!!E2e().find(i=>i===t.provider),n=EN[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 Fhe(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>e.text).join(""):String(t||"")}function qz(t){let r=Fhe(t).replace(/<think>[\s\S]*?<\/think>/g,"");return r=r.replace(/<think>[\s\S]*$/g,""),r.trim()}function J6(t){return Fhe(t).replace(/<errorChunk>[\s\S]*?<\/errorChunk>/g,"").trim()}function kRt(){return crypto.randomUUID()}async function ih(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 khe(t,e,r="Operation"){let{TimeoutError:n}=await Promise.resolve().then(()=>(Yw(),ORt)),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 P2e(){let t=app.workspace.getActiveViewOfType(oy.MarkdownView);return t?t.getState().source===!0:!0}function ree(t){return new TextEncoder().encode(t).length}function M2e(t,e){if(e<=0)return"";let r=new TextEncoder;if(r.encode(t).length<=e)return t;let o=0,i=t.length,a="";for(;o<=i;){let s=Math.floor((o+i)/2),u=t.substring(0,s);r.encode(u).length<=e?(a=u,o=s+1):i=s-1}return a}async function qRt(t,e=!0){let r=null;app.workspace.iterateAllLeaves(n=>{if(n.view.getViewType()==="markdown"||n.view.getViewType()==="pdf"||n.view.getViewType()==="canvas"){let o=n.view.file;o&&o.path===t.path&&(r=n)}}),r&&e?app.workspace.setActiveLeaf(r,{focus:!0}):r||await app.workspace.getLeaf("tab").openFile(t)}var TRt,oy,x2e,QQ,ggn,ygn,MRt,eg,bgn,vgn,yr=v(()=>{Hc();Zr();Bt();TRt=L(xRt()),oy=require("obsidian");w2e();x2e={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}`};QQ=(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})};ggn=t=>t.last?.modelName||t.last?.model,ygn=t=>t.last?.retriever!==void 0,MRt=t=>ggn(t)||ygn(t),eg=(t,e="local")=>{let r=(0,TRt.default)(t);return e==="utc"&&r.utc(),{fileName:r.format("YYYYMMDD_HHmmss"),display:r.format("YYYY/MM/DD HH:mm:ss"),epoch:r.valueOf()}};bgn=["md","pdf","canvas"];vgn=/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|shorts\/)|youtu\.be\/)([^\s&]+)/});var K6,R2e,nee,Hc=v(()=>{_O();Ev();Ov();o2e();yr();K6=class K6{static createNewLLMChain(e){let{llm:r,memory:n,prompt:o,abortController:i}=e,a=r.withConfig({signal:i?.signal}),s=Sl.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=su.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=su.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=Sl.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 ghe,g=>{let y=qz(g),b=J6(y);return n&&console.log("Standalone Question: ",b),b}]),p=async g=>(r(g),JQ(g)),m=Sl.from([{context:i.pipe(p),question:new wu,system_message:()=>a},c,o]);return f.pipe(m)}};K6.instances=new Map;R2e=K6,nee=R2e});var oee=v(()=>{});var A2e,Bz,Cc,Zs,TO,wO,xgn,Ogn,Tgn,v2e,SRt,URt,iee,s_,aee,Uz,see,I2e,uee,N2e,zz,j2e,D2e,W6,EO,PN,iy,OO,gL,SO,pL,Dz,O2e,TN,EN,zRt,ZQ,Gn,qhe,G6,Ds,eS,Zr=v(()=>{kU();Hc();oee();A2e="https://api.brevilabs.com/v1",Bz="https://models.brevilabs.com/v1",Cc="copilot-chat-view",Zs="user",TO="ai",wO="copilot",xgn=`${wO}/copilot-conversations`,Ogn=`${wO}/copilot-custom-prompts`,Tgn=`${wO}/memory`,v2e=wO,SRt=`You are Obsidian Copilot, a helpful assistant that integrates AI to Obsidian note-taking.
1. Never mention that you do not have access to something. Always rely on the user provided context.
2. Always answer to the best of your knowledge. If you are unsure about something, say so and ask the user to provide more context.
3. If the user mentions "note", it most likely means an Obsidian note in the vault, not the generic meaning of a note.
4. If the user mentions "@vault", it means the user wants you to search the Obsidian vault for information relevant to the query. The search results will be provided to you in the context along with the user query, read it carefully and answer the question based on the information provided. If there's no relevant information in the vault, just say so.
5. If the user mentions any other tool with the @ symbol, check the context for their results. If nothing is found, just ignore the @ symbol in the query.
6. Always use $'s instead of \\[ etc. for LaTeX equations.
7. When showing note titles, use [[title]] format and do not wrap them in \` \`.
8. When showing **Obsidian internal** image links, use ![[link]] format and do not wrap them in \` \`.
9. When showing **web** image links, use ![link](url) format and do not wrap them in \` \`.
10. When generating a table, format as github markdown tables, however, for table headings, immediately add ' |' after the table heading.
11. Always respond in the language of the user's query.
12. Do NOT mention the additional context provided such as getCurrentTime and getTimeRangeMs if it's irrelevant to the user message.
13. If the user mentions "tags", it most likely means tags in Obsidian note properties.
14. YouTube URLs: If the user provides YouTube URLs in their message, transcriptions will be automatically fetched and provided to you. You don't need to do anything special - just use the transcription content if available.
15. For markdown lists, always use '- ' (hyphen followed by exactly one space) for bullet points, with no leading spaces before the hyphen. Never use '*' (asterisk) for bullets.`,URt=`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.
`,iee="note_context",s_="selected_text",aee="variable",Uz="variable_note",see="embedded_pdf",I2e="embedded_note",uee="dataview_block",N2e="retrieved_document",zz=6e3,j2e=.4,D2e=448e3,W6=3e4,EO={DEFAULT:"",READING_FILES:"Reading files",SEARCHING_WEB:"Searching the web",READING_FILE_TREE:"Reading file tree"},PN={SETTINGS:"settings",EXPIRED_MODAL:"expired_modal",CHAT_MODE_SELECT:"chat_mode_select",MODE_SELECT_TOOLTIP:"mode_select_tooltip"},iy={MAX_TOKENS:6e3,TEMPERATURE:.1,REASONING_EFFORT:"low",VERBOSITY:"medium"},OO=(g=>(g.OPENROUTERAI="openrouterai",g.OPENAI="openai",g.OPENAI_FORMAT="3rd party (openai-format)",g.ANTHROPIC="anthropic",g.GOOGLE="google",g.XAI="xai",g.AMAZON_BEDROCK="amazon-bedrock",g.AZURE_OPENAI="azure openai",g.GROQ="groq",g.OLLAMA="ollama",g.LM_STUDIO="lm-studio",g.COPILOT_PLUS="copilot-plus",g.MISTRAL="mistralai",g.DEEPSEEK="deepseek",g.COHEREAI="cohereai",g.SILICONFLOW="siliconflow",g))(OO||{}),gL={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:"grok-4-fast",provider:"xai",enabled:!0,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"x-ai/grok-4-fast",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-5",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"gpt-5-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"gpt-4.1",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-4.1-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"claude-sonnet-4-20250514",provider:"anthropic",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-2.5-flash",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gemini-2.5-flash-lite",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gemini-2.5-pro",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"azure-openai",provider:"azure openai",enabled:!0,isBuiltIn:!0},{name:"deepseek-chat",provider:"deepseek",enabled:!0,isBuiltIn:!0},{name:"deepseek-reasoner",provider:"deepseek",enabled:!0,isBuiltIn:!0,capabilities:["reasoning"]},{name:"deepseek-ai/DeepSeek-V3",provider:"siliconflow",enabled:!1,isBuiltIn:!1,baseUrl:"https://api.siliconflow.com/v1"},{name:"deepseek-ai/DeepSeek-R1",provider:"siliconflow",enabled:!1,isBuiltIn:!1,baseUrl:"https://api.siliconflow.com/v1",capabilities:["reasoning"]}],pL=(c=>(c.OPENAI="openai",c.COHEREAI="cohereai",c.GOOGLE="google",c.AZURE_OPENAI="azure openai",c.OLLAMA="ollama",c.LM_STUDIO="lm-studio",c.OPENAI_FORMAT="3rd party (openai-format)",c.COPILOT_PLUS="copilot-plus",c.COPILOT_PLUS_JINA="copilot-plus-jina",c.SILICONFLOW="siliconflow",c))(pL||{}),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:"cop
`+gHe+t}var yHe=!1;function bHe(t,e){if(!t||yHe)return"";yHe=!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{yHe=!1,Error.prepareStackTrace=r}return(t=t?t.displayName||t.name:"")?Tee(t):""}function _yn(t){switch(t.tag){case 5:return Tee(t.type);case 16:return Tee("Lazy");case 13:return Tee("Suspense");case 19:return Tee("SuspenseList");case 0:case 2:case 15:return t=bHe(t.type,!1),t;case 11:return t=bHe(t.type.render,!1),t;case 1:return t=bHe(t.type,!0),t;default:return""}}function UHe(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 n5:return"Fragment";case r5:return"Portal";case kHe:return"Profiler";case NVe:return"StrictMode";case qHe:return"Suspense";case BHe:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case LIt:return(t.displayName||"Context")+".Consumer";case $It:return(t._context.displayName||"Context")+".Provider";case jVe:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case DVe:return e=t.displayName||null,e!==null?e:UHe(t.type)||"Memo";case CL:e=t._payload,t=t._init;try{return UHe(t(e))}catch{}}return null}function vyn(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 UHe(e);case 8:return e===NVe?"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 LL(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function kIt(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function wyn(t){var e=kIt(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 tge(t){t._valueTracker||(t._valueTracker=wyn(t))}function qIt(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var r=e.getValue(),n="";return t&&(n=kIt(t)?t.checked?"true":"false":t.value),t=n,t!==r?(e.setValue(t),!0):!1}function Mge(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 zHe(t,e){var r=e.checked;return rc({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??t._wrapperState.initialChecked})}function AAt(t,e){var r=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;r=LL(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 BIt(t,e){e=e.checked,e!=null&&IVe(t,"checked",e,!1)}function HHe(t,e){BIt(t,e);var r=LL(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")?VHe(t,e.type,r):e.hasOwnProperty("defaultValue")&&VHe(t,e.type,LL(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}fun
`).replace(Mbn,"")}function pge(t,e,r){if(e=rIt(e),rIt(t)!==e&&r)throw Error(et(425))}function Lge(){}var iVe=null,aVe=null;function sVe(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 uVe=typeof setTimeout=="function"?setTimeout:void 0,Rbn=typeof clearTimeout=="function"?clearTimeout:void 0,nIt=typeof Promise=="function"?Promise:void 0,Abn=typeof queueMicrotask=="function"?queueMicrotask:typeof nIt<"u"?function(t){return nIt.resolve(null).then(t).catch(Ibn)}:uVe;function Ibn(t){setTimeout(function(){throw t})}function PHe(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),Hee(e);return}n--}else r!=="$"&&r!=="$?"&&r!=="$!"||n++;r=o}while(r);Hee(e)}function IL(t){for(;t!=null;t=t.nextSibling){var e=t.nodeType;if(e===1||e===3)break;if(e===8){if(e=t.data,e==="$"||e==="$!"||e==="$?")break;if(e==="/$")return null}}return t}function oIt(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 P5=Math.random().toString(36).slice(2),jO="__reactFiber$"+P5,Gee="__reactProps$"+P5,LN="__reactContainer$"+P5,lVe="__reactEvents$"+P5,Nbn="__reactListeners$"+P5,jbn="__reactHandles$"+P5;function Qz(t){var e=t[jO];if(e)return e;for(var r=t.parentNode;r;){if(e=r[LN]||r[jO]){if(r=e.alternate,e.child!==null||r!==null&&r.child!==null)for(t=oIt(t);t!==null;){if(r=t[jO])return r;t=oIt(t)}return e}t=r,r=t.parentNode}return null}function ote(t){return t=t[jO]||t[LN],!t||t.tag!==5&&t.tag!==6&&t.tag!==13&&t.tag!==3?null:t}function s5(t){if(t.tag===5||t.tag===6)return t.stateNode;throw Error(et(33))}function nye(t){return t[Gee]||null}var cVe=[],u5=-1;function qL(t){return{current:t}}function nl(t){0>u5||(t.current=cVe[u5],cVe[u5]=null,u5--)}function Du(t,e){u5++,cVe[u5]=t.current,t.current=e}var FL={},cy=qL(FL),f_=qL(!1),o4=FL;function w5(t,e){var r=t.type.contextTypes;if(!r)return FL;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 Fge(){nl(f_),nl(cy)}function iIt(t,e,r){if(cy.current!==FL)throw Error(et(168));Du(cy,e),Du(f_,r)}function MNt(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(et(108,vyn(t)||"Unknown",o));return rc({},r,n)}function kge(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||FL,o4=cy.current,Du(cy,t),Du(f_,f_.current),!0}function aIt(t,e,r){var n=t.stateNode;if(!n)throw Error(et(169));r?(t=MNt(t,e,o4),n.__reactInternalMemoizedMergedChildContext=t,nl(f_),nl(cy),Du(cy,t)):nl(f_),Du(f_,r)}var IN=null,oye=!1,MHe=!1;function RNt(t){IN===null?IN=[t]:IN.push(t)}function Dbn(t){oye=!0,RNt(t)}function BL(){if(!MHe&&IN!==null){MHe=!0;var t=0,e=Xs;try{var r=IN;for(Xs=1;t<r.length;t++){var n=r[t];do n=n(!0);while(n!==null)}IN=null,oye=!1}catch(o){throw IN!==null&&(IN=IN.slice(t+1)),tNt(LVe,BL),o}finally{Xs=e,MHe=!1}}return null}var l5=[],c5=0,qge=null,Bge=0,oS=[],iS=0,i4=null,NN=1,jN="";function Xz(t,e){l5[c5++]=Bge,l5[c5++]=qge,qge=t,Bge=e}function ANt(t,e,r){oS[iS++]=NN,oS[iS++]=jN,oS[iS++]=i4,i4=t;var n=NN;t=jN;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,NN=1<<32-oC(e)+o|r<<o|n,jN=i+t}else NN=1<<i|r<<o|n,jN=t}function JVe(t){t.return!==null&&(Xz(t,1),ANt(t,1,0))}function KVe(t){for(;t===qge;)qge=l5[--c5],l5[c5]=null,Bge=l5[--c5],l5[c5]=null;for(;t===i4;)i4=oS[--iS],oS[iS]=null,jN=oS[--iS],oS[iS]=null,NN=oS[--iS],oS[iS]=null}var Av=null,Rv=null,xl=!1,nC=null;function INt(t,e){var r=aS(5,n
Error generating stack: `+i.message+`
`+i.stack}return{value:t,source:e,stack:o,digest:null}}function jHe(t,e,r){return{value:t,source:null,stack:r??null,digest:e??null}}function gVe(t,e){try{console.error(e.value)}catch(r){setTimeout(function(){throw r})}}var Hbn=typeof WeakMap=="function"?WeakMap:Map;function a1t(t,e,r){r=DN(-1,r),r.tag=3,r.payload={element:null};var n=e.value;return r.callback=function(){Gge||(Gge=!0,TVe=n),gVe(t,e)},r}function s1t(t,e,r){r=DN(-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(){gVe(t,e)}}var i=t.stateNode;return i!==null&&typeof i.componentDidCatch=="function"&&(r.callback=function(){gVe(t,e),typeof n!="function"&&(jL===null?jL=new Set([this]):jL.add(this));var a=e.stack;this.componentDidCatch(e.value,{componentStack:a!==null?a:""})}),r}function gIt(t,e,r){var n=t.pingCache;if(n===null){n=t.pingCache=new Hbn;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=o_n.bind(null,t,e,r),e.then(t,t))}function yIt(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 bIt(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=DN(-1,1),e.tag=2,NL(r,e,1))),r.lanes|=1),t):(t.flags|=65536,t.lanes=o,t)}var Vbn=qN.ReactCurrentOwner,d_=!1;function sb(t,e,r,n){e.child=t===null?kNt(e,null,r,n):C5(e,t.child,r,n)}function _It(t,e,r,n,o){r=r.render;var i=e.ref;return b5(e,o),n=oJe(t,e,r,n,i,o),r=iJe(),t!==null&&!d_?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,kN(t,e,o)):(xl&&r&&JVe(e),e.flags|=1,sb(t,e,n,o),e.child)}function vIt(t,e,r,n,o){if(t===null){var i=r.type;return typeof i=="function"&&!hJe(i)&&i.defaultProps===void 0&&r.compare===null&&r.defaultProps===void 0?(e.tag=15,e.type=i,u1t(t,e,i,n,o)):(t=Pge(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:Jee,r(a,n)&&t.ref===e.ref)return kN(t,e,o)}return e.flags|=1,t=$L(i,n),t.ref=e.ref,t.return=e,e.child=t}function u1t(t,e,r,n,o){if(t!==null){var i=t.memoizedProps;if(Jee(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,kN(t,e,o)}return yVe(t,e,r,n,o)}function l1t(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},Du(p5,Mv),Mv|=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,Du(p5,Mv),Mv|=t,null;e.memoizedState={baseLanes:0,cachePool:null,transitions:null},n=i!==null?i.baseLanes:r,Du(p5,Mv),Mv|=n}else i!==null?(n=i.baseLanes|r,e.memoizedState=null):n=r,Du(p5,Mv),Mv|=n;return sb(t,e,o,r),e.child}function c1t(t,e){var r=e.ref;(t===null&&r!==null||t!==null&&t.ref!==r)&&(e.flags|=512,e.flags|=2097152)}function yVe(t,e,r,n,o){var i=p_(r)?o4:cy.current;return i=w5(e,i),b5(e,o),r=oJe(t,e,r,n,i,o),n=iJe(),t!==null&&!d_?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,kN(t,e,o)):(xl&&n&&JVe(e),e.flags|=1,sb(t,e,r,o),e.child)}function wIt(t,e,r,n,o){if(p_(r)){var i=!0;kge(e)}else i=!1;if(b5(e,o),e.stateNode===null)Oge(t,e),LNt(e,r,n),hVe(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=uS(l):(l=p_(r)?o4:cy.current,l=w5(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)&&fIt(e,a,n,l),xL=!1;var f=e.memoizedState;a.state=f,Hge(e,n,a,o),u=e.memoizedState,s!==n||f!==u||f_.current||xL?(typeof c=="function"&&(mVe(e,r,c,n),u=e.memoizedState),(s=xL||dIt(e,r,s,n,f,u,l))?(d||typeof a.UNSAFE_componentWillMount
`)}});var Bzt=S(mbe=>{"use strict";Object.defineProperty(mbe,"__esModule",{value:!0});mbe.CohereTimeoutError=void 0;var FJe=class t extends Error{constructor(e){super(e),Object.setPrototypeOf(this,t.prototype)}};mbe.CohereTimeoutError=FJe});var Oc=S(q5=>{"use strict";Object.defineProperty(q5,"__esModule",{value:!0});q5.CohereTimeoutError=q5.CohereError=void 0;var zvn=qzt();Object.defineProperty(q5,"CohereError",{enumerable:!0,get:function(){return zvn.CohereError}});var Hvn=Bzt();Object.defineProperty(q5,"CohereTimeoutError",{enumerable:!0,get:function(){return Hvn.CohereTimeoutError}})});var Uzt=S(BO=>{"use strict";var Vvn=BO&&BO.__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]}),Jvn=BO&&BO.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Kvn=BO&&BO.__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"&&Vvn(r,e,n[o]);return Jvn(r,e),r}}();Object.defineProperty(BO,"__esModule",{value:!0});BO.BadRequestError=void 0;var Wvn=Kvn(Oc()),kJe=class t extends Wvn.CohereError{constructor(e,r){super({message:"BadRequestError",statusCode:400,body:e,rawResponse:r}),Object.setPrototypeOf(this,t.prototype)}};BO.BadRequestError=kJe});var zzt=S(UO=>{"use strict";var Gvn=UO&&UO.__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]}),Zvn=UO&&UO.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Xvn=UO&&UO.__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"&&Gvn(r,e,n[o]);return Zvn(r,e),r}}();Object.defineProperty(UO,"__esModule",{value:!0});UO.UnauthorizedError=void 0;var Yvn=Xvn(Oc()),qJe=class t extends Yvn.CohereError{constructor(e,r){super({message:"UnauthorizedError",statusCode:401,body:e,rawResponse:r}),Object.setPrototypeOf(this,t.prototype)}};UO.UnauthorizedError=qJe});var Hzt=S(zO=>{"use strict";var Qvn=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]}),ewn=zO&&zO.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),twn=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"&&Qvn(r,e,n[o]);return ewn(r,e),r}}();Object.defineProperty(zO,"__esModule",{value:!0});zO.ForbiddenError=void 0;var rwn=twn(Oc()),BJe=class t extends rwn.CohereError{constructor(e,r){super({message:"ForbiddenError",statusCode:403,body:e,rawResponse:r}),Object.setPrototypeOf(this,t.prototype)}};zO.ForbiddenError=BJe});var Vzt=S(HO=>{"use strict";var nwn=HO&&HO.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(
`));return r(o)}});var _Jt,r0n,n0n,o0n,i0n,a0n,vJt=v(()=>{_Jt=async t=>{let e=t?.Bucket||"";if(typeof t.Bucket=="string"&&(t.Bucket=e.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),a0n(e)){if(t.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!i0n(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},r0n=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,n0n=/(\d+\.){3}\d+/,o0n=/\.\./,i0n=t=>r0n.test(t)&&!n0n.test(t)&&!o0n.test(t),a0n=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 wJt=v(()=>{vJt()});var SJt,CJt=v(()=>{SJt=(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 xJt,OJt=v(()=>{xJt=async t=>{}});function TJt(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 EJt=v(()=>{});var oF,r_e=v(()=>{EJt();oF=t=>{if(typeof t=="string")return oF(new URL(t));let{hostname:e,pathname:r,port:n,protocol:o,search:i}=t,a;return i&&(a=TJt(i)),{hostname:e,port:n?parseInt(n):void 0,protocol:o,path:r,query:a}}});var n_e,o_e=v(()=>{r_e();n_e=t=>typeof t=="object"?"url"in t?oF(t.url):t:oF(t)});var PJt,s0n,j3e=v(()=>{wJt();CJt();OJt();o_e();PJt=async(t,e,r,n)=>{if(!r.endpoint){let a=await xJt(r.serviceId||"");a&&(r.endpoint=()=>Promise.resolve(n_e(a)))}let o=await s0n(t,e,r);if(typeof r.endpointProvider!="function")throw new Error("config.endpointProvider is not set.");return r.endpointProvider(o,n)},s0n=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 SJt(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 _Jt(n),n}});var MJt=v(()=>{j3e();o_e()});var RJt,D3e=v(()=>{pC();j3e();RJt=({config:t,instructions:e})=>(r,n)=>async o=>{let i=await PJt(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=tT(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 AJt,$3e=v(()=>{AJt=(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 IJt,L3e=v(()=>{IJt=(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 xr(t,e,r){return{applyToStack:n=>{n.add(AJt(t,r),u0n),n.add(IJt(t,e),Jte)}}}var u0n,Jte,NJt=v(()=>{$3e();L3e();u0n={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},Jte={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});var Ji=v(()=>{$3e();NJt();L3e()});var F3e,Or,jJt=v(()=>{Ji();D3e();F3e={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:Jte.name},Or=(t,e)=>({applyToStack:r=>{r.addRelativeTo(RJt({config:t,instructions:e}),F3e)}})});var i_e,DJt=v(()=>{pC();o_e();i_e=t=>{let e=t.tls??!0,{endpoint:r}=t,n=r!=null?async()=>n_e(await py(r)()):void 0;return{...t,endpoint:n,tls:e,isCustomEndpoint:!!r,useDualstackEndpoint:py(t.useDualstackEndpoint??!1),useFipsEndpoint:py(t.useFipsEndpoint??!1)}}});var $Jt=v(()=>{});var Li=v(()=>{MJt();D3e();jJt();DJt();$Jt()});var l0n,a_e,LJt=v(()=>{Li();t_e();l0n={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:F3e.name},a_e=(t,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:r})=>({applyToStack:n=>{n.addRelativeTo(N3e(t,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:r}),l0n)}})});var y3i,FJt=v(()=>{Ji();t_e();y3i={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:Jte.name}});var kJt=v(()=>{t_e();LJt();FJt()});var qJt=v(()=>{});var BJt=v(()=>{qJt()});var UJt=v(()=>{hd()});var zJt=v(()=>{});var HJt=v(()=>{});function c0n(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return{...e,[r]:Array.isArray(n)?[...n]:n}},{})}var T4,VJt=v(()=>{T4=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=c0n(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 JJt=v(()=>{});var KJt=v(()=>{});var WJt=v(()=>{});var Kte=v(()=>{BJt();UJt();zJt();HJt();VJt();JJt();KJt();WJt()});var d0n,f0n,GJt,k3e=v(()=>{Kte();hd();pC();d0n=t=>e=>{throw e},f0n=(t,e)=>{},GJt=t=>(e,r)=>async n=>{if(!T4.isInstance(n.request))return e(n);let i=tT(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||d0n)(a));return(u.successHandler||f0n)(l.response,a),l}});var mC,rT,Wte,s_e=v(()=>{(function(t){t.STANDARD="standard",t.ADAPTIVE="adaptive"})(mC||(mC={}));rT=3,Wte=mC.STANDARD});var ZJt,XJt,YJt,QJt,e3t=v(()=>{ZJt=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],XJt=["TimeoutError","RequestTimeout","RequestTimeoutException"],YJt=[500,502,503,504],QJt=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"]});var p0n,J5,u_e,t3t,Gte=v(()=>{e3t();p0n=t=>t.$metadata?.clockSkewCorrected,J5=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 lF(i);if(o==="hex")return a6t(i);if(o===void 0||o==="utf8"||o==="utf-8")return g_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(u6t);if(e=!0,l6t(t))return n(t);if(o6e(t))return t;throw new Error(`Cannot transform payload to web stream, got ${t}`)}})},l6t=t=>typeof Blob=="function"&&t instanceof Blob});var f6t=v(()=>{});var p6t=v(()=>{});var a6e=v(()=>{t6e();B3t();d6t();f6t();p6t();i6e()});var dF,m6t=v(()=>{a6e();dF=async(t=new Uint8Array,e)=>{if(t instanceof Uint8Array)return e1.mutate(t);if(!t)return e1.mutate(new Uint8Array);let r=e.streamCollector(t);return e1.mutate(await r)}});var gr,s6e,h6t=v(()=>{W3e();hd();gr=class{constructor(){this.middlewareStack=Z5()}static classBuilder(){return new s6e}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,[H5]:{commandInstance:this,...l},...c},{requestHandler:h}=r;return f.resolve(g=>h.handle(g.request,n||{}),m)}},s6e=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 gr{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 b_e,g6t=v(()=>{b_e="***SensitiveInformation***"});var __e,y6t=v(()=>{__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 I4,v0n,b6t,w0n,_6t,v6t,w6t,u6e,S0n,Q5,ei,S6t,C6t,C0n,ere,tre,l6e,x6t,O6t,T6t,c6e=v(()=>{I4=t=>{if(t!=null){if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return String(e)!==String(t)&&T6t.warn(O6t(`Expected number but observed string: ${t}`)),e}if(typeof t=="number")return t;throw new TypeError(`Expected number, got ${typeof t}: ${t}`)}},v0n=Math.ceil(34028234663852886e22),b6t=t=>{let e=I4(t);if(e!==void 0&&!Number.isNaN(e)&&e!==1/0&&e!==-1/0&&Math.abs(e)>v0n)throw new TypeError(`Expected 32-bit float, got ${t}`);return e},w0n=t=>{if(t!=null){if(Number.isInteger(t)&&!Number.isNaN(t))return t;throw new TypeError(`Expected integer, got ${typeof t}: ${t}`)}},_6t=t=>u6e(t,32),v6t=t=>u6e(
`).slice(0,5).filter(e=>!e.includes("stackTraceWarning")).join(`
`),T6t={warn:console.warn}});var x0n,O0n,E6t,T0n,P6t,dWi,fWi,pWi,v_e,M6t,mWi,E0n,P0n,M0n,N4,R0n,A0n,d6e,R6t=v(()=>{c6e();x0n=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],O0n=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),E6t=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=O0n.exec(t);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");let[r,n,o,i,a,s,u,l]=e,c=l6e(d6e(n)),d=N4(o,"month",1,12),f=N4(i,"day",1,31);return M6t(c,d,f,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l})},T0n=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),P6t=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=T0n.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=l6e(d6e(n)),f=N4(o,"month",1,12),p=N4(i,"day",1,31),m=M6t(d,f,p,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l});return c.toUpperCase()!="Z"&&m.setTime(m.getTime()-A0n(c)),m},dWi=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$/),fWi=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$/),pWi=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})$/),v_e=t=>{if(t==null)return;let e;if(typeof t=="number")e=t;else if(typeof t=="string")e=S6t(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))},M6t=(t,e,r,n)=>{let o=e-1;return P0n(t,o,r),new Date(Date.UTC(t,o,r,N4(n.hours,"hour",0,23),N4(n.minutes,"minute",0,59),N4(n.seconds,"seconds",0,60),R0n(n.fractionalMilliseconds)))},mWi=50*365*24*60*60*1e3,E0n=[31,28,31,30,31,30,31,31,30,31,30,31],P0n=(t,e,r)=>{let n=E0n[e];if(e===1&&M0n(t)&&(n=29),r>n)throw new TypeError(`Invalid day for ${x0n[e]} in ${t}: ${r}`)},M0n=t=>t%4===0&&(t%100!==0||t%400===0),N4=(t,e,r,n)=>{let o=x6t(d6e(t));if(o<r||o>n)throw new TypeError(`${e} must be between ${r} and ${n}, inclusive`);return o},R0n=t=>t==null?0:C6t("0."+t)*1e3,A0n=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},d6e=t=>{let e=0;for(;e<t.length-1&&t.charAt(e)==="0";)e++;return e===0?t:t.slice(e)}});var eK,nc,f6e=v(()=>{eK=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}},nc=(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 I0n,w_e,N0n,A6t=v(()=>{f6e();I0n=({output:t,parsedBody:e,exceptionCtor:r,errorCode:n})=>{let o=N0n(t),i=o.httpStatusCode?o.httpStatusCode+"":void 0,a=new r({name:e?.code||e?.Code||n||i||"UnknownError",$fault:"client",$metadata:o});throw nc(a,e)},w_e=t=>({output:e,parsedBody:r,errorCode:n})=>{I0n({output:e,parsedBody:r,exceptionCtor:t,errorCode:n})},N0n=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 S_e,I6t=v(()=>{S_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}=k_e(r),u=new this.sha256(await this.getSigningKey(i,a,s,o));return u.update(mF(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=F_e(e),{longDate:c,shortDate:d}=k_e(r),f=D_e(d,u,a??this.service);l.headers[M6e]=c,s.sessionToken&&(l.headers[eKt]=s.sessionToken);let p=await lre(l,this.sha256);!hKt(ure,l.headers)&&this.applyChecksum&&(l.headers[ure]=p);let m=$_e(l,o,n),h=await this.getSignature(c,f,this.getSigningKey(s,u,d,a),this.createCanonicalRequest(l,m,p));return l.headers[P6e]=`${N_e} Credential=${s.accessKeyId}/${f}, SignedHeaders=${_Kt(m)}, Signature=${h}`,l}createCanonicalRequest(e,r,n){let o=Object.keys(r).sort();return`${e.method}
${this.getCanonicalPath(e)}
${j6e(e)}
${o.map(i=>`${i}:${r[i]}`).join(`
`)}
${o.join(";")}
${n}`}async createStringToSign(e,r,n){let o=new this.sha256;o.update(mF(n));let i=await o.digest();return`${N_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 gS(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(mF(i)),hC(await a.digest())}getSigningKey(e,r,n,o){return lKt(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")}},k_e=t=>{let e=yKt(t).replace(/[\-:]/g,"");return{longDate:e,shortDate:e.slice(0,8)}},_Kt=t=>Object.keys(t).sort().join(";")});var wKt=v(()=>{vKt();N6e();D6e();$6e();k6e();q6e();I6e()});var q_e,SKt=v(()=>{fF();wKt();q_e=t=>{let e;t.credentials&&(e=s5t(t.credentials,a5t,y6e)),e||(t.credentialDefaultProvider?e=nK(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=nK(t.signer):t.regionInfoProvider?i=()=>nK(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||cre;return new d(c)}):i=async a=>{a=Object.assign({},{name:"sigv4",signingName:t.signingName||t.defaultSigningName,signingRegion:await nK(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||cre;return new c(l)},{...t,systemClockOffset:n,signingEscapePath:r,credentials:e,signer:i}}});var CKt=v(()=>{U5t();z5t();SKt()});var xKt=v(()=>{CKt()});var OKt=v(()=>{});var TKt=v(()=>{tn()});var B_e,B6e=v(()=>{tn();B_e=(t,e)=>dF(t,e).then(r=>e.utf8Encoder(r))});var Kc,EKt,PKt,MKt=v(()=>{B6e();Kc=(t,e)=>B_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{}}),EKt=async(t,e)=>{let r=await Kc(t,e);return r.message=r.message??r.Message,r},PKt=(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 U_e=S(t1=>{"use strict";var RKt=":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",Q0n=RKt+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",AKt="["+RKt+"]["+Q0n+"]*",eCn=new RegExp("^"+AKt+"$"),tCn=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},rCn=function(t){let e=eCn.exec(t);return!(e===null||typeof e>"u")};t1.isExist=function(t){return typeof t<"u"};t1.isEmptyObject=function(t){return Object.keys(t).length===0};t1.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]]}};t1.getValue=function(t){return t1.isExist(t)?t:""};t1.isName=rCn;t1.getAllMatches=tCn;t1.nameRegexp=AKt});var z6e=S($Kt=>{"use strict";var U6e=U_e(),nCn={allowBooleanAttributes:!1,unpairedTags:[]};$Kt.validate=function(t,e){e=Object.assign({},nCn,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--),!dCn(u)){let d;return u.trim().length===0?d="Invalid space after '<'.":d="Tag '"+u+"' is an invalid name.",Wc("InvalidTag",d,db(t,i))}let l=aCn(t,i);if(l===!1)return Wc("InvalidAttr","Attributes for '"+u+"' have open quote.",db(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=DKt(c,e);if(f===!0)n=!0;else return Wc(f.err.code,f.err.msg,db(t,d+f.err.line))}else if(s)if(l.tagClosed){if(c.trim().length>0)return Wc("InvalidTag","Closing tag '"+u+"' can't have attributes or invalid starting.",db(t,a));if(r.length===0)return Wc("InvalidTag","Closing tag '"+u+"' has not been opened.",db(t,a));{let d=r.pop();if(u!==d.tagName){let f=db(t,d.tagStartPos);return Wc("InvalidTag","Expected closing tag '"+d.tagName+"' (opened in line "+f.line+", col "+f.col+") instead of closing tag '"+u+"'.",db(t,a))}r.length==0&&(o=!0)}}else return Wc("InvalidTag","Closing tag '"+u+"' doesn't have proper closing.",db(t,i));else{let d=DKt(c,e);if(d!==!0)return Wc(d.err.code,d.err.msg,db(t,i-c.length+d.err.line));if(o===!0)return Wc("InvalidXml","Multiple possible root nodes found.",db(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=jKt(t,i);continue}else if(t[i+1]==="?"){if(i=NKt(t,++i),i.err)return i}else break;else if(t[i]==="&"){let d=lCn(t,i);if(d==-1)return Wc("InvalidChar","char '&' is not expected.",db(t,i));i=d}else if(o===!0&&!IKt(t[i]))return Wc("InvalidXml","Extra text at the end",db(t,i));t[i]==="<"&&i--}}else{if(IKt(t[i]))continue;return Wc("InvalidChar","char '"+t[i]+"' is not expected.",db(t,i))}if(n){if(r.length==1)return Wc("InvalidTag","Unclosed tag '"+r[0].tagName+"'.",db(t,r[0].tagStartPos));if(r.length>0)return Wc("InvalidXml","Invalid '"+JSON.stringify(r.map(i=>i.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return Wc("InvalidXml","Start tag expected.",1);return!0};function IKt(t){return t===" "||t===" "||t===`
`||t==="\r"}function NKt(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 Wc("InvalidXml","XML declaration allowed only at the start of the document.",db(t,e));if(t[e]=="?"&&t[e+1]==">"){e++;break}else continue}return e}function jKt(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 oCn='"',iCn="'";function aCn(t,e){let r="",n="",o=!1;for(;e<t.length;e++){if(t[e]===oCn||t[e]===iCn)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 sCn=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function DKt(t,e){let r=U6e.getAllMatches(t,sCn),n={};for(let o=0;o<r.length;o++){if(r[o][1].length===0)return Wc("InvalidAttr","Attribute '"+r[o][2]+"' has no space in starting.",dre(r[o]));if(r[o][3]!==void 0&&r[o][4]===void 0)return Wc("InvalidAttr","Attribute '"+r[o][2]+"' is without value.",dre(r[o]));if(r[o][3]===void 0&&!e.allowBooleanAttributes)return Wc("InvalidAttr","boolean attribute '"+r[o][2]+"' is not allowed.",dre(r[o]));let i=r[o][2];if(!cCn(i))return Wc("InvalidAttr","Attribute '"+i+"' is an invalid name.",dre(r[o]));if(!n.hasOwnProperty(i))n[i]=1;else return Wc("InvalidAttr","Attribute '"+i+"' is repeated.",dre(r[o]))}return!0}function uCn(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 lCn(t,e){if(e++,t[e]===";")return-1;if(t[e]==="#")return e++,uCn(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 Wc(t,e,r){return{err:{code:t,msg:e,line:r.line||r,col:r.col}}}function cCn(t){return U6e.isName(t)}function dCn(t){return U6e.isName(t)}function db(t,e){let r=t.substring(0,e).split(/\r?\n/);return{line:r.length,col:r[r.length-1].length+1}}function dre(t){return t.startIndex+t[1].length}});var FKt=S(H6e=>{var LKt={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}},fCn=function(t){return Object.assign({},LKt,t)};H6e.buildOptions=fCn;H6e.defaultOptions=LKt});var qKt=S((F7i,kKt)=>{"use strict";var V6e=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})}};kKt.exports=V6e});var UKt=S((k7i,BKt)=>{var pCn=U_e();function mCn(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&&yCn(t,e))e+=7,[entityName,val,e]=hCn(t,e+1),val.indexOf("&")===-1&&(r[wCn(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(o&&bCn(t,e))e+=8;else if(o&&_Cn(t,e))e+=8;else if(o&&vCn(t,e))e+=9;else if(gCn)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 fre("!xml"),r=e,n="",o="";for(let i=0;i<t.length;i++)if(t[i]==="<")if(t[i+1]==="/"){let s=$4(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=K6e(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 fre(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=$4(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=ECn(t,i);this.docTypeEntities=s.entities,i=s.i}else if(t.substr(i+1,2)==="!["){let s=$4(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=K6e(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 fre(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 fre(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 fre(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 DCn(t,e,r){let n=this.options.updateTag(e.tagname,r,e[":@"]);n===!1||(typeof n=="string"&&(e.tagname=n),t.addChild(e))}var $Cn=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 LCn(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 FCn(t,e,r){let
`;function ZCn(t,e){let r="";return e.format&&e.indentBy.length>0&&(r=GCn),eWt(t,e,"",r)}function eWt(t,e,r,n){let o="",i=!1;for(let a=0;a<t.length;a++){let s=t[a],u=XCn(s);if(u===void 0)continue;let l="";if(r.length===0?l=u:l=`${r}.${u}`,u===e.textNodeName){let m=s[u];YCn(l,e)||(m=e.tagValueProcessor(u,m),m=tWt(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=QKt(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=QKt(s[":@"],e),f=n+`<${u}${d}`,p=eWt(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 XCn(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 QKt(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=tWt(o,e),o===!0&&e.suppressBooleanAttributes?r+=` ${n.substr(e.attributeNamePrefix.length)}`:r+=` ${n.substr(e.attributeNamePrefix.length)}="${o}"`}return r}function YCn(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 tWt(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}rWt.exports=ZCn});var iWt=S((V7i,oWt)=>{"use strict";var QCn=nWt(),exn={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 hF(t){this.options=Object.assign({},exn,t),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=nxn),this.processTextOrObjNode=txn,this.options.format?(this.indentate=rxn,this.tagEndChar=`>
`,this.newLine=`
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}hF.prototype.build=function(t){return this.options.preserveOrder?QCn(t,this.options):(Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t}),this.j2x(t,0).val)};hF.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}};hF.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 txn(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)}hF.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}};hF.prototype.closeTag=function(t){let e="";return this.options.unpairedTags.indexOf(t)!==-1?this.options.suppressUnpairedNode||(e="/"):this.options.suppressEmptyNode?e="/":e=`></${t}`,e};hF.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}};hF.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 rxn(t){return this.options.indentBy.repeat(t)}function nxn(t){return t.startsWith(this.options.attributeNamePrefix)&&t!==this.options.textNodeName?t.substr(this.attrPrefixLen):!1}oWt.exports=hF});var sWt=S((J7i,aWt)=>{"use strict";var oxn=z6e(),ixn=YKt(),axn=iWt();aWt.exports={XMLParser:ixn,XMLValidator:oxn,XMLBuilder:axn}});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]),m6e(s)}return{}}),lWt=async(t,e)=>{let r=await oT(t,e);return r.Error&&(r.Error.message=r.Error.message??r.Error.Message),r}});var dWt=v(()=>{OKt();TKt();MKt();cWt()});var L4=v(()=>{T5t();xKt();dWt()});function sxn(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"cognito-identity",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function z_e(t){return{schemeId:"smithy.api#noAuth"}}var fWt,pWt,mWt,Z6e=v(()=>{L4();pC();fWt=async(t,e,r)=>({operation:tT(e).operation,region:await py(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});pWt=t=>{let e=[];switch(t.operation){case"GetCredentialsForIdentity":{e.push(z_e(t));break}case"GetId":{e.push(z_e(t));break}case"GetOpenIdToken":{e.push(z_e(t));break}case"UnlinkIdentity":{e.push(z_e(t));break}default:e.push(sxn(t))}return e},mWt=t=>({...q_e(t)})});var hWt,eo,il=v(()=>{hWt=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 yWt,gWt=v(()=>{yWt={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 $Gt=v(()=>{});var LGt=v(()=>{$Gt()});var FGt=v(()=>{hd()});var kGt=v(()=>{});var qGt=v(()=>{});function Vxn(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return{...e,[r]:Array.isArray(n)?[...n]:n}},{})}var Dve,BGt=v(()=>{Dve=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=Vxn(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 UGt=v(()=>{});var zGt=v(()=>{});var HGt=v(()=>{});var VGt=v(()=>{LGt();FGt();kGt();qGt();BGt();UGt();zGt();HGt()});function JGt(t){return new Dve({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 KGt(t,e){let n=await c6t(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 xm("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:E6t(o.Expiration)}}if(t.statusCode>=400&&t.statusCode<500){let o={};try{o=JSON.parse(n)}catch{}throw Object.assign(new xm(`Server responded with status: ${t.statusCode}`,{logger:e}),{Code:o.Code,Message:o.Message})}throw new xm(`Server responded with status: ${t.statusCode}`,{logger:e})}var WGt=v(()=>{ZN();VGt();tn();a6e()});var GGt,ZGt=v(()=>{GGt=(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 V5e,XGt=v(()=>{Qte();ZN();DGt();WGt();ZGt();V5e=(t={})=>{t.logger?.debug("@aws-sdk/credential-provider-http - fromHttp");let e,r=t.credentialsFullUri;if(r)e=r;else throw new xm("No HTTP credential provider host provided.",{logger:t.logger});let n=new URL(e);jGt(n,t.logger);let o=new cF;return GGt(async()=>{let i=JGt(n);t.authorizationToken&&(i.headers.Authorization=t.authorizationToken);let a=await o.handle(i);return KGt(a.response)},t.maxRetries??3,t.timeout??1e3)}});var YGt=v(()=>{XGt()});function Jxn(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sts",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function QGt(t){return{schemeId:"smithy.api#noAuth"}}var e9t,t9t,Kxn,r9t,J5e=v(()=>{L4();pC();gre();e9t=async(t,e,r)=>({operation:tT(e).operation,region:await py(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});t9t=t=>{let e=[];switch(t.operation){case"AssumeRoleWithSAML":{e.push(QGt(t));break}case"AssumeRoleWithWebIdentity":{e.push(QGt(t));break}default:e.push(Jxn(t))}return e},Kxn=t=>({...t,stsClientCtor:yS}),r9t=t=>{let e=Kxn(t);return{...q_e(e)}}});var n9t,hy,uT=v(()=>{n9t=t=>({...t,useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,useGlobalEndpoint:t.useGlobalEndpoint??!1,defaultSigningName:"sts"}),hy={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 i9t,o9t=v(()=>{i9t={name:"@aws-sdk/client-sts",description:"AWS SDK for JavaScript Sts Client for Node.js,
${this.getCanonicalPath(e)}
${wZt(e)}
${o.map(i=>`${i}:${r[i]}`).join(`
`)}
${o.join(";")}
${n}`}async createStringToSign(e,r,n,o){let i=new this.sha256;i.update(k4.toUint8Array(n));let a=await i.digest();return`${o}
${e}
${r}
${PF.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 Hve.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=xTn(e).replace(/[\-:]/g,"");return{longDate:r,shortDate:r.slice(0,8)}}getCanonicalHeaderList(e){return Object.keys(e).sort().join(";")}},oWe=class extends Zve{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 tWe)}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>yZt)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");let g=Kve(h,p,d??this.service),y=vZt(nWe(r),{unhoistableHeaders:s,hoistableHeaders:l});f.sessionToken&&(y.query[sWe]=f.sessionToken),y.query[nZt]=Vve,y.query[oZt]=`${f.accessKeyId}/${g}`,y.query[iWe]=m,y.query[aZt]=i.toString(10);let b=eWe(y,a,u);return y.query[iZt]=this.getCanonicalHeaderList(b),y.query[aWe]=await this.getSignature(m,g,this.getSigningKey(f,p,h,d),this.createCanonicalRequest(y,b,await Wve(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=Kve(l,u,s??this.service),f=await Wve({headers:{},body:n},this.sha256),p=new this.sha256;p.update(r);let m=PF.toHex(await p.digest()),h=[mZt,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(k4.toUint8Array(r)),PF.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=nWe(r),{longDate:d,shortDate:f}=this.formatDate(n),p=Kve(f,l,s??this.service);c.headers[lWe]=d,u.sessionToken&&(c.headers[cZt]=u.sessionToken);let m=await Wve(c,this.sha256);!_Zt(Gve,c.headers)&&this.applyChecksum&&(c.headers[Gve]=m);let h=eWe(c,i,o),g=await this.getSignature(d,p,this.getSigningKey(u,l,f,s),this.createCanonicalRequest(c,h,m));return c.headers[uWe]=`${Vve} 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,Vve),s=new this.sha256(await o);return s.update(k4.toUint8Array(a)),PF.toHex(await s.digest())}getSigningKey(r,n,o,i){return bZt(this.sha256,r,o,n,i||this.service)}},TTn={SignatureV4a:null};ti.ALGORITHM_IDENTIFIER=Vve;ti.ALGORITHM_IDENTIFIER_V4A=wTn;ti.ALGORITHM_QUERY_PARAM=nZt;ti.ALWAYS_UNSIGNABLE_HEADERS=dZt;ti.AMZ_DATE_HEADER=lWe;ti.AMZ_DATE_QUERY_PARAM=iWe;ti.AUTH_HEADER=uWe;ti.CREDENTIAL_QUERY_PARAM=oZt;ti.DATE_HEADER=sZt;ti.EVENT_ALGORITHM_IDENTIFIER=mZt;ti.EXPIRES_QUERY_PARAM=aZt;ti.GENERATED_HEADERS=uZt;ti.HOST_HEADER=_Tn;ti.KEY_TYPE_IDENTIFIER=cWe;ti.MAX_CACHE_SIZE=gZt;ti.MAX_PRESIGNED_TTL=yZt;ti.PROXY_HEADER_PATTERN=fZt;ti.REGION_SET_PARAM=bTn;ti.SEC_HEADER_PATTERN=pZt;ti.SHA256_HEADER=Gve;ti.SIGNATURE_HEADER=lZt;ti.SIGNATURE_QUERY_PARAM=aWe;ti.SIGNED_HEADERS_QUERY_PARAM=iZt;ti.SignatureV4=oWe;ti.SignatureV4Base=Zve;ti.TOKEN_HEADER=cZt;ti.TOKEN_QUERY_PARAM=sWe;ti.UNSIGNABLE_PATTERNS=vTn;ti.UNSIGNED_PAYLOAD=hZt;ti.clearCredentialCache=STn;ti.createScope=Kve;ti.getCanonicalHeaders=eWe;ti.getCanonicalQuery=wZt;ti.getPayloadHash=Wve;ti.getSigningKey=bZt;ti.hasHeader=_Zt;ti.moveHeadersToQuery=vZt;ti.prepareRequest=nWe;ti.signatureV4aContainer=TTn});var sc=S((lsa,CZt)=>{"use strict";CZt.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}};pWe.exports={AggregateError:fWe,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 kTn},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:qTn,deprecate(t,e){return t},addAbortListener:Ire().addAbortListener||function(e,r){if(e===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);$Zt(e,"signal"),BTn(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[DTn]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[$Tn](){var o;(o=n)===null||o===void 0||o()}}},AbortSignalAny:LTn.any||function(e){if(e.length===1)return e[0];let r=new FTn,n=()=>r.abort();return e.forEach(o=>{$Zt(o,"signals"),o.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{e.forEach(o=>o.removeEventListener("abort",n))},{once:!0}),r.signal}};pWe.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var hb=S((psa,kZt)=>{"use strict";var{format:UTn,inspect:ewe,AggregateError:zTn}=by(),HTn=globalThis.AggregateError||zTn,VTn=Symbol("kIsNodeError"),JTn=["string","function","number","object","Function","Object","boolean","bigint","symbol"],KTn=/^([A-Z][a-z0-9]*)+$/,WTn="__node_internal_",twe={};function q4(t,e){if(!t)throw new twe.ERR_INTERNAL_ASSERTION(e)}function LZt(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 GTn(t,e,r){if(typeof e=="function")return q4(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 q4(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:UTn(e,...r)}function lg(t,e,r){r||(r=Error);class n extends r{constructor(...i){super(GTn(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[VTn]=!0,twe[t]=n}function FZt(t){let e=WTn+t.name;return Object.defineProperty(t,"name",{value:e}),t}function ZTn(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new HTn([e,t],e.message);return r.code=e.code,r}return t||e}var mWe=class extends Error{constructor(e="The operation was aborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new twe.ERR_INVALID_ARG_TYPE("options","Object",r);super(e,r),this.code="ABORT_ERR",this.name="AbortError"}};lg("ERR_ASSERTION","%s",Error);lg("ERR_INVALID_ARG_TYPE",(t,e,r)=>{q4(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)q4(typeof u=="string","All expected entries have to be of type string"),JTn.includes(u)?o.push(u.toLowerCase()):KTn.test(u)?i.push(u):(q4(u!=="object",'The value "object" should be written as "Object"'),a.push(u));if(i.length>
`)>=0)return!1;return!0}function OIn(t,e){var r;if(t.indent===" ")r=" ";else if(typeof t.indent=="number"&&t.indent>0)r=bT.call(Array(t.indent+1)," ");else return null;return{base:r,prev:bT.call(Array(e+1),r)}}function j8e(t,e){if(t.length===0)return"";var r=`
`+e.prev+e.base;return r+bT.call(t,","+r)+`
`+e.prev}function Awe(t,e){var r=N8e(t),n=[];if(r){n.length=t.length;for(var o=0;o<t.length;o++)n[o]=m1(t,o)?e(t[o],t):""}var i=typeof P8e=="function"?P8e(t):[],a;if($K){a={};for(var s=0;s<i.length;s++)a["$"+i[s]]=i[s]}for(var u in t)m1(t,u)&&(r&&String(Number(u))===u&&u<t.length||$K&&a["$"+u]instanceof Symbol||(GQt.call(/[^\w$]/,u)?n.push(e(u,t)+": "+e(t[u],t)):n.push(u+": "+e(t[u],t))));if(typeof P8e=="function")for(var l=0;l<i.length;l++)ZQt.call(t,i[l])&&n.push("["+e(i[l])+"]: "+e(t[i[l]],t));return n}});var oer=S((Hsa,ner)=>{"use strict";var TIn=Zre(),EIn=Q4(),jwe=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},PIn=function(t,e){if(t){var r=jwe(t,e);return r&&r.value}},MIn=function(t,e,r){var n=jwe(t,e);n?n.value=r:t.next={key:e,next:t.next,value:r}},RIn=function(t,e){return t?!!jwe(t,e):!1},AIn=function(t,e){if(t)return jwe(t,e,!0)};ner.exports=function(){var e,r={assert:function(n){if(!r.has(n))throw new EIn("Side channel does not contain "+TIn(n))},delete:function(n){var o=e&&e.next,i=AIn(e,n);return i&&o&&o===i&&(e=void 0),!!i},get:function(n){return PIn(e,n)},has:function(n){return RIn(e,n)},set:function(n,o){e||(e={next:void 0}),MIn(e,n,o)}};return r}});var F8e=S((Vsa,ier)=>{"use strict";ier.exports=Object});var ser=S((Jsa,aer)=>{"use strict";aer.exports=Error});var ler=S((Ksa,uer)=>{"use strict";uer.exports=EvalError});var der=S((Wsa,cer)=>{"use strict";cer.exports=RangeError});var per=S((Gsa,fer)=>{"use strict";fer.exports=ReferenceError});var her=S((Zsa,mer)=>{"use strict";mer.exports=SyntaxError});var yer=S((Xsa,ger)=>{"use strict";ger.exports=URIError});var _er=S((Ysa,ber)=>{"use strict";ber.exports=Math.abs});var wer=S((Qsa,ver)=>{"use strict";ver.exports=Math.floor});var Cer=S((eua,Ser)=>{"use strict";Ser.exports=Math.max});var Oer=S((tua,xer)=>{"use strict";xer.exports=Math.min});var Eer=S((rua,Ter)=>{"use strict";Ter.exports=Math.pow});var Mer=S((nua,Per)=>{"use strict";Per.exports=Math.round});var Aer=S((oua,Rer)=>{"use strict";Rer.exports=Number.isNaN||function(e){return e!==e}});var Ner=S((iua,Ier)=>{"use strict";var IIn=Aer();Ier.exports=function(e){return IIn(e)||e===0?e:e<0?-1:1}});var Der=S((aua,jer)=>{"use strict";jer.exports=Object.getOwnPropertyDescriptor});var k8e=S((sua,$er)=>{"use strict";var Dwe=Der();if(Dwe)try{Dwe([],"length")}catch{Dwe=null}$er.exports=Dwe});var Fer=S((uua,Ler)=>{"use strict";var $we=Object.defineProperty||!1;if($we)try{$we({},"a",{value:1})}catch{$we=!1}Ler.exports=$we});var qer=S((lua,ker)=>{"use strict";ker.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 zer=S((cua,Uer)=>{"use strict";var Ber=typeof Symbol<"u"&&Symbol,NIn=qer();Uer.exports=function(){return typeof Ber!="function"||typeof Symbol!="function"||typeof Ber("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:NIn()}});var q8e=S((dua,Her)=>{"use strict";Her.exports=typeof Reflect<"u"&&Reflect.getPrototypeOf||null});var B8e=S((fua,Ver)=>{"use strict";var jIn=F8e();Ver.exports=jIn.getPrototypeOf||null});var Wer=S((pua,Ker)=>{"use strict";var DIn="Function.prototype.bind called on incompatible ",$In=Object.prototype.toString,LIn=Math.max,FIn="[object Function]",Jer=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},kIn=function(e,r){
`,this.streamTerminator=n.streamTerminator):this.messageTerminator=n.messageTerminator,o?.addEventListener("abort",()=>this.controller.abort())}iterMessages(){return vrr(this,arguments,function*(){var r,n,o,i;this.controller.signal;let a=wrr(this.stream),s="",u=!1;try{for(var l=!0,c=_rr(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 vrr(this,arguments,function*(){var r,n,o,i;try{for(var a=!0,s=_rr(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 vjn.RUNTIME.type==="node"&&typeof e<"u"&&(r+=Buffer.isBuffer(e)?e:Buffer.from(e));return r}};Bv.Stream=fGe;function wrr(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{next(){return brr(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 brr(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 Srr=S(Qwe=>{"use strict";Object.defineProperty(Qwe,"__esModule",{value:!0});Qwe.Stream=void 0;var Sjn=pGe();Object.defineProperty(Qwe,"Stream",{enumerable:!0,get:function(){return Sjn.Stream}})});var Crr=S(une=>{"use strict";var Cjn=une&&une.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(une,"__esModule",{value:!0});une.encodeAsFormParameter=Ojn;var xjn=Cjn(tGe());function Ojn(t){let r=xjn.default.stringify(t,{encode:!1}).split("&").map(n=>{let[o,i]=n.split("=");return[o,i]});return Object.fromEntries(r)}});var Trr=S((nla,Orr)=>{"use strict";var mGe=Object.defineProperty,Tjn=Object.getOwnPropertyDescriptor,Ejn=Object.getOwnPropertyNames,Pjn=Object.prototype.hasOwnProperty,Mjn=(t,e)=>{for(var r in e)mGe(t,r,{get:e[r],enumerable:!0})},Rjn=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ejn(e))!Pjn.call(t,o)&&o!==r&&mGe(t,o,{get:()=>e[o],enumerable:!(n=Tjn(e,o))||n.enumerable});return t},Ajn=t=>Rjn(mGe({},"__esModule",{value:!0}),t),xrr={};Mjn(xrr,{Blob:()=>jjn,File:()=>Djn,FormData:()=>Njn});Orr.exports=Ajn(xrr);var Ijn=function(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:window}(),{FormData:Njn,Blob:jjn,File:Djn}=Ijn});var krr=S((ola,Frr)=>{"use strict";var yGe=Object.defineProperty,$jn=Object.getOwnPropertyDescriptor,Ljn=Object.getOwnPropertyNames,Fjn=Object.prototype.hasOwnProperty,kjn=(t,e)=>{for(var r in e)yGe(t,r,{get:e[r],enumerable:!0})},qjn=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ljn(e))!Fjn.call(t,o)&&o!==r&&yGe(t,o,{get:()=>e[o],enumerable:!(n=$jn(e,o))||n.enumerable});return t},Bjn=t=>qjn(yGe({},"__esModule",{value:!0}),t),bGe=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},Ec=(t,e,r)=>(bGe(t,e,"read from private field"),r?r.call(t):e.get(t)),wT=(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)},lne=(t,e,r,n)=>(bGe(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),hGe=(t,e,r)=>(bGe(t,e,"access private method"),r),Nrr={};kjn(Nrr,{FormDataEncoder:()=>Gjn,isFile:()=>a2,isFormData:()=>$rr});Frr.exports=Bjn(Nrr);var h1=t=>typeof t=="function",Ujn=t=>h1(t[Symbol.asyncIterator]),Err=65536;function*jrr(t){if(t.byteLength<=Err){yield t;return}let e=
`||e===`
`&&n[r-1]!=="\r"?`\r
`:e),Jjn=t=>Object.prototype.toString.call(t).slice(8,-1).toLowerCase();function Rrr(t){if(Jjn(t)!=="object")return!1;let e=Object.getPrototypeOf(t);return e==null?!0:(e.constructor&&e.constructor.toString())===Object.toString()}function Arr(t,e){if(typeof e=="string"){for(let[r,n]of Object.entries(t))if(e.toLowerCase()===r.toLowerCase())return n}}var Kjn=t=>new Proxy(t,{get:(e,r)=>Arr(e,r),has:(e,r)=>Arr(e,r)!==void 0}),$rr=t=>!!(t&&h1(t.constructor)&&t[Symbol.toStringTag]==="FormData"&&h1(t.append)&&h1(t.getAll)&&h1(t.entries)&&h1(t[Symbol.iterator])),Irr=t=>String(t).replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/"/g,"%22"),a2=t=>!!(t&&typeof t=="object"&&h1(t.constructor)&&t[Symbol.toStringTag]==="File"&&h1(t.stream)&&t.name!=null),Wjn={enableAdditionalHeaders:!1},eSe={writable:!1,configurable:!1},$F,cne,tSe,dne,i2,fne,pne,rSe,nSe,_Ge,gGe,Lrr,Gjn=class{constructor(t,e,r){if(wT(this,nSe),wT(this,gGe),wT(this,$F,`\r
`),wT(this,cne,void 0),wT(this,tSe,void 0),wT(this,dne,"-".repeat(2)),wT(this,i2,new TextEncoder),wT(this,fne,void 0),wT(this,pne,void 0),wT(this,rSe,void 0),!$rr(t))throw new TypeError("Expected first argument to be a FormData instance.");let n;if(Rrr(e)?r=e:n=e,n||(n=Vjn()),typeof n!="string")throw new TypeError("Expected boundary argument to be a string.");if(r&&!Rrr(r))throw new TypeError("Expected options argument to be an object.");lne(this,pne,Array.from(t.entries())),lne(this,rSe,{...Wjn,...r}),lne(this,cne,Ec(this,i2).encode(Ec(this,$F))),lne(this,tSe,Ec(this,cne).byteLength),this.boundary=`form-data-boundary-${n}`,this.contentType=`multipart/form-data; boundary=${this.boundary}`,lne(this,fne,Ec(this,i2).encode(`${Ec(this,dne)}${this.boundary}${Ec(this,dne)}${Ec(this,$F).repeat(2)}`));let o={"Content-Type":this.contentType},i=hGe(this,gGe,Lrr).call(this);i&&(this.contentLength=i,o["Content-Length"]=i),this.headers=Kjn(Object.freeze(o)),Object.defineProperties(this,{boundary:eSe,contentType:eSe,contentLength:eSe,headers:eSe})}*values(){for(let[t,e]of Ec(this,pne)){let r=a2(e)?e:Ec(this,i2).encode(Drr(e));yield hGe(this,nSe,_Ge).call(this,t,r),yield r,yield Ec(this,cne)}yield Ec(this,fne)}async*encode(){for(let t of this.values())a2(t)?yield*Hjn(t.stream()):yield*jrr(t)}[Symbol.iterator](){return this.values()}[Symbol.asyncIterator](){return this.encode()}};$F=new WeakMap;cne=new WeakMap;tSe=new WeakMap;dne=new WeakMap;i2=new WeakMap;fne=new WeakMap;pne=new WeakMap;rSe=new WeakMap;nSe=new WeakSet;_Ge=function(t,e){let r="";if(r+=`${Ec(this,dne)}${this.boundary}${Ec(this,$F)}`,r+=`Content-Disposition: form-data; name="${Irr(t)}"`,a2(e)&&(r+=`; filename="${Irr(e.name)}"${Ec(this,$F)}`,r+=`Content-Type: ${e.type||"application/octet-stream"}`),Ec(this,rSe).enableAdditionalHeaders===!0){let n=a2(e)?e.size:e.byteLength;n!=null&&!isNaN(n)&&(r+=`${Ec(this,$F)}Content-Length: ${n}`)}return Ec(this,i2).encode(`${r}${Ec(this,$F).repeat(2)}`)};gGe=new WeakSet;Lrr=function(){let t=0;for(let[e,r]of Ec(this,pne)){let n=a2(r)?r:Ec(this,i2).encode(Drr(r)),o=a2(n)?n.size:n.byteLength;if(o==null||isNaN(o))return;t+=hGe(this,nSe,_Ge).call(this,e,n).byteLength,t+=o,t+=Ec(this,tSe)}return String(t+Ec(this,fne).byteLength)}});var Brr=S((ala,qrr)=>{"use strict";qrr.exports=typeof self=="object"?self.FormData:window.FormData});var Urr=S(cg=>{"use strict";var Zjn=cg&&cg.__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]}),Xjn=cg&&cg.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),XK=cg&&cg.__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"&&Zjn(r,e,n[o]);return Xjn(r,e),r}}(),LF=cg&&cg.__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(cg,"__esModule",{value:!0});cg.WebFormData=cg.Node16FormData=cg.Node18FormData=void 0;cg.newFormData=Yjn;var oSe=UK();function vGe(t){return typeof t=="object"&&t!=null&&"name"in t}function Yjn(){return LF(this,void 0,void 0,function*(){let t;return oSe.RUNTIME.type==="node"&&oSe.RUNTIME.parsedVersion!=null&&oSe.RUNTIME.parsedVersion>=18?t=new iSe:oSe.RUNTIME.type==="node"?t=new aSe:t=new sSe,yield t.setup(),t})}var iSe=class{setup(){return LF(this,void 0,void 0,function*(){this.fd=new(yield Promise.resolve().then(()=>XK(Trr()))).FormData})}append(e
`)),{ok:!0,value:e}):n}}});var xGe=S(CGe=>{"use strict";Object.defineProperty(CGe,"__esModule",{value:!0});CGe.stringifyValidationError=iDn;function iDn(t){return t.path.length===0?t.message:`${t.path.join(" -> ")}: ${t.message}`}});var TGe=S(lSe=>{"use strict";Object.defineProperty(lSe,"__esModule",{value:!0});lSe.JsonError=void 0;var aDn=xGe(),OGe=class t extends Error{constructor(e){super(e.map(aDn.stringifyValidationError).join("; ")),this.errors=e,Object.setPrototypeOf(this,t.prototype)}};lSe.JsonError=OGe});var PGe=S(cSe=>{"use strict";Object.defineProperty(cSe,"__esModule",{value:!0});cSe.ParseError=void 0;var sDn=xGe(),EGe=class t extends Error{constructor(e){super(e.map(sDn.stringifyValidationError).join("; ")),this.errors=e,Object.setPrototypeOf(this,t.prototype)}};cSe.ParseError=EGe});var Grr=S(s2=>{"use strict";Object.defineProperty(s2,"__esModule",{value:!0});s2.getSchemaUtils=mne;s2.nullable=Vrr;s2.optional=Jrr;s2.optionalNullable=Krr;s2.transform=Wrr;var MGe=mh(),uDn=TGe(),lDn=PGe();function mne(t){return{nullable:()=>Vrr(t),optional:()=>Jrr(t),optionalNullable:()=>Krr(t),transform:e=>Wrr(t,e),parseOrThrow:(e,r)=>{let n=t.parse(e,r);if(n.ok)return n.value;throw new lDn.ParseError(n.errors)},jsonOrThrow:(e,r)=>{let n=t.json(e,r);if(n.ok)return n.value;throw new uDn.JsonError(n.errors)}}}function Vrr(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:()=>MGe.SchemaType.NULLABLE};return Object.assign(Object.assign({},e),mne(e))}function Jrr(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:()=>MGe.SchemaType.OPTIONAL};return Object.assign(Object.assign({},e),mne(e))}function Krr(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:()=>MGe.SchemaType.OPTIONAL_NULLABLE};return Object.assign(Object.assign({},e),mne(e))}function Wrr(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),mne(r))}});var y_=S(xS=>{"use strict";Object.defineProperty(xS,"__esModule",{value:!0});xS.ParseError=xS.JsonError=xS.transform=xS.optional=xS.getSchemaUtils=void 0;var RGe=Grr();Object.defineProperty(xS,"getSchemaUtils",{enumerable:!0,get:function(){return RGe.getSchemaUtils}});Object.defineProperty(xS,"optional",{enumerable:!0,get:function(){return RGe.optional}});Object.defineProperty(xS,"transform",{enumerable:!0,get:function(){return RGe.transform}});var cDn=TGe();Object.defineProperty(xS,"JsonError",{enumerable:!0,get:function(){return cDn.JsonError}});var dDn=PGe();Object.defineProperty(xS,"ParseError",{enumerable:!0,get:function(){return dDn.ParseError}})});var Xrr=S(AGe=>{"use strict";Object.defineProperty(AGe,"__esModule",{value:!0});AGe.bigint=hDn;var fDn=mh(),Zrr=gb(),pDn=ST(),mDn=y_();function hDn(){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,Zrr.getErrorMessageForIncorrectType)(e,"bigint | number")}]},json:(e,{breadcrumbsPrefix:r=[]}={})=>typeof e!="bigint"?{ok:!1,errors:[{path:r,message:(0,Zrr.getErrorMessageForIncorrectType)(e,"bigint")}]}:{ok:!0,value:e},getType:()=>fDn.SchemaType.BIGINT};return Object.assign(Object.assign({},(0,pDn.maybeSkipValidation)(t)),(0,mDn.getSchemaUtils)(t))}});var Yrr=S(dSe=>{"use strict";Object.defineProperty(dSe,"__esModule",{value:!0});dSe.bigint=void 0;var gDn=Xrr();Object.defineProperty(dSe,"bigint",{enumerable:!0,get:function(){return gDn.bigint}})});var Qrr=S(NGe=>{"use strict";Object.defineProperty(NGe,"__esModule",{value:!0});NGe.date=wDn;var yDn=mh(),IGe=gb(),bDn=ST(),_Dn=y_(),vDn=/^([+-]?\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 wne(this,void 0,void 0,function*(){var o;yield(o=r.return)===null||o===void 0?void 0:o.call(r)})}})}};fg.StreamUtils=l9e;function Jnr(t,e){return Cne(this,arguments,function*(){var n,o,i,a;if(!t.body)throw e?.abort(),new rW.CohereError({message:"Attempted to iterate over a response with no body"});let s=new c9e,u=new FF,l=d9e(t.body);try{for(var c=!0,d=Sne(wLn(l)),f;f=yield Rl(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 Rl(h))}}}catch(p){o={error:p}}finally{try{!c&&!n&&(i=d.return)&&(yield Rl(i.call(d)))}finally{if(o)throw o.error}}for(let p of u.flush()){let m=s.decode(p);m&&(yield yield Rl(m))}})}function wLn(t){return Cne(this,arguments,function*(){var r,n,o,i;let a=new Uint8Array;try{for(var s=!0,u=Sne(t),l;l=yield Rl(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=SLn(a))!==-1;)yield yield Rl(a.slice(0,p)),a=a.slice(p)}}catch(c){n={error:c}}finally{try{!s&&!r&&(o=u.return)&&(yield Rl(o.call(u)))}finally{if(n)throw n.error}}a.length>0&&(yield yield Rl(a))})}function SLn(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 c9e=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]=xLn(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},FF=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 rW.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 rW.CohereError({message:`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`})}throw new rW.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}};fg.LineDecoder=FF;FF.NEWLINE_CHARS=new Set([`
`,"\r"]);FF.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function CLn(t){let e=new FF,r=[];for(let n of t)r.push(...e.decode(n));return r}function xLn(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}function d9e(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{next(){return wne(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 wne(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 One=S(CT=>{"use strict";var OLn=CT&&CT.__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]}),TLn=CT&&CT.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),ELn=CT&&CT.__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"&&OLn(r,e,n[o]);return TLn(r,e),r}}();Object.defineProperty(CT,"__esModule",{value:!0});CT.Document=void 0;var xne=ELn(re());CT.Document=xne.serialization.object({data:xne.serialization.record(xne.serialization.string(),xne.serialization.unknown()),id:xne.serialization.string().optional()})});var f9e=S(xT=>{"use strict";var PLn=xT&&xT.__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]}),MLn=xT&&xT.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),RLn=xT&&xT.__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"&&PLn(r,e,n[o]);return MLn(r,e),r}}();Object.defineProperty(xT,"__esModule",{value:!0});xT.V2ChatStreamRequestDocumentsItem=void 0;var Wnr=RLn(re()),ALn=One();xT.V2ChatStreamRequestDocumentsItem=Wnr.serialization.undiscriminatedUnion([Wnr.serialization.string(),ALn.Document])});var p9e=S(OT=>{"use strict";var ILn=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]}),NLn=OT&&OT.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),jLn=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"&&ILn(r,e,n[o]);return NLn(r,e),r}}();Object.defineProperty(OT,"__esModule",{value:!0});OT.V2ChatStreamRequestSafetyMode=void 0;var DLn=jLn(re());OT.V2ChatStreamRequestSafetyMode=DLn.serialization.enum_(["CONTEXTUAL","STRICT","OFF"])});var m9e=S(TT=>{"use strict";var $Ln=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(
`)}}}}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,Qs.parseAWSEvent)(T);if(R){let I=yield(0,Qs.mapResponseFromBedrock)(m,d,f,R);E.push(JSON.stringify(I)+`
`)}}return E.end(),{ok:!0,body:E,rawResponse:y.rawResponse}}else{let x=yield y.body;return{ok:!0,body:yield(0,Qs.mapResponseFromBedrock)(m,d,f,x),rawResponse:y.rawResponse}}}catch(x){throw x}});Qs.fetchOverride=aXn});var T1=S(m0e=>{"use strict";Object.defineProperty(m0e,"__esModule",{value:!0});m0e.CohereEnvironment=void 0;m0e.CohereEnvironment={Production:"https://api.cohere.com"}});var WF=S((par,h0e)=>{(function(t,e,r){typeof h0e<"u"&&h0e.exports?h0e.exports=r():typeof define=="function"&&define.amd?define(r):e[t]=r()})("urljoin",par,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 KXe=S(w_=>{"use strict";var sXn=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]}),uXn=w_&&w_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Zne=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"&&sXn(r,e,n[o]);return uXn(r,e),r}}(),xW=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())})},lXn=w_&&w_.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(w_,"__esModule",{value:!0});w_.V2=void 0;var g0e=Zne(T1()),Wi=Zne(re()),Nn=Zne(GN()),GF=Zne(O1()),y0e=lXn(WF()),mg=Zne(Oc()),JXe=class{constructor(e={}){this._options=e}chatStream(e,r){return Wi.HttpResponsePromise.fromPromise(this.__chatStream(e,r))}__chatStream(e,r){return xW(this,void 0,void 0,function*(){var n,o,i;let a=yield((n=this._options.fetcher)!==null&&n!==void 0?n:Wi.fetcher)({url:(0,y0e.default)((i=(o=yield Wi.Supplier.get(this._options.baseUrl))!==null&&o!==void 0?o:yield Wi.Supplier.get(this._options.environment))!==null&&i!==void 0?i:g0e.CohereEnvironment.Production,"v2/chat"),method:"POST",headers:Object.assign({Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield Wi.Supplier.get(this._options.clientName))!=null?yield Wi.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":Wi.RUNTIME.type,"X-Fern-Runtime-Version":Wi.RUNTIME.version},r?.headers),contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},GF.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 Wi.Stream({stream:a.body,parse:s=>xW(this,void 0,void
`}}),rawResponse:u.rawResponse};if(u.error.reason==="status-code")switch(u.error.statusCode){case 400:throw new Re.BadRequestError(u.error.body,u.rawResponse);case 401:throw new Re.UnauthorizedError(u.error.body,u.rawResponse);case 403:throw new Re.ForbiddenError(u.error.body,u.rawResponse);case 404:throw new Re.NotFoundError(u.error.body,u.rawResponse);case 422:throw new Re.UnprocessableEntityError(u.error.body,u.rawResponse);case 429:throw new Re.TooManyRequestsError(u.error.body,u.rawResponse);case 498:throw new Re.InvalidTokenError(u.error.body,u.rawResponse);case 499:throw new Re.ClientClosedRequestError(u.error.body,u.rawResponse);case 500:throw new Re.InternalServerError(u.error.body,u.rawResponse);case 501:throw new Re.NotImplementedError(u.error.body,u.rawResponse);case 503:throw new Re.ServiceUnavailableError(u.error.body,u.rawResponse);case 504:throw new Re.GatewayTimeoutError(u.error.body,u.rawResponse);default:throw new 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 rt.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=Sar(e,["accepts"]),u=yield((n=this._options.fetcher)!==null&&n!==void 0?n:rt.fetcher)({url:(0,TC.default)((i=(o=yield rt.Supplier.get(this._options.baseUrl))!==null&&o!==void 0?o:yield rt.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 rt.Supplier.get(this._options.clientName))!=null?yield rt.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":rt.RUNTIME.type,"X-Fern-Runtime-Version":rt.RUNTIME.version,Accepts:a??void 0},r?.headers),contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},Yc.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:Yc.NonStreamedChatResponse.parseOrThrow(u.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}),rawResponse:u.rawResponse};if(u.error.reason==="status-code")switch(u.error.statusCode){case 400:throw new Re.BadRequestError(u.error.body,u.rawResponse);case 401:throw new Re.UnauthorizedError(u.error.body,u.rawResponse);case 403:throw new Re.ForbiddenError(u.error.body,u.rawResponse);case 404:throw new Re.NotFoundError(u.error.body,u.rawResponse);case 422:throw new Re.UnprocessableEntityError(u.error.body,u.rawResponse);case 429:throw new Re.TooManyRequestsError(u.error.body,u.rawResponse);case 498:throw new Re.InvalidTokenError(u.error.body,u.rawResponse);case 499:throw new Re.ClientClosedRequestError(u.error.body,u.rawResponse);case 500:throw new Re.InternalServerError(u.error.body,u.rawResponse);case 501:throw new Re.NotImplementedError(u.error.body,u.rawResponse);case 503:throw new Re.ServiceUnavailableError(u.error.body,u.rawResponse);case 504:throw new Re.GatewayTimeoutError(u.error.body,u.rawResponse);default:throw new 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 Re.BadRequestError(a.error.body,a.rawResponse);case 401:throw new Re.UnauthorizedError(a.error.body,a.rawResponse);case 403:throw new Re.ForbiddenError(a.error.body,a.rawResponse);case 404:throw new Re.NotFoundError(a.error.body,a.rawResponse);case 422:throw new Re.UnprocessableEntityError(a.error.body,a.rawResponse);case 429:throw new Re.TooManyRequestsError(a.error.body,a.rawResponse);case 498:throw new Re.InvalidTokenError(a.error.body,a.rawResponse);case 499:throw new Re.ClientClosedRequestError(a.error.body,a.rawResponse);case 500:throw new Re.InternalServerError(a.error.body,a.rawResponse);case 501:throw new Re.NotImplementedError(a.error.body,a.rawResponse);case 503:throw new Re.ServiceUnavailableError(a.error.body,a.rawResponse);case 504:throw new Re.GatewayTimeoutError(a.error.body,a.rawResponse);default:throw new 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 rt.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:rt.fetcher)({url:(0,TC.default)((i=(o=yield rt.Supplier.get(this._options.baseUrl))!==null&&o!==void 0?o:yield rt.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 rt.Supplier.get(this._options.clientName))!=null?yield rt.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":rt.RUNTIME.type,"X-Fern-Runtime-Version":rt.RUNTIME.version},r?.headers),contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},Yc.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:Yc.Generation.parseOrThrow(a.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}),rawResponse:a.rawResponse};if(a.error.reason==="status-code")switch(a.error.statusCode){case 400:throw new Re.BadRequestError(a.error.body,a.rawResponse);case 401:throw new Re.UnauthorizedError(a.error.body,a.rawResponse);case 403:throw new Re.ForbiddenError(a.error.body,a.rawResponse);case 404:throw new Re.NotFoundError(a.error.body,a.rawResponse);case 422:throw new Re.UnprocessableEntityError(a.error.body,a.rawResponse);case 429:throw new Re.TooManyRequestsError(a.error.body,a.rawResponse);case 498:throw new Re.InvalidTokenError(a.error.body,a.rawResponse);case 499:throw new Re.ClientClosedRequestError(a.error.body,a.rawResponse);case 500:throw new Re.InternalServerError(a.error.body,a.rawResponse);case 501:throw new Re.NotImplementedError(a.error.body,a.rawResponse);case 503:throw new Re.ServiceUnavailableError(a.error.body,a.rawResponse);case 504:throw new Re.GatewayTimeoutError(a.error.body,a.rawResponse);default:throw new 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=qar.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=mYe.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=mYe.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(...tYn(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)}},T0e=mYe;QXn(T0e,"specialTokenRegex",t=>new RegExp(t.map(e=>rYn(e)).join("|"),"g"))});var Uar=v(()=>{Bar()});async function gYe(t){return t in E0e||(E0e[t]=oYn.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>new T0e(e)).catch(e=>{throw delete E0e[t],e})),await E0e[t]}async function P0e(t){return gYe(hYe(t))}var nYn,E0e,oYn,yYe=v(()=>{Do();nz();Uar();nYn={};Tt(nYn,{encodingForModel:()=>P0e,getEncoding:()=>gYe});E0e={},oYn=new kw({})});function Wv(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 iYn,M0e,aYn,zar,Har,sYn,IW,M2,Gv=v(()=>{Do();iO();nz();Yh();$Q();kar();yYe();iYn={};Tt(iYn,{BaseLangChain:()=>IW,BaseLanguageModel:()=>M2,calculateMaxTokens:()=>Har,getEmbeddingContextSize:()=>aYn,getModelContextSize:()=>zar,getModelNameForTiktoken:()=>M0e,isOpenAITool:()=>Wv});M0e=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,aYn=t=>{switch(t){case"text-embedding-ada-002":return 8191;default:return 2046}},zar=t=>{switch(M0e(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}};Har=async({prompt:t,modelName:e})=>{let r;try{r=(await P0e(M0e(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 zar(e)-r},sYn=()=>!1,IW=class extends Lo{constructor(e){super(e);M(this,"verbose");M(this,"callbacks");M(this,"tags");M(this,"metadata");this.verbose=e.verbose??sYn(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}get lc_attributes(){return{callbacks:void 0,verbose:void 0}}},M2=class extends IW{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=pYe.global():this.cache=void 0,this.caller=new kw(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 Asr(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 L0e(t){return!!t.finishReason&&zYn.includes(t.finishReason)}function ek(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];L0e(i)&&(o+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(o+=`: ${i.finishMessage}`))}return o}function moe(t){return this instanceof moe?(this.v=t,this):new moe(t)}function HYn(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 moe?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 VYn(t){let e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),r=WYn(e),[n,o]=r.tee();return{stream:KYn(n),response:JYn(o)}}async function JYn(t){let e=[],r=t.getReader();for(;;){let{done:n,value:o}=await r.read();if(n)return DYe(GYn(e));e.push(o)}}function KYn(t){return HYn(this,arguments,function*(){let r=t.getReader();for(;;){let{value:n,done:o}=yield moe(r.read());if(o)break;yield yield moe(DYe(n))}})}function WYn(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 _h("Failed to parse stream"));return}n.close();return}o+=a;let u=o.match(Isr),l;for(;u;){try{l=JSON.parse(u[1])}catch{n.error(new _h(`Error parsing JSON response: "${u[1]}"`));return}n.enqueue(l),o=o.substring(u[0].length),u=o.match(Isr)}return i()}).catch(a=>{let s=a;throw s.stack=a.stack,s.name==="AbortError"?s=new k0e("Request aborted when reading from the stream"):s=new _h("Error reading from the stream"),s})}}})}function GYn(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 Lsr(t,e,r,n){let o=await goe(e,N2.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(r),n);return VYn(o)}async function Fsr(t,e,r,n){let i=await(await goe(e,N2.GENERATE_CONTENT,t,!1,JSON.stringify(r),n)).json();return{response:DYe(i)}}function ksr(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 sA(t,e){if(!(this instanceof sA))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 Rm(e.headers),this.url=e.url||"",this._initBody(t)}function our(t,e){return new Promise(function(r,n){var o=new $2(t,e);if(o.signal&&o.signal.aborted)return n(new D2("Aborted","AbortError"));var i=new XMLHttpRequest;function a(){i.abort()}i.onload=function(){var l={statusText:i.statusText,headers:wQn(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 sA(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 D2("Aborted","AbortError"))},0)};function s(l){try{return l===""&&wg.location.href?wg.location.href:l}catch{return l}}if(i.open(o.method,s(o.url),!0),o.credentials==="include"?i.withCredentials=!0:o.credentials==="omit"&&(i.withCredentials=!1),"responseType"in i&&(bb.blob?i.responseType="blob":bb.arrayBuffer&&(i.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof Rm||wg.Headers&&e.headers instanceof wg.Headers)){var u=[];Object.getOwnPropertyNames(e.headers).forEach(function(l){u.push(NW(l)),i.setRequestHeader(l,HYe(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 wg,bb,Qsr,tur,bQn,SQn,D2,iur=v(()=>{wg=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof window<"u"&&window||{},bb={searchParams:"URLSearchParams"in wg,iterable:"Symbol"in wg&&"iterator"in Symbol,blob:"FileReader"in wg&&"Blob"in wg&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in wg,arrayBuffer:"ArrayBuffer"in wg};bb.arrayBuffer&&(Qsr=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],tur=ArrayBuffer.isView||function(t){return t&&Qsr.indexOf(Object.prototype.toString.call(t))>-1});Rm.prototype.append=function(t,e){t=NW(t),e=HYe(e);var r=this.map[t];this.map[t]=r?r+", "+e:e};Rm.prototype.delete=function(t){delete this.map[NW(t)]};Rm.prototype.get=function(t){return t=NW(t),this.has(t)?this.map[t]:null};Rm.prototype.has=function(t){return this.map.hasOwnProperty(NW(t))};Rm.prototype.set=function(t,e){this.map[NW(t)]=HYe(e)};Rm.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)};Rm.prototype.keys=function(){var t=[];return this.forEach(function(e,r){t.push(r)}),VYe(t)};Rm.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),VYe(t)};Rm.prototype.entries=function(){var t=[];return this.forEach(function(e,r){t.push([r,e])}),VYe(t)};bb.iterable&&(Rm.prototype[Symbol.iterator]=Rm.prototype.entries);bQn=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];$2.prototype.clone=function(){return new $2(this,{body:this._bodyInit})};nur.call($2.prototype);nur.call(sA.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)}},RQn=t=>{if(!t)return uur;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=sur);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},AQn=Object.defineProperty,IQn=(t,e,r)=>e in t?AQn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,KYe=(t,e,r)=>(IQn(t,typeof e!="symbol"?e+"":e,r),r),DW=class{constructor(e){KYe(this,"config"),KYe(this,"fetch"),KYe(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e?.headers},e?.proxy||(this.config.host=RQn(e?.host??uur)),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 jW(this.fetch,n,r,{signal:i.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");let s=MQn(a.body),u=new GYe(i,s,()=>{let l=this.ongoingStreamedRequests.indexOf(u);l>-1&&this.ongoingStreamedRequests.splice(l,1)});return this.ongoingStreamedRequests.push(u),u}return await(await jW(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 PQn(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await jW(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await aur(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await jW(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await jW(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await jW(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await aur(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}},t_a=new DW});var YYe,lur=v(()=>{Ysr();js();A1();H0e();gm();Ov();R1();cO();_O();Zv();o_();YYe=class extends bh{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 DW({fetch:e?.fetch,host:e?.baseUrl,headers:e?.headers}),this.baseUr
`)}function mur(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}: ${V0e(o,e)},`):r.push(`${n}?: ${V0e(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
`)}function V0e(t,e){if(jQn(t))return t.anyOf.map(r=>V0e(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["{",mur(t,e+2),"}"].join(`
`);case"array":return t.items?`${V0e(t.items,e)}[]`:"any[]";default:return""}}function J0e(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 $W(t){return"type"in t&&t.type!=="function"}function hur(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function L2(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 K0e(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function gur(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 yur(t){return t.type==="tool_call"&&"isCustomTool"in t&&t.isCustomTool===!0}function bur(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 _ur(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 boe=v(()=>{Zv();o_();R1()});function _oe(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var voe,W0e=v(()=>{voe=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 Ft,Am,Mc,nk,dA,LW,FW,kW,qW,BW,UW,zW,HW,VW,JW,fA,pA=v(()=>{W0e();Ft=class extends Error{},Am=class t extends Ft{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 nk({message:n,cause:voe(r)});let i=r?.error;return e===400?new LW(e,i,n,o):e===401?new FW(e,i,n,o):e===403?new kW(e,i,n,o):e===404?new qW(e,i,n,o):e===409?new BW(e,i,n,o):e===422?new UW(e,i,n,o):e===429?new zW(e,i,n,o):e>=500?new HW(e,i,n,o):new t(e,i,n,o)}},Mc=class extends Am{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},nk=class extends Am{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},dA=class extends nk{constructor({message:e}={}){super({message:e??"Request timed out."})}},LW=class extends Am{},FW=class extends Am{},kW=class extends Am{},qW=class extends Am{},BW=class extends Am{},UW=class extends Am{},zW=class extends Am{},HW=class extends Am{},VW=class extends Ft{constructor(){super("Could not parse response content as the length limit was reached")}},JW=class extends Ft{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},fA=class extends Error{constructor(e){super(e)}}});var RC=v(()=>{pA()});function woe(t){return t!==void 0&&"function"in t&&t.function!==void 0}function vur(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Soe(t){return t?.$brand==="auto-parseable-response-format"}function F2(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 Y0e(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===Me.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:hn(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:hn(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===Me.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(Z0e(t.keyType._def,e)).reduce((o,[i,a])=>i==="type"?o:{...o,[i]:a},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===Me.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}var Q0e=v(()=>{yO();yd();X0e()});function Uur(t,e){if(e.mapStrategy==="record")return Y0e(t,e);let r=hn(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=hn(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 vQe=v(()=>{yd();Q0e()});function zur(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 wQe=v(()=>{});function Hur(){return{not:{}}}var SQe=v(()=>{});function Vur(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var CQe=v(()=>{});function Kur(t,e){if(e.target==="openApi3")return Jur(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Ooe&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=Ooe[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 Jur(t,e)}var Ooe,Jur,eCe=v(()=>{yd();Ooe={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Jur=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>hn(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 Wur(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:Ooe[t.innerType._def.typeName],nullable:!0}:{type:[Ooe[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=hn(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=hn(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var xQe=v(()=>{yd();eCe()});function Gur(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",iQe(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?
`):[]}};Xv=new WeakMap,Yv=new WeakMap;q2.NEWLINE_CHARS=new Set([`
`,"\r"]);q2.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function Eoe(){}function cCe(t,e,r){return!e||dCe[t]>dCe[r]?Eoe:e[t].bind(e)}function Qc(t){let e=t.logger,r=t.logLevel??"off";if(!e)return ceo;let n=Blr.get(e);if(n&&n[0]===r)return n[1];let o={error:cCe("error",e,r),warn:cCe("warn",e,r),info:cCe("info",e,r),debug:cCe("debug",e,r)};return Blr.set(e,[r,o]),o}var dCe,eet,ceo,Blr,j1,Poe=v(()=>{N1();dCe={off:0,error:200,warn:300,info:400,debug:500},eet=(t,e,r)=>{if(t){if(hlr(dCe,t))return t;Qc(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(dCe))}`)}};ceo={error:Eoe,warn:Eoe,info:Eoe,debug:Eoe},Blr=new WeakMap;j1=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*deo(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Ft("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 Ft("Attempted to iterate over a response with no body");let r=new tet,n=new q2,o=JQe(t.body);for await(let i of feo(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*feo(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"?ZW(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let i;for(;(i=klr(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function peo(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var Moe,gA,tet,ret=v(()=>{AS();pA();Toe();qlr();Toe();W0e();lCe();Poe();pA();gA=class t{constructor(e,r,n){this.iterator=e,Moe.set(this,void 0),this.controller=r,Fr(this,Moe,n,"f")}static fromSSEResponse(e,r,n){let o=!1,i=n?Qc(n):console;async function*a(){if(o)throw new Ft("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let s=!1;try{for await(let u of deo(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 Am(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 Am(void 0,l.error,l.message,void 0);yield{event:u.event,data:l}}}s=!0}catch(u){if(_oe(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 q2,u=JQe(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 Ft("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(_oe(u))return;throw u}finally{s||r.abort()}}return new t(a,r,n)}[(Moe=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),o=i=>({next:()=>{if(i.length===0){let a=n.next();e.push(a),r.push(a)}return i.shift()}});return[new t(()=>o(e),this.controller,Ce(this,Moe,"f")),new t(()=>o(r),this.controller,Ce(this,Moe,"f"))]}toReadableStream(){let e=this,r;return VQe({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=ZW(JSON.stringify(o)+`
`);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};tet=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]=peo(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function fCe(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:o,startTime:i}=e,a=await(async()=>{if(e.options.stream)return Qc(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller,t):gA.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 net(d,r)}return await r.text()})();return Qc(t).debug(`[${n}] response parsed`,j1({retryOfRequestLogID:o,url:r.url,status:r.status,body:a,durationMs:Date.now()-i})),a}function net(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 oet=v(()=>{ret();Poe()});var Roe,B2,pCe=v(()=>{AS();oet();B2=class t extends Promise{constructor(e,r,n=fCe){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,Roe.set(this,void 0),Fr(this,Roe,e,"f")}_thenUnwrap(e){return new t(Ce(this,Roe,"f"),this.responsePromise,async(r,n)=>net(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(Ce(this,Roe,"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)}};Roe=new WeakMap});var mCe,Aoe,Ioe,yA,Go,D1,xu=v(()=>{AS();pA();oet();pCe();N1();Aoe=class{constructor(e,r,n,o){mCe.set(this,void 0),Fr(this,mCe,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 Ft("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await Ce(this,mCe,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(mCe=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},Ioe=class extends B2{constructor(e,r,n){super(e,r,async(o,i)=>new n(o,i.response,await fCe(o,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},yA=class extends Aoe{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 Aoe{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:{...UQe(this.options.query),after:r}}:null}},D1=class extends Aoe{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:{...UQe(this.options.query),after:e}}:null}}});function XW(t,e,r){return set(),new File(t,e??"unknown_file",r)}function Noe(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 heo(t){let e=typeof t=="fu
${i.map(f=>f.error).join(`
`)}
${a}
${d}`)}return a},Ne=weo(Wlr)});var U2,gCe=v(()=>{kr();xu();Ya();U2=class extends qe{list(e,r={},n){return this._client.getAPIList(Ne`/chat/completions/${e}/messages`,Go,{query:r,...n})}}});var YW,fet,pet=v(()=>{YW=t=>t?.role==="assistant",fet=t=>t?.role==="tool"});var met,yCe,bCe,Doe,$oe,_Ce,Loe,$1,Foe,vCe,wCe,QW,Glr,ak,SCe=v(()=>{AS();RC();ak=class{constructor(){met.add(this),this.controller=new AbortController,yCe.set(this,void 0),bCe.set(this,()=>{}),Doe.set(this,()=>{}),$oe.set(this,void 0),_Ce.set(this,()=>{}),Loe.set(this,()=>{}),$1.set(this,{}),Foe.set(this,!1),vCe.set(this,!1),wCe.set(this,!1),QW.set(this,!1),Fr(this,yCe,new Promise((e,r)=>{Fr(this,bCe,e,"f"),Fr(this,Doe,r,"f")}),"f"),Fr(this,$oe,new Promise((e,r)=>{Fr(this,_Ce,e,"f"),Fr(this,Loe,r,"f")}),"f"),Ce(this,yCe,"f").catch(()=>{}),Ce(this,$oe,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},Ce(this,met,"m",Glr).bind(this))},0)}_connected(){this.ended||(Ce(this,bCe,"f").call(this),this._emit("connect"))}get ended(){return Ce(this,Foe,"f")}get errored(){return Ce(this,vCe,"f")}get aborted(){return Ce(this,wCe,"f")}abort(){this.controller.abort()}on(e,r){return(Ce(this,$1,"f")[e]||(Ce(this,$1,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=Ce(this,$1,"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(Ce(this,$1,"f")[e]||(Ce(this,$1,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{Fr(this,QW,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){Fr(this,QW,!0,"f"),await Ce(this,$oe,"f")}_emit(e,...r){if(Ce(this,Foe,"f"))return;e==="end"&&(Fr(this,Foe,!0,"f"),Ce(this,_Ce,"f").call(this));let n=Ce(this,$1,"f")[e];if(n&&(Ce(this,$1,"f")[e]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...r))),e==="abort"){let o=r[0];!Ce(this,QW,"f")&&!n?.length&&Promise.reject(o),Ce(this,Doe,"f").call(this,o),Ce(this,Loe,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=r[0];!Ce(this,QW,"f")&&!n?.length&&Promise.reject(o),Ce(this,Doe,"f").call(this,o),Ce(this,Loe,"f").call(this,o),this._emit("end")}}_emitFinal(){}};yCe=new WeakMap,bCe=new WeakMap,Doe=new WeakMap,$oe=new WeakMap,_Ce=new WeakMap,Loe=new WeakMap,$1=new WeakMap,Foe=new WeakMap,vCe=new WeakMap,wCe=new WeakMap,QW=new WeakMap,met=new WeakSet,Glr=function(e){if(Fr(this,vCe,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new Mc),e instanceof Mc)return Fr(this,wCe,!0,"f"),this._emit("abort",e);if(e instanceof Ft)return this._emit("error",e);if(e instanceof Error){let r=new Ft(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new Ft(String(e)))}});function Zlr(t){return typeof t.parse=="function"}var het=v(()=>{});var _b,get,CCe,yet,bet,_et,Xlr,Ylr,Ceo,e8,vet=v(()=>{AS();RC();KW();pet();SCe();het();Ceo=10,e8=class extends ak{constructor(){super(...arguments),_b.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),fet(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(YW(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 Ft("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),Ce(this,_b,"m",get).call(this)}async finalMessage(){return await this.done(),Ce(this,_b,"m",CCe).call(this)}async finalFunctionToolCall(){return await this.done(),Ce(this,_b,"m",yet).call(this)}async finalFunctionToolCallResult(){return await this.done(),Ce(this,_b,"m",bet).call(this)}async totalUsage(){return await this.done(),Ce(this,_b,"m",_et).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[th
\r `.includes(t[n]);)n++};return a()},Oet=t=>xeo(t,vh.ALL^vh.NUM)});var Tet=v(()=>{ret()});function Teo(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 Ft(`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 Ft(`missing role for choice ${d}`);if(h){let{arguments:_,name:w}=h;if(_==null)throw new Ft(`missing function_call.arguments for choice ${d}`);if(!w)throw new Ft(`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:I,...j}=x||{};if(E==null)throw new Ft(`missing choices[${d}].tool_calls[${w}].id
${TCe(t)}`);if(O==null)throw new Ft(`missing choices[${d}].tool_calls[${w}].type
${TCe(t)}`);if(I==null)throw new Ft(`missing choices[${d}].tool_calls[${w}].function.name
${TCe(t)}`);if(R==null)throw new Ft(`missing choices[${d}].tool_calls[${w}].function.arguments
${TCe(t)}`);return{...T,id:E,type:O,function:{...j,name:I,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 wur(u,e)}function TCe(t){return JSON.stringify(t)}var Nm,L1,t8,sk,Eet,xCe,Pet,Met,Ret,OCe,Aet,ecr,z2,ECe=v(()=>{AS();Qlr();RC();KW();Tet();vet();z2=class t extends e8{constructor(e){super(),Nm.add(this),L1.set(this,void 0),t8.set(this,void 0),sk.set(this,void 0),Fr(this,L1,e,"f"),Fr(this,t8,[],"f")}get currentChatCompletionSnapshot(){return Ce(this,sk,"f")}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createChatCompletion(e,r,n){let o=new t(r);return o._run(()=>o._runChatCompletion(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createChatCompletion(e,r,n){super._createChatCompletion;let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),Ce(this,Nm,"m",Eet).call(this);let i=await e.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let a of i)Ce(this,Nm,"m",Pet).call(this,a);if(i.controller.signal?.aborted)throw new Mc;return this._addChatCompletion(Ce(this,Nm,"m",OCe).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),Ce(this,Nm,"m",Eet).call(this),this._connected();let o=gA.fromReadableStream(e,this.controller),i;for await(let a of o)i&&i!==a.id&&this._addChatCompletion(Ce(this,Nm,"m",OCe).call(this)),Ce(this,Nm,"m",Pet).call(this,a),i=a.id;if(o.controller.signal?.aborted)throw new Mc;return this._addChatCompletion(Ce(this,Nm,"m",OCe).call(this))}[(L1=new WeakMap,t8=new WeakMap,sk=new WeakMap,Nm=new WeakSet,Eet=function(){this.ended||Fr(this,sk,void 0,"f")},xCe=function(r){let n=Ce(this,t8,"f")[r.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},Ce(this,t8,"f")[r.index]=n,n)},Pet=function(r){if(this.ended)return;let n=Ce(this,Nm,"m",ecr).call(this,r);this._emit("chunk",r,n);for(let o of r.choices){let i=n.choices[o.index];o.delta.content!=null&&i.message?.role==="assistant"&&i.message?.content&&(this._emit("content",o.delta.content,i.message.content),this._emit("content.delta",{delta:o.delta.content,snapshot:i.message.content,parsed:i.message.parsed})),o.delta.refusal!=null&&i.message?.role==="assistant"&&i.message?.refusal&&this._emit("refusal.delta",{delta:o.delta.refusal,snapshot:i.message.refusal}),o.logprobs?.content!=null&&i.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:o.logprobs?.content,snapshot:i.logprobs?.content??[]}),o.logprobs?.refusal!=null&&i.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:o.logprobs?.refusal,snapshot:i.logprobs?.refusal??[]});let a=Ce(this,Nm,"m",xCe).call(this,i);i.finish_reason&&(Ce(this,Nm,"m",Ret).call(this,i),a.current_tool_call_index!=null&&Ce(this,Nm,"m",Met).call(this,i,a.current_tool_call_index));for(let s of o.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(Ce(this,Nm,"m",Ret).call(this,i),a.current_tool_call_index!=null&&Ce(this,Nm,"m",Met).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))}}},Met=function(r,n){if(Ce(this,Nm,"m",xCe).call(this,r).done_tool_calls.has(n))return;let i=r.message.tool_calls?.[n];if(!i)throw new Error("no tool call snapshot");if(!i.type)throw new Error("tool call snapshot missing `type`");if(i.type==="function"){let a=Ce(this,L1,"f")?.tools?.find(s=>woe(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??Ltt.DEFAULT_TIMEOUT,this.logger=s.logger??console;let u="warn";this.logLevel=u,this.logLevel=eet(s.logLevel,"ClientOptions.logLevel",this)??eet(NC("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??Clr(),Fr(this,$Ce,Olr,"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 YQe(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${ik}`}defaultIdempotencyKey(){return`stainless-node-retry-${kQe()}`}makeStatusError(e,r,n,o){return Am.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 Ft?n:new Ft(`Failed to get token from 'apiKey' function: ${n.message}`,{cause:n})}if(typeof r!="string"||!r)throw new Ft(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,n){let o=!Ce(this,$tt,"m",Ccr).call(this)&&n||this.baseURL,i=plr(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return mlr(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 B2(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(Qc(this).debug(`[${l}] sending request`,j1({retryOfRequestLogID:n,method:o.method,url:s,options:o,headers:a.headers})),o.signal?.aborted)throw new Mc;let f=new AbortController,p=await this.fetchWithTimeout(s,a,u,f).catch(voe),m=Date.now();if(p instanceof globalThis.Error){let y=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new Mc;let b=_oe(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(r)return Qc(this).info(`[${l}] connection ${b?"timed out":"failed"} - ${y}`),Qc(this).debug(`[${l}] connection ${b?"timed out":"failed"} (${y})`,j1({retryOfRequestLogID:n,url:s,durationMs:m-d,message:p.message})),this.retryRequest(o,r,n??l);throw Qc(this).info(`[${l}] connection ${b?"timed out":"failed"} - error; no more retries left`),Qc(this).debug(`[${l}] connection ${b?"timed out":"failed"} (error; no more retries left)`,j1({retryOfRequestLogID:n,url:s,durationMs:m-d,message:p.message})),b?new dA:new nk({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 xlr(p.body),Qc(this).info(`${g} - ${E}`),Qc(this).debug(`[${l}] response error (${E})`,j1({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 _k(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 Ftt,kC,Ocr=v(()=>{cY();z0();mN();E6();cL();z4e();Ftt=class extends lL{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(qs(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 Ftt{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 eL(this.zodSchema,e);if(r.success)return r.data;throw new nh(`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 dto,lH=v(()=>{Do();Ocr();dto={};Tt(dto,{JsonOutputKeyToolsParser:()=>kC,JsonOutputToolsParser:()=>Ftt,convertLangChainToolCallToOpenAI:()=>_k,makeInvalidToolCall:()=>FC,parseToolCall:()=>LC})});var cH,Joe=v(()=>{tk();rk();boe();nCe();wA();Yu();A1();Gv();Ov();_O();lH();Zv();o_();cH=class extends bh{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??dn("OPENAI_API_KEY"),this.organization=e?.configuration?.organization??dn("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 Tcr=v(()=>{});function SA(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===dA.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===Mc.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=Koe(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=Koe(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=Koe(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=Koe(t,"MODEL_NOT_FOUND"):e=t,e}var dH=v(()=>{Tcr();wA()});function fto(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 Ecr(t,e){let r=lA(t);if(r==="system"&&uA(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=fto(i);a&&(yield a)}}return{role:"user",content:Array.from(n(t.contentBlocks))}}function Pcr(t){let e=qs(t)&&t.response_metadata?.model_provider==="openai";function*r(){let n=MC(()=>{try{let y=lA(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}
${ixe.prettifyError(m)}`),new G3(h,JSON.stringify(e))}else{let m=Nu(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 G3(h,JSON.stringify(e))}i=o}let a=aN(r),u=await Gl.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;k$(e)&&(f=e.id),!f&&Twt(a)&&(f=a.toolCall.id);let p=Nro({content:c,artifact:d,toolCallId:f,name:this.name,metadata:this.metadata});return await u?.handleToolEnd(p),p}},$rt=class extends Drt{constructor(e){super(e);M(this,"schema",mt.object({input:mt.string().optional()}).transform(e=>e.input))}call(e,r){let n=typeof e=="string"||e==null?{input:e}:e;return super.call(n,r)}},Lrt=class extends $rt{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=aN(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)}},Idr=class extends Drt{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=aN(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)}},Aro=class{getTools(){return this.tools}}});var krt=v(()=>{wA();Yu();Frt()});var Ndr=v(()=>{krt()});var jdr=v(()=>{Ov();Frt();ez()});var Ddr=v(()=>{Goe()});var fH=v(()=>{tk();rk();Joe();dH();Goe();kCe();qCe();Btt();Utt();ztt();Dcr();Htt();$cr();Vtt();Lcr();krt();Ndr();jdr();Ddr();wA()});var Ldr=S((JIa,$dr)=>{$dr.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 Dro,$ro,Fdr,kdr=v(()=>{Dro=L(Ldr(),1),$ro=Object.defineProperty,Fdr=(t,e)=>{for(var r in e)$ro(t,r,{get:e[r],enumerable:!0})}});var Lro,qrt,qdr=v(()=>{kdr();Yu();A2();YF();Lro={};Fdr(Lro,{JinaEmbeddings:()=>qrt});qrt=class extends MS{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||dn("JINA_API_KEY")||dn("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=RS(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 axe,Bdr=v(()=>{qdr();axe=class extends qrt{constructor(e){super(e),e?.baseUrl&&(this.baseUrl=e.baseUrl)}}});var I8,Udr=v(()=>{fH();I8=class extends wk{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(t
without CORS Error: `+Mo(n)+`
with CORS Error: `+Mo(o);throw new Error(i)}}}}});function Vdr(t){return t!==void 0&&tie.includes(t)?zdr[t]:void 0}var zdr,Hdr,tie,uxe=v(()=>{zdr={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"},Hdr={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},tie=Object.keys(zdr)});function Ou(t,e){if(e.length<Brt)Array.prototype.push.apply(t,e);else{let r=e.length;for(let n=0;n<r;n+=Brt)Array.prototype.push.apply(t,e.slice(n,n+Brt))}}function Zdr(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 Bro(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Uro(){return typeof process<"u"&&process.release&&process.release.name==="node"}function Gdr(){return BigInt(Math.floor(performance.now()*1e6))}function mH(t){return typeof t=="number"&&(t=BigInt(t)),t<Jdr?`${t}ns`:t<Kdr?`${t/Jdr}\u03BCs`:t<Wdr?`${t/Kdr}ms`:`${t/Wdr}s`}function BC(){return Bro()?Gdr():Uro()||typeof process<"u"&&typeof process?.hrtime?.bigint=="function"?process.hrtime.bigint():typeof performance<"u"?Gdr():BigInt(0)}function rie(){return`${kro}-${qro++}`}function N8(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 Xdr(t,e){return e[1]===t[1]?t[0]-e[0]:e[1]-t[1]}function j8(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 lxe(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 D8(t,e){return lxe(t,[e])[e]}fu
- `),Vro={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:
- ${Hro}`,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 Ydr(t){return{raw:Number(t),formatted:mH(t)}}function Qdr(t){if(t.id){if(typeof t.id!="string")throw Ir("DOCUMENT_ID_MUST_BE_STRING",typeof t.id);return t.id}return rie()}function zrt(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(z1(n)){let i=Vrt(n);if(!Array.isArray(o)||o.length!==i)throw Ir("INVALID_INPUT_VECTOR",r,i,o.length);continue}if($8(n)){if(!Array.isArray(o))return r;let i=Hrt(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=zrt(o,n);if(i)return r+"."+i;continue}if(typeof o!==n)return r}}}function efr(t){return t==="geopoint"}function z1(t){return typeof t=="string"&&/^vector\[\d+\]$/.test(t)}function $8(t){return typeof t=="string"&&Jro[t]}function Hrt(t){return Kro[t]}function Vrt(t){let e=Number(t.slice(7,-1));switch(!0){case isNaN(e):throw Ir("INVALID_VECTOR_VALUE",t);case e<=0:throw Ir("INVALID_VECTOR_SIZE",t);default:return e}}var Jro,Kro,nie=v(()=>{wh();ed();ed();Jro={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},Kro={"string[]":"string","number[]":"number","boolean[]":"boolean","enum[]":"enum"}});function tfr(){return{idToInternalId:new Map,internalIdToId:[],save:Wro,load:Gro}}function Wro(t){return{internalIdToId:t.internalIdToId}}function Gro(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 tu(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?tu(t,e.toString()):e}function IS(t,e){if(t.internalIdToId.length<e)throw new Error(`Invalid internalId ${e}`);return t.internalIdToId[e-1]}var NS=v(()=>{});function Xro(t,e){return{sharedInternalDocumentStore:e,docs:{},count:0}}function Yro(t,e){let r=tu(t.sharedInternalDocumentStore,e);return t.docs[r]}function Qro(t,e){let r=e.length,n=Array.from({length:r});for(let o=0;o<r;o++){let i=tu(t.sharedInternalDocumentStore,e[o]);n[o]=t.docs[i]}return n}function eno(t){return t.docs}function tno(t,e,r){let n=tu(t.sharedInternalDocumentStore,e);return typeof t.docs[n]<"u"?!1:(t.docs[n]=r,t.count++,!0)}function rno(t,e){let r=tu(t.sharedInternalDocumentStore,e);return typeof t.docs[r]>"u"?!1:(delete t.docs[r],t.count--,!0)}function nno(t){return t.count}function ono(t,e){let r=e;return{docs:r.docs,count:r.count,sharedInternalDocumentStore:t}}function ino(t){return{docs:t.docs,count:t.count}}function rfr(){return{create:Xro,get:Yro,getMultiple:Qro,getAll:eno,store:tno,remove:rno,count:nno,load:ono,save:ino}}var Jrt=v(()=>{NS()});function ofr(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),Ir("PLUGIN_CRASHED")}return r}var nfr,ifr=v(()=>{wh();nfr=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeLoad","afterLoad","afterCreate"]});function UC(t,e,r,n){if(t.some(_d))return(async()=>{for(let i of t)await i(e,r,n)})();for(let i of t)i(e,r,n)}function hH(t,e,r){if(t.some(_d))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}},hie=class Dnt extends Nmr{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 Dnt({...n,separators:Dnt.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 $nt=v(()=>{jmr()});var Dmr,EA,fOe,$mr=v(()=>{Zr();pH();Bt();Rmr();jt();yr();Dmr=L(wH());$nt();EA=require("obsidian");vb();fOe=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 pie(o.embeddingRequestsPerMin),this.embeddingBatchSize=o.embeddingBatchSize,this.checkpointInterval=8*this.embeddingBatchSize,Yl(async()=>{let i=ce();this.rateLimiter=new pie(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 EA.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 EA.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(()=>{H("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=bd.getModelName(r),o=hie.fromLanguage("markdown",{chunkSize:zz}),i=[];for(let a of e){let s=await this.app.vault.cachedRead(a);if(!s?.trim())continue;let u=this.app.metadataCache.getFileCache(a),l={title:a.basename,path:a.path,embeddingModel:n,ctime:a.stat.ctime,mtime:a.stat.mtime,tags:u?.tags?.map(d=>d.tag)??[],extension:a.extension,metadata:{...u?.frontmatter??{},created:eg(new Date(a.stat.ctime)).display,modified:eg(new Date(a.stat.mtime)).display}};(await o.createDocuments([s],[],{chunkHeader:`
NOTE TITLE: [[${l.title}]]
METADATA:${JSON.stringify(l.metadata)}
NOTE BLOCK CONTENT:
`,appendChunkOverlapHeader:!0})).forEach(d=>{d.pageContent.trim()&&i.push({content:d.pageContent,fileInfo:l})})}return i}getDocHash(e){return(0,Dmr.MD5)(e).toString()}async getFilesToIndex(e){let{inclusions:r,exclusions:n}=td(),o=this.app.vault.getMarkdownFiles();if(e)return o.filter(c=>cl(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(!cl(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 H([`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 EA.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 EA.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=M_(n.qaInclusions);o.length>0&&r.push(`Inclusions: ${o.join(", ")}`);let a=[...cie(this.app),...M_(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 EA.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 EA.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 EA.Notice("Indexing cancelled");return}e.length>0?new EA.Notice(`Indexing completed with ${e.length} errors. Check console for details.`):new EA.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 Cg={};Jn(Cg,{default:()=>V1});var gie,V1,$m=v(()=>{Yw();pH();jt();gie=require("obsidian");fie();Mmr();$mr();V1=class t{constructor(){this.embeddingsManager=bd.getInstance(),this.dbOps=new TA(app),this.indexOps=new fOe(app,this.dbOps,this.embeddingsManager),this.eventHandler=new dOe(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())}};Yl(()=>{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 Ro&&n.message.includes("Vault adapter not available")&&(r--,r>0)){await new Promise(o=>setTimeout(o,100));continue}new gie.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(),gie.Platform.isMobile&&ce().disableIndexOnMobile?(new gie.Notice("Indexing is disabled on mobile devices"),0):this.indexOps.indexVaultToVectorStore(e)}async clearIndex(){a
${e.join(`
`)}`)}}});var Y8,Jnt=v(()=>{Vnt();CA();yr();Bt();Y8=class t{constructor(){this.mentions=new Map,this.brevilabsClient=cc.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=Mo(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=Mo(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 PA.isImageUrl(s,app.vault))return n.push(s),{type:"image",url:s};if($Rt(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 Jmr,gOe,Kmr=v(()=>{Bt();Jmr=L(wH()),gOe=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)||(H("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,Jmr.MD5)(r).toString();return H("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)){H("Cache hit for PDF:",e.path);let o=await app.vault.adapter.read(n);return JSON.parse(o)}return H("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);H("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);H("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 J1(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 Wmr(t){let r=(t?.message||t?.toString()||"").match(/Try again in ([\d\w\s]+)/);return r?r[1]:"some time"}var bie=v(()=>{});var Gmr,bOe,Zmr,yOe,Xmr=v(()=>{Gmr=require("obsidian"),yOe=class{constructor(e){this.vault=e;uY(this,bOe)}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 Gmr.TFile?await this.vault.cachedRead(l):"";return{...u,content:c}}return u.type==="text"?{...u,content:u.text??""}:{...u,content:""}})),a=[...o];iwt(this,bOe,Zmr).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}};bOe=new WeakSet,Zmr=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 Ymr,Knt,_Oe,Wnt,Q8,_ie,Mk,vOe=v(()=>{Kmr();yie();Bt();bie();Ymr=require("obsidian");Xmr();Knt=class{constructor(){this.supportedExtensions=["md"]}async parseFile(e,r){return await r.read(e)}},_Oe=class{constructor(e){this.supportedExtensions=["pdf"];this.brevilabsClient=e,this.pdfCache=gOe.getInstance()}async parseFile(e,r){try{H("Parsing PDF file:",e.path);let n=await this.pdfCache.get(e);if(n)return H("Using cached PDF content for:",e.path),n.response;let o=await r.readBinary(e);H("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(){H("Clearing PDF cache"),await this.pdfCache.clear()}},Wnt=class{constructor(){this.supportedExtensions=["canvas"]}async parseFile(e,r){try{H("Parsing Canvas file:",e.path);let n=new yOe(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}]`}}},Q8=class Q8{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=zC.getInstance(),this.currentProject=r}static resetRateLimitNoticeTimer(){Q8.lastRateLimitNoticeTime=0}async parseFile(e,r){try{if(H(`[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 H(`[Docs4LLMParser] Project ${this.currentProject.name}: Using cached content for: ${e.path}`),n;H(`[Docs4LLMParser] Project ${this.currentProject.name}: Cache miss for: ${e.path}. Proceeding to API call.`);let o=await r.readBinary(e);H(`[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),H(`[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),J1(n)&&this.showRateLimitNotice(n),n}}showRateLimitNotice(e){let r=Date.now();if(r-Q8.lastRateLimitNoticeTime<6e4)return;Q8.lastRateLimitNoticeTime=r;let n=Wmr(e);new Ymr.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(){H("Cache clearing is now handled at the project level")}};Q8.lastRateLimitNoticeTime=0;_ie=Q8,Mk=class{constructor(e,r,n=!1,o=null){this.parsers=new Map;this.isProjectMode=n,this.currentProject=o,this.registerParser(new Knt),this.registerParser(new _ie(e,o)),n||this.registerParser(new _Oe(e)),this.registerParser(new Wnt)}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 _Oe&&await e.clearCache()}}});var eot={};Jn(eot,{createToolCallMarker:()=>SOe,decodeResultFromMarker:()=>Xnt,decodeToolCallMarkerResults:()=>rio,ensureEncodedToolCallMarkerResults:()=>wOe,parseToolCallMarkers:()=>Ynt,updateToolCallMarker:()=>Qnt});function Znt(t){try{return`ENC:${encodeURIComponent(t)}`}catch{return t}}function Xnt(t){if(typeof t!="string"||!t.startsWith("ENC:"))return t;try{return decodeURIComponent(t.slice(4))}catch{return t}}function tio(t){return`Tool '${t}' ${eio}`}function rio(t){return!t||typeof t!="string"?t:t.replace(/<!--TOOL_CALL_END:([^:]+):(ENC:[\s\S]*?)-->/g,(e,r,n)=>{let o=Xnt(n)||n;return`<!--TOOL_CALL_END:${r}:${o}-->`})}function wOe(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=Znt(n);return`<!--TOOL_CALL_END:${r}:${o}-->`})}function Gnt(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 Ynt(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);Gnt(_,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=Xnt(typeof m=="string"?m:""),b=(typeof g=="string"?g.length:0)>5e3?tio(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);Gnt(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&&Gnt(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 SOe(t,e,r,n,o="",i=!0,a="",s=""){let u=s&&Znt(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(()=>(vie(),eot)),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;H(`Final AI response (truncated):
`,h)}catch{let f=typeof e=="string"?e:String(e??""),p=f.length>d?f.slice(0,d)+"... (truncated)":f;H(`Final AI response (truncated):
`,p)}return e}async handleError(e,r){let n=Mo(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,e))}enhancedErrorMsg(e,r,n){let o=e.search("Troubleshooting URL");return e=o!==-1?e.slice(0,o):e,this.isAuthenticationError(n,r)&&(e=`Something went wrong. Please check if you have set your API key.
Path: Settings > copilot plugin > Basic Tab > Set Keys.
Or check model config
Error Details: `+e),e}isAuthenticationError(e,r){let n=e?.response,o=n?.data?.error??e?.error,i=n?.status??o?.status,a=typeof i=="string"?Number.parseInt(i,10):i,s=typeof o=="object"&&o!==null?o:void 0,u=(typeof s?.message=="string"?s.message:r).toLowerCase(),l=typeof s?.code=="string"?s.code.toLowerCase():"",c=typeof s?.type=="string"?s.type.toLowerCase():"";return a===401?!0:["api key","apikey","unauthorized","authentication","invalid authentication"].some(f=>u.includes(f)||l.includes(f)||c.includes(f))}}});var MA,Cie=v(()=>{Bt();MA=class{static convert(e,r={}){let{includeSystemMessage:n=!0,mergeUserContent:o=!0,debug:i=!1}=r,a=[],s=e.layers.find(f=>f.id==="L1_SYSTEM"),u=e.layers.find(f=>f.id==="L2_PREVIOUS"),l=e.layers.find(f=>f.id==="L3_TURN"),c=e.layers.find(f=>f.id==="L4_STRIP"),d=e.layers.find(f=>f.id==="L5_USER");if(n&&s&&s.text){let f=[s.text];u&&u.text&&(f.push(`
## Context Library
The following notes are available for reference:
`+u.text),i&&H("[LayerToMessagesConverter] Added L2 (cumulative context) to system")),a.push({role:"system",content:f.join(`
`)}),i&&H("[LayerToMessagesConverter] Added L1 (System) + L2 (Cumulative) as stable prefix")}if(c&&c.text&&i&&H("[LayerToMessagesConverter] L4 (Strip) found but skipped (using LangChain memory)"),o){let f=[];if(l&&l.segments.length>0&&u){let p=new Set(u.segments.map(g=>g.id)),m=[],h=[];for(let g of l.segments)p.has(g.id)?m.push(g.id):h.push(g);if(m.length>0||h.length>0){let g=[];m.length>0&&g.push(`Context attached to this message:
`+m.map(y=>`- ${y}`).join(`
`)+`
Find them in the Context Library in the system prompt above.`),h.length>0&&g.push(h.map(y=>y.content).join(`
`)),f.push(g.join(`
`)),i&&H(`[LayerToMessagesConverter] Added L3: ${m.length} references, ${h.length} new items`)}}else l&&l.text&&(f.push(l.text),i&&H("[LayerToMessagesConverter] Added L3 (all new context)"));f.length>0&&d&&d.text&&f.push(`---
[User query]:`),d&&d.text&&(f.push(d.text),i&&H("[LayerToMessagesConverter] Added L5 (user message)")),f.length>0&&a.push({role:"user",content:f.join(`
`)})}else l&&l.text&&a.push({role:"user",content:l.text}),d&&d.text&&a.push({role:"user",content:d.text});return i&&(H(`[LayerToMessagesConverter] Converted envelope to ${a.length} messages`),a.forEach((f,p)=>{let m=f.content.substring(0,100);H(` Message ${p+1} [${f.role}]: ${m}...`)})),a}static extractUserContent(e){let r=e.layers.find(i=>i.id==="L3_TURN"),n=e.layers.find(i=>i.id==="L5_USER"),o=[];return r&&r.text&&o.push(r.text),n&&n.text&&o.push(n.text),o.join(`
`)}static extractFullContext(e){let r=e.layers.find(a=>a.id==="L2_PREVIOUS"),n=e.layers.find(a=>a.id==="L3_TURN"),o=e.layers.find(a=>a.id==="L5_USER"),i=[];return r&&r.text&&i.push(r.text),n&&n.text&&i.push(n.text),o&&o.text&&i.push(o.text),i.join(`
`)}static extractSystemMessage(e){return e.layers.find(n=>n.id==="L1_SYSTEM")?.text||""}static getLayerHashes(e){return e.layerHashes}}});var vd,xH=v(()=>{vd=class t{constructor(){this.tools=new Map}static getInstance(){return t.instance||(t.instance=new t),t.instance}register(e){this.tools.set(e.metadata.id,e)}registerAll(e){e.forEach(r=>this.register(r))}getAllTools(){return Array.from(this.tools.values())}getEnabledTools(e,r){let n=[];for(let[o,i]of this.tools){let{metadata:a,tool:s}=i;if(a.isAlwaysEnabled){(!a.requiresVault||r)&&n.push(s);continue}e.has(o)&&(!a.requiresVault||r)&&n.push(s)}return n}getToolsByCategory(){let e=new Map;for(let r of this.tools.values()){let n=r.metadata.category;e.has(n)||e.set(n,[]),e.get(n).push(r)}return e}getConfigurableTools(){return Array.from(this.tools.values()).filter(e=>!e.metadata.isAlwaysEnabled)}getCopilotCommandMappings(){let e=new Map;for(let r of this.tools.values()){let n=r.metadata.copilotCommands;if(n)for(let o of n){let i=o.toLowerCase();e.has(i)||e.set(i,r)}}return e}getToolMetadata(e){return this.tools.get(e)?.metadata}clear(){this.tools.clear()}}});function nio(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 oio(t,e){let r=[];e&&(r.push(`msg:${e.messageId??"N/A"} | conv:${e.conversationId??"N/A"} | v${e.version}`),r.push(""));let n=vd.getInstance(),o=new Set(n.getAllTools().map(c=>c.tool.name)),i=c=>{let d=[],f=/<(\w+)>([\s\S]*?)<\/\1>/g,p;for(;(p=f.exec(c))!==null;){let m=p[1],h=p[2];if(o.has(m)){let g=h.length>200?h.substring(0,200).trim()+"...[truncated]":h.trim();d.push({tool:m,preview:g})}}return d},a=c=>typeof c.content=="string"?c.content:Array.isArray(c.content)?c.content.filter(f=>f.type==="text").map(f=>f.text).join(`
`):"",s=Array.isArray(t)?t:[],u=0;for(let c=0;c<s.length;c++){let d=s[c],f=a(d);if(d.role==="system"){r.push("\u2501\u2501\u2501 SYSTEM MESSAGE \u2501\u2501\u2501"),r.push("");let p=e?.layers.find(h=>h.id==="L1_SYSTEM"),m=e?.layers.find(h=>h.id==="L2_PREVIOUS");if(p&&f.includes(p.text)){let h=p.hash.substring(0,8);r.push(`\u{1F512} L1_SYSTEM (${h}) [CACHEABLE]`);let g=f.indexOf(p.text)+p.text.length,y=p.text.length>300?p.text.substring(0,300)+"...[truncated]":p.text;if(r.push(y),r.push(""),m&&m.text){let w=m.hash.substring(0,8);r.push(`\u{1F512} L2_PREVIOUS (${w}) [CACHEABLE]`);let x=m.text.length>300?m.text.substring(0,300)+"...[truncated]":m.text;r.push(x),r.push("")}let b=f.substring(g),_=i(b);if(_.length>0){r.push("--- PER-TURN ADDITIONS (not cached) ---"),r.push("");for(let w of _)r.push(`\u{1F4E6} TOOL: ${w.tool} (turn-specific RAG)`),r.push(w.preview),r.push("")}}else{let h=i(f);if(h.length>0){let g=f.match(/<(\w+)>/);if(g){let y=f.substring(0,g.index);if(y.trim()){let b=y.length>300?y.substring(0,300)+"...[truncated]":y;r.push(b),r.push("")}}r.push("--- PER-TURN ADDITIONS (not cached) ---"),r.push("");for(let y of h)r.push(`\u{1F4E6} TOOL: ${y.tool}`),r.push(y.preview),r.push("")}else{let g=f.length>300?f.substring(0,300)+"...[truncated]":f;r.push(g),r.push("")}}}else(d.role==="user"||d.role==="assistant")&&c<s.length-1&&u++}u>0&&(r.push("\u2501\u2501\u2501 CHAT HISTORY (L4) \u2501\u2501\u2501"),r.push(""),r.push(`${u} message(s)`),r.push(""));let l=s[s.length-1];if(l&&l.role==="user"){r.push("\u2501\u2501\u2501 USER MESSAGE \u2501\u2501\u2501"),r.push("");let c=a(l),d=i(c);if(d.length>0){r.push("--- PER-TURN TOOL RESULTS ---"),r.push("");for(let m of d)r.push(`\u{1F4E6} TOOL: ${m.tool}`),r.push(m.preview),r.push("")}let f=e?.layers.find(m=>m.id==="L3_TURN"),p=e?.layers.find(m=>m.id==="L5_USER");if(f&&f.text&&c.includes(f.text)){let m=f.hash.substring(0,8);r.push(`\u26A1 L3_TURN (${m})`);let h=f.text.length>300?f.text.substring(0,300)+"...[truncated]":f.text;r.push(h),r.push("")}if(p&&p.text&&c.includes(p.text)){let m=p.hash.substring(0,8);r.push(`\u26A1 L5_USER (${m})`),r.push(p.text),r.push("")}}return r.join(`
`)}function Rk(t){let{messages:e,modelName:r,contextEnvelope:n}=t;try{eG={timestamp:new Date().toISOString(),modelName:r,serializedMessages:nio(e),messagesArray:e,contextEnvelope:n}}catch{eG={timestamp:new Date().toISOString(),modelName:r,serializedMessages:String(e),messagesArray:e,contextEnvelope:n}}}function tG(){eG=null}async function COe(){if(!eG)return;let{timestamp:t,modelName:e,serializedMessages:r,messagesArray:n,contextEnvelope:o}=eG,i=[`### Prompt \u2014 ${t}${e?` \u2014 ${e}`:""}`,"","**Actual Messages Sent to LLM:**","","```json",r,"```",""],a=oio(n,o);i.push("**Layered Context Metadata:**"),i.push(""),i.push("```"),i.push(a),i.push("```"),i.push(""),Ihe(i),eG=null}var eG,W1=v(()=>{Bt();xH();eG=null});function Qmr(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 ehr(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 thr=v(()=>{});function iio(){return 1e4}function aio(t,e){let r=e??iio();if(!t||t.length<=r)return t;let n=t.substring(0,r),o=t.length-r;return`${n}
... (truncated ${o.toLocaleString()} characters)`}function sio(t,e,r){let n=aio(e,r);return`Tool '${t}' result: ${n}`}function tot(t,e=!1){return t.map(r=>e?sio(r.toolName,r.result):`Tool '${r.toolName}' result: ${r.result}`).join(`
`)}function uio(t){return`<errorChunk>${t}</errorChunk>`}function rG(t,e){let r=uio(t);return e?`${e}
${r}`:`
${r}`}var xOe=v(()=>{});var R_,OH=v(()=>{thr();xOe();R_=class{constructor(e,r,n=!1){this.updateCurrentAiMessage=e;this.modelAdapter=r;this.excludeThinking=n;this.hasOpenThinkBlock=!1;this.fullResponse="";this.errorResponse="";this.shouldTruncate=!1;this.wasTruncated=!1;this.tokenUsage=null}handleClaudeChunk(e){let r="",n=!1;for(let o of e)switch(o.type){case"text":r+=o.text;break;case"thinking":if(n=!0,this.excludeThinking)break;this.hasOpenThinkBlock||(this.fullResponse+=`
<think>`,this.hasOpenThinkBlock=!0),o.thinking!==void 0&&(this.fullResponse+=o.thinking),this.updateCurrentAiMessage(this.fullResponse);break}return r&&this.hasOpenThinkBlock&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),r&&(this.fullResponse+=r),n}handleDeepseekChunk(e){return typeof e.content=="string"&&(this.fullResponse+=e.content),e.additional_kwargs?.reasoning_content?(this.excludeThinking||(this.hasOpenThinkBlock||(this.fullResponse+=`
<think>`,this.hasOpenThinkBlock=!0),e.additional_kwargs.reasoning_content!==void 0&&(this.fullResponse+=e.additional_kwargs.reasoning_content)),!0):!1}handleOpenRouterChunk(e){return e.additional_kwargs?.delta?.reasoning?(this.excludeThinking||(this.hasOpenThinkBlock||(this.fullResponse+=`
<think>`,this.hasOpenThinkBlock=!0),this.fullResponse+=e.additional_kwargs.delta.reasoning),!0):(typeof e.content=="string"&&e.content&&this.hasOpenThinkBlock&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),typeof e.content=="string"&&e.content&&(this.fullResponse+=e.content),!1)}processChunk(e){if(this.shouldTruncate)return;Qmr(e).wasTruncated&&(this.wasTruncated=!0);let n=ehr(e);n&&(this.tokenUsage=n);let o=Array.isArray(e.content)||e.additional_kwargs?.delta?.reasoning||e.additional_kwargs?.reasoning_details&&Array.isArray(e.additional_kwargs.reasoning_details)&&e.additional_kwargs.reasoning_details.length>0||e.additional_kwargs?.reasoning_content;this.hasOpenThinkBlock&&!o&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),Array.isArray(e.content)?this.handleClaudeChunk(e.content):e.additional_kwargs?.reasoning_content?this.handleDeepseekChunk(e):o?this.handleOpenRouterChunk(e):this.handleDeepseekChunk(e),this.modelAdapter?.shouldTruncateStreaming?.(this.fullResponse)&&(this.shouldTruncate=!0,this.fullResponse=this.truncateToLastCompleteToolCall(this.fullResponse)),this.updateCurrentAiMessage(this.fullResponse)}truncateToLastCompleteToolCall(e){let r=e.lastIndexOf("</use_tool>");if(r===-1)return e;let n=e.substring(0,r+11);return this.modelAdapter?.sanitizeResponse?this.modelAdapter.sanitizeResponse(n,1):n}processErrorChunk(e){this.errorResponse=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 xie,rhr=v(()=>{Zr();Cie();Bt();jt();yr();Sie();W1();OH();Us();xie=class extends K1{async constructMessages(e){if(!e.contextEnvelope)throw new Error("[LLMChainRunner] Context envelope is required but not available. Cannot proceed with LLM chain.");H("[LLMChainRunner] Using envelope-based context");let n=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),o=z6(n),i=MA.convert(e.contextEnvelope,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),a=[],s=i.find(l=>l.role==="system");s&&a.push(s);for(let l of o)a.push({role:l.role,content:l.content});let u=i.find(l=>l.role==="user");if(u)if(e.content&&Array.isArray(e.content)){let l=e.content.map(c=>c.type==="text"?{...c,text:u.content}:c);a.push({role:"user",content:l})}else a.push(u);return a}async run(e,r,n,o,i){let a=ce(),s=Pv(),u=!1;try{u=!Qw(s,a.activeModels).capabilities?.includes("reasoning")}catch(f){H("Could not determine model capabilities, defaulting to include thinking blocks",f)}let l=new R_(n,void 0,u);try{let f=await this.constructMessages(e),m=this.chainManager.chatModelManager.getChatModel()?.modelName;Rk({messages:f,modelName:m,contextEnvelope:e.contextEnvelope}),H(`Final Request to AI:
`,f);let h=await ih(()=>this.chainManager.chatModelManager.getChatModel().stream(f,{signal:r.signal}));for await(let g of h){if(r.signal.aborted){H("Stream iteration aborted",{reason:r.signal.reason});break}l.processChunk(g)}}catch(f){f.name==="AbortError"||r.signal.aborted?H("Stream aborted by user",{reason:r.signal.reason}):await this.handleError(f,l.processErrorChunk.bind(l))}let c=l.close(),d={wasTruncated:c.wasTruncated,tokenUsage:c.tokenUsage??void 0};return r.signal.aborted&&r.signal.reason==="new-chat"?(n(""),""):(await this.handleResponse(c.content,e,r,o,n,void 0,void 0,d),c.content)}}});async function OOe(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 ih(async()=>{let i=await(await xg.instance.getCurrentChainManager().chatModelManager.getChatModelWithTemperature(0)).invoke([{role:"user",content:r.replace("{chat_history}",n).replace("{question}",t)}]),a=qz(i.content);return J6(a)})}var rot=v(()=>{Ik();yr()});var lio,TH,TOe=v(()=>{Do();H$();uO();Yh();lio={};Tt(lio,{BaseRetriever:()=>TH});TH=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(aN(r)),i=await(await Gl.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 oot,not,Nk,EOe=v(()=>{Bt();Zr();oot=require("obsidian");$nt();not={maxChars:zz,overlap:0,maxBytesTotal:10*1024*1024},Nk=class{constructor(e){this.app=e;this.cache=new Map;this.memoryUsage=0;this.splitter=hie.fromLanguage("markdown",{chunkSize:zz,chunkOverlap:0,separators:[`
`,`
`,". "," ",""],keepSeparator:!1})}async getChunks(e,r={}){try{if(!Array.isArray(e))return it("ChunkManager: Invalid notePaths provided"),[];if(e.length===0)return[];e.length>1e3&&(it("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 it("ChunkManager: No valid note paths provided"),[];let o={...not,...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):it(`ChunkManager: Skipping cache for ${a}, would exceed memory budget`)}i.push(...s)}return H(`ChunkManager: Retrieved ${i.length} chunks from ${n.length} notes (${this.formatMemoryUsage()})`),i}catch(n){return it("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||it(`ChunkManager: Chunk ${e} not found after regeneration`),o||null}async getValidatedChunks(e){let r=this.cache.get(e);if(!r&&(H(`ChunkManager: Cache miss for ${e}, regenerating...`),r=await this.regenerateChunks(e),!r||r.length===0))return it(`ChunkManager: Failed to regenerate chunks for ${e}`),[];let n=this.app.vault.getAbstractFileByPath(e);return n&&n instanceof oot.TFile&&r.length>0&&n.stat.mtime>r[0].mtime&&(H(`ChunkManager: File ${e} modified, regenerating chunks`),r=await this.regenerateChunks(e),!r||r.length===0)?(it(`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||"":(it(`ChunkManager: Chunk not in cache: ${e} (use async getChunkText for auto-regeneration)`),"")}async regenerateChunks(e){try{let r=await this.generateChunksForNote(e,not);if(r.length>0){let n=this.calculateChunkBytes(r);if(this.memoryUsage+n<=not.maxBytesTotal){let o=this.cache.get(e);o&&(this.memoryUsage-=this.calculateChunkBytes(o)),this.cache.set(e,r),this.memoryUsage+=n}else it(`ChunkManager: Cannot cache regenerated chunks for ${e}, would exceed memory budget`)}return r}catch(r){return it(`ChunkManager: Failed to regenerate chunks for ${e}`,r),[]}}clearCache(){this.cache.clear(),this.memoryUsage=0,H("ChunkManager: Cache cleared")}async generateChunksForNote(e,r){try{let n=this.app.vault.getAbstractFileByPath(e);if(!n||!(n instanceof oot.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 it(`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){it(`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 it(`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 iot=S(()=>{});function Og(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 Rc(){return Object.create(null)}function HC(t){return typeof t=="string"}function Tie(t){return typeof t=="object"}function Eie(t,e){if(HC(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 PH(t){t.F=null,t.B.clear(),t.D.clear()}function fot(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 AH);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 AH(t){this.limit=t&&t!==!0?t:1e3,this.cache=new Map,this.h=""}function uhr(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 uhr(e,o||0,i||e.length,!1)};if(n==="splice")return function(o,i){return uhr(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 VC(t=8){if(!this||this.constructor!==VC)return new VC(t);this.index=Rc(),this.h=[],this.size=0,t>32?(this.B=ghr,this.A=BigInt(t)):(this.B=hhr,this.A=t)}function JC(t=8){if(!this||this.constructor!==JC)return new JC(t);this.index=Rc(),this.h=[],this.size=0,t>32?(this.B=ghr,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=Rie(e),o=this.combineBaseAndTagTerms(r,n,e),i=new Set([e]);for(let s of o)if(!s.startsWith("#")&&s.length>=3){let u=BOe.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(),H("QueryExpander: Cache cleared")}getCacheSize(){return this.cache.size}async expandQueries(e){return(await this.expand(e)).queries}};zOe.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>`;UOe=zOe});var Aie,HOe,Rhr=v(()=>{Bt();vb();Aie=class Aie{constructor(e){this.app=e}async batchCachedReadGrep(e,r){let{inclusions:n,exclusions:o}=td(),a=this.app.vault.getMarkdownFiles().filter(d=>cl(d,n,o)),s=new Set,u=Aie.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){H(`GrepScanner: Skipping file ${p.path}: ${m}`)}})),d%Aie.CONFIG.YIELD_INTERVAL===0&&await new Promise(p=>setTimeout(p,0))}let c=Array.from(s).slice(0,r);return c.length>0&&H(` 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}}};Aie.CONFIG={BATCH_SIZE:30,YIELD_INTERVAL:100};HOe=Aie});var Pio,VOe,Ahr=v(()=>{Bt();Pio={enabled:!0,minDocsForBoost:2,maxBoostFactor:1.15,minRelevanceRatio:.4},VOe=class{constructor(e){this.config=Pio;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&&(H(`Folder boost: Boosting ${r.length} folders with significant relevance`),r.slice(0,5).forEach(n=>{let o=(n.relevanceRatio*100).toFixed(1);H(` ${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 Mio,JOe,Ihr=v(()=>{Bt();Mio={enabled:!0,maxCandidates:10,backlinkWeight:1,coCitationWeight:.5,sharedTagWeight:.3,boostStrength:.1,maxBoostMultiplier:1.2},JOe=class{constructor(e,r={}){this.metadataCache=e.metadataCache,this.config={...Mio,...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&&H(`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 Nio(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 au({content:[{type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}]}))}else e.push(new au({content:[{type:"tool_result",...r.content!=null?{content:Tot(r)}:{},tool_use_id:r.tool_call_id}]}));else e.push(r);return e}function ogr(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*jio(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){Qm(n)&&(yield oO(n,Zhr));let o="cache_control"in n?n.cache_control:void 0;if(n.type==="image_url"){let i;typeof n.image_url=="string"?i=ngr(n.image_url):typeof n.image_url=="object"&&n.image_url!==null&&"url"in n.image_url&&typeof n.image_url.url=="string"&&(i=ngr(n.image_url.url)),i&&(yield{type:"image",source:i,...o?{cache_control:o}:{}})}else{if(Ghr(n))return n;if(n.type==="document")yield{...n,...o?{cache_control:o}:{}};else if(Jhr(n))yield{type:"thinking",thinking:n.thinking,signature:n.signature,...o?{cache_control:o}:{}};else if(Khr(n))yield{type:"redacted_thinking",data:n.data,...o?{cache_control:o}:{}};else if(Whr(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 Tot(t){let{content:e}=t;return typeof e=="string"?e:Array.from(jio(e))}function ZOe(t){let e=Nio(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(qs(i)&&i.response_metadata?.output_version==="v1")return{role:a,content:tgr(i)};if(qs(i)&&i.tool_calls?.length){if(typeof i.content=="string")return i.content===""?{role:a,content:i.tool_calls.map(ogr)}:{role:a,content:[{type:"text",text:i.content},...i.tool_calls.map(ogr)]};{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:Tot(i)}}}else return{role:a,content:Tot(i)}});return{messages:Dio(o),system:r}}function Dio(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 Eot=v(()=>{Xhr();rgr();js()});function igr(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 Pot(t){let e;return t.status===400&&t.message.includes("tool")?e=XOe(t,"INVALID_TOOL_RESULTS"):t.status===401?e=XOe(t,"MODEL_AUTHENTICATION"):t.status===404?e=XOe(t,"MODEL_NOT_FOUND"):t.status===429?e=XOe(t,"MODEL_RATE_LIMIT"):e=t,e}var ugr=v(()=>{});function or(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 Ee(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 Z1=v(()=>{});var Mot,lgr=v(()=>{Mot=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return Mot=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 X1(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var Die,dG=v(()=>{Die=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 Xr,Sh,Tg,Lk,fG,pG,mG,hG,gG,yG,bG,_G,vG,WC=v(()=>{dG();Xr=class extends Error{},Sh=class t extends Xr{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:Die(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)}},Tg=class extends Sh{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Lk=class extends Sh{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 Sh{},mG=class extends Sh{},hG=class extends Sh{},gG=class extends Sh{},yG=class extends Sh{},bG=class extends Sh{},_G=class extends Sh{},vG=class extends Sh{}});function Iot(t){return typeof t!="object"?{}:t??{}}function dgr(t){if(!t)return!0;for(let e in t)return!1;return!0}function fgr(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var Lio,cgr,Rot,Aot,pgr,YOe,jH=v(()=>{WC();Lio=/^[a-z][a-z0-9+.-]*:/i,cgr=t=>Lio.test(t),Rot=t=>(Rot=Array.isArray,Rot(t)),Aot=Rot;pgr=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Xr(`${t} must be an integer`);if(e<0)throw new Xr(`${t} must be a positive integer`);return e},YOe=t=>{try{return JSON.parse(t)}catch{return}}});var mgr,hgr=v(()=>{mgr=t=>new Promise(e=>setTimeout(e,t))});var Fk,Not=v(()=>{Fk="0.65.0"});function Fio(){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 qio(){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+
`):[]}};tw=new WeakMap,rw=new WeakMap;Y1.NEWLINE_CHARS=new Set([`
`,"\r"]);Y1.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function Fie(){}function eTe(t,e,r){return!e||tTe[t]>tTe[r]?Fie:e[t].bind(e)}function Ch(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Hio;let n=Mgr.get(e);if(n&&n[0]===r)return n[1];let o={error:eTe("error",e,r),warn:eTe("warn",e,r),info:eTe("info",e,r),debug:eTe("debug",e,r)};return Mgr.set(e,[r,o]),o}var tTe,kot,Hio,Mgr,Q1,rTe=v(()=>{jH();tTe={off:0,error:200,warn:300,info:400,debug:500},kot=(t,e,r)=>{if(t){if(fgr(tTe,t))return t;Ch(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(tTe))}`)}};Hio={error:Fie,warn:Fie,info:Fie,debug:Fie},Mgr=new WeakMap;Q1=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*Vio(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Xr("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 Xr("Attempted to iterate over a response with no body");let r=new qot,n=new Y1,o=$ie(t.body);for await(let i of Jio(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*Jio(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"?Lie(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let i;for(;(i=Pgr(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function Kio(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var kie,RA,qot,Bot=v(()=>{Z1();WC();wG();Fot();wG();dG();jH();Lot();rTe();WC();RA=class t{constructor(e,r,n){this.iterator=e,kie.set(this,void 0),this.controller=r,or(this,kie,n,"f")}static fromSSEResponse(e,r,n){let o=!1,i=n?Ch(n):console;async function*a(){if(o)throw new Xr("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let s=!1;try{for await(let u of Vio(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 Sh(void 0,YOe(u.data)??u.data,void 0,e.headers)}s=!0}catch(u){if(X1(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 Y1,u=$ie(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 Xr("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(X1(u))return;throw u}finally{s||r.abort()}}return new t(a,r,n)}[(kie=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,Ee(this,kie,"f")),new t(()=>o(r),this.controller,Ee(this,kie,"f"))]}toReadableStream(){let e=this,r;return Dot({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=Lie(JSON.stringify(o)+`
`);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};qot=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]=Kio(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function nTe(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:o,startTime:i}=e,a=await(async()=>{if(e.options.stream)return Ch(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 Uot(d,r)}return await r.text()})();return Ch(t).debug(`[${n}] response parsed`,Q1({retryOfRequestLogID:o,url:r.url,status:r.status,body:a,durationMs:Date.now()-i})),a}function Uot(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 zot=v(()=>{Bot();rTe()});var qie,DH,oTe=v(()=>{Z1();zot();DH=class t extends Promise{constructor(e,r,n=nTe){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,qie.set(this,void 0),or(this,qie,e,"f")}_thenUnwrap(e){return new t(Ee(this,qie,"f"),this.responsePromise,async(r,n)=>Uot(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(Ee(this,qie,"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)}};qie=new WeakMap});var iTe,Hot,Bie,$S,kk=v(()=>{Z1();WC();zot();oTe();jH();Hot=class{constructor(e,r,n,o){iTe.set(this,void 0),or(this,iTe,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 Xr("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await Ee(this,iTe,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(iTe=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},Bie=class extends DH{constructor(e,r,n){super(e,r,async(o,i)=>new n(o,i.response,await nTe(o,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},$S=class extends Hot{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:{...Iot(this.options.query),before_id:r}}:null}let e=this.last_id;return e?{...this.options,query:{...Iot(this.options.query),after_id:e}}:null}}});function $H(t,e,r){return Jot(),new File(t,e??"unknown_file",r)}function Uie(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 Gio(t){let e=typeof t=="function"?t:t.fetch,r=Rgr.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 Rgr.set(e,n),n}var Jot,Kot,Agr,Rgr,Zio,Xio,Vot,aTe=v(()=>{wG();Jot=()=>{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},Ty=nao(Lgr)});var CG,Zot=v(()=>{AA();kk();IA();aTe();SG();CG=class extends wd{list(e={},r){let{betas:n,...o}=e??{};return this._client.getAPIList("/v1/files",$S,{query:o,...r,headers:Gi([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},r?.headers])})}delete(e,r={},n){let{betas:o}=r??{};return this._client.delete(Ty`/v1/files/${e}`,{...n,headers:Gi([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString()},n?.headers])})}download(e,r={},n){let{betas:o}=r??{};return this._client.get(Ty`/v1/files/${e}/content`,{...n,headers:Gi([{"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(Ty`/v1/files/${e}`,{...n,headers:Gi([{"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",Agr({body:o,...r,headers:Gi([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},r?.headers])},this._client))}}});var xG,Xot=v(()=>{AA();kk();IA();SG();xG=class extends wd{retrieve(e,r={},n){let{betas:o}=r??{};return this._client.get(Ty`/v1/models/${e}?beta=true`,{...n,headers:Gi([{...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",$S,{query:o,...r,headers:Gi([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers])})}}});var OG,Yot=v(()=>{WC();wG();Fot();OG=class t{constructor(e,r){this.iterator=e,this.controller=r}async*decoder(){let e=new Y1;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 Xr("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 Xr("Attempted to iterate over a response with no body");return new t($ie(e.body),r)}}});var zie=v(()=>{WC()});var TG,Qot=v(()=>{AA();kk();IA();Yot();zie();SG();TG=class extends wd{create(e,r){let{betas:n,...o}=e;return this._client.post("/v1/messages/batches?beta=true",{body:o,...r,headers:Gi([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}retrieve(e,r={},n){let{betas:o}=r??{};return this._client.get(Ty`/v1/messages/batches/${e}?beta=true`,{...n,headers:Gi([{"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",$S,{query:o,...r,headers:Gi([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},r?.headers])})}delete(e,r={},n){let{betas:o}=r??{};return this._client.delete(Ty`/v1/messages/batches/${e}?beta=true`,{...n,headers:Gi([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString()},n?.headers])})}cancel(e,r={},n){let{betas:o}=r??{};return this._client.post(Ty`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:Gi([{"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 Xr(`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:Gi([{"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 eit=v(()=>{Bot()});var sao,EG,uao,lao,uTe,tit=v(()=>{sao=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=yTe[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:Gi([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers]),stream:e.stream??!1})}stream(e,r){return gTe.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:Gi([{"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,cit=v(()=>{AA();Zot();Zot();Xot();Xot();lit();lit();jA=class extends wd{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 FH,dit=v(()=>{AA();IA();FH=class extends wd{create(e,r){let{betas:n,...o}=e;return this._client.post("/v1/complete",{body:o,timeout:this._client._options.timeout??6e5,...r,headers:Gi([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers]),stream:e.stream??!1})}}});function Wgr(t){return t.type==="tool_use"||t.type==="server_tool_use"}var FS,zk,Xie,_Te,Yie,Qie,vTe,eae,rj,tae,wTe,STe,AG,CTe,xTe,fit,Vgr,pit,mit,hit,git,Jgr,Kgr,OTe,Ggr=v(()=>{Z1();dG();zie();eit();tit();Kgr="__json_buf";OTe=class t{constructor(){FS.add(this),this.messages=[],this.receivedMessages=[],zk.set(this,void 0),this.controller=new AbortController,Xie.set(this,void 0),_Te.set(this,()=>{}),Yie.set(this,()=>{}),Qie.set(this,void 0),vTe.set(this,()=>{}),eae.set(this,()=>{}),rj.set(this,{}),tae.set(this,!1),wTe.set(this,!1),STe.set(this,!1),AG.set(this,!1),CTe.set(this,void 0),xTe.set(this,void 0),pit.set(this,e=>{if(or(this,wTe,!0,"f"),X1(e)&&(e=new Tg),e instanceof Tg)return or(this,STe,!0,"f"),this._emit("abort",e);if(e instanceof Xr)return this._emit("error",e);if(e instanceof Error){let r=new Xr(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new Xr(String(e)))}),or(this,Xie,new Promise((e,r)=>{or(this,_Te,e,"f"),or(this,Yie,r,"f")}),"f"),or(this,Qie,new Promise((e,r)=>{or(this,vTe,e,"f"),or(this,eae,r,"f")}),"f"),Ee(this,Xie,"f").catch(()=>{}),Ee(this,Qie,"f").catch(()=>{})}get response(){return Ee(this,CTe,"f")}get request_id(){return Ee(this,xTe,"f")}async withResponse(){let e=await Ee(this,Xie,"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")},Ee(this,pit,"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{Ee(this,FS,"m",mit).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)Ee(this,FS,"m",hit).call(this,u);if(s.controller.signal?.aborted)throw new Tg;Ee(this,FS,"m",git).call(this)}finally{o&&i&&o.removeEventListener("abort",i)}}_connected(e){this.ended||(or(this,CTe,e,"f"),or(this,xTe,e?.headers.get("request-id"),"f"),Ee(this,_Te,"f").call(this,e),this._emit("connect"))}get ended(){return Ee(this,tae,"f")}get errored(){return Ee(this,wTe,"f")}get aborted(){return Ee(this,STe,"f")}abort(){this.controller.abort()}on(e,r){return(Ee(this,rj,"f")[e]||(Ee(this,rj,"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=yTe[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 OTe.createMessage(this,e,r)}countTokens(e,r){return this._client.post("/v1/messages/count_tokens",{body:e,...r})}},Zgr={"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 kH,_it=v(()=>{AA();kk();IA();SG();kH=class extends wd{retrieve(e,r={},n){let{betas:o}=r??{};return this._client.get(Ty`/v1/models/${e}`,{...n,headers:Gi([{...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",$S,{query:o,...r,headers:Gi([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},r?.headers])})}}});var Xgr=v(()=>{jgr();cit();dit();bit();_it()});var rae,Ygr=v(()=>{rae=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 vit,wit,TTe,Qgr,eyr,tyr,dc,DA,Sit=v(()=>{Z1();lgr();jH();hgr();dG();jot();wG();xgr();Not();WC();kk();Got();Xgr();oTe();dit();_it();cit();bit();jot();IA();Ygr();rTe();jH();eyr="\\n\\nHuman:",tyr="\\n\\nAssistant:",dc=class{constructor({baseURL:e=rae("ANTHROPIC_BASE_URL"),apiKey:r=rae("ANTHROPIC_API_KEY")??null,authToken:n=rae("ANTHROPIC_AUTH_TOKEN")??null,...o}={}){vit.add(this),TTe.set(this,void 0);let i={apiKey:r,authToken:n,...o,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&_gr())throw new Xr(`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??wit.DEFAULT_TIMEOUT,this.logger=i.logger??console;let a="warn";this.logLevel=a,this.logLevel=kot(i.logLevel,"ClientOptions.logLevel",this)??kot(rae("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??wgr(),or(this,TTe,Cgr,"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 Gi([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return Gi([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return Gi([{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 Xr(`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-${Mot()}`}makeStatusError(e,r,n,o){return Sh.generate(e,r,n,o)}buildURL(e,r,n){let o=!Ee(this,vit,"m",Qgr).call(this)&&n||this.baseURL,i=cgr(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return dgr(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 Xr("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 DH(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(Ch(this).debug(`[${l}] sending request`,Q1({retryOfRequestLogID:n,method:o.method,url:s,options:o,headers:a.headers})),o.signal?.aborted)throw new Tg;let f=new AbortController,p=await this.fetchWithTimeout(s,a,u,f).catch(Die),m=Date.now();if(p instanceof globalThis.Error){let y=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new Tg;let b=X1(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(r)return Ch(this).info(`[${l}] connection ${b?"timed out":"failed"} - ${y}`),Ch(this).debug(`[${l}] connection ${b?"timed out":"failed"} (${y})`,Q1({retryOfRequestLogID:n,url:s,durationMs:m-d,messag
`);o.enqueue(s)}catch(i){o.error(i)}},async cancel(){await r.return?.()}})}},Nit=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]=Mao(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 Eg(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new Eg(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new Eg("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}};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 $it(t,e,r){if(t=await t,vyr(t))return t;if(_yr(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=pae(o)?[await o.arrayBuffer()]:[o];return new ETe(i,e,r)}let n=await Aao(t);if(e||(e=Nao(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new ETe(n,e,r)}async function Aao(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(pae(t))e.push(await t.arrayBuffer());else if(jao(t))for await(let r of t)e.push(r);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${Iao(t)}`);return e}function Iao(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function Nao(t){return jit(t.name)||jit(t.filename)||jit(t.path)?.split(/[\\/]/).pop()}var _yr,vyr,pae,Rao,jit,jao,Lit,zH,wyr,Dit,ITe=v(()=>{nae();nae();_yr=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",vyr=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&pae(t),pae=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",Rao=t=>vyr(t)||_yr(t)||Rit(t);jit=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},jao=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Lit=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody",zH=async t=>{let e=await wyr(t.body);return Pit(e,t)},wyr=async t=>{let e=new Tit;return await Promise.all(Object.entries(t||{}).map(([r,n])=>Dit(e,r,n))),e},Dit=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(Rao(r)){let n=await $it(r);t.append(e,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>Dit(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>Dit(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 Eyr(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):ATe.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 qao(){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 Jao(t){if(!t)return!0;for(let e in t)return!1;return!0}function Kao(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Tyr(t,e){for(let r in e){if(!Kao(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 $ao,Lao,NTe,DTe,$Te,Syr,kit,Fao,kao,Cyr,xyr,Oyr,Bao,Uao,z
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 VH(this),this.chat=new Jk(this),this.embeddings=new JH(this),this.audio=new $A(this),this.models=new WH(this),this.batches=new HH(this),this.files=new KH(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}`}}};Ayr=cu;cu.Groq=Ayr;cu.DEFAULT_TIMEOUT=6e4;cu.GroqError=Eg;cu.APIError=xh;cu.APIConnectionError=Vk;cu.APIConnectionTimeoutError=NG;cu.APIUserAbortError=UH;cu.NotFoundError=sae;cu.ConflictError=uae;cu.RateLimitError=cae;cu.BadRequestError=oae;cu.AuthenticationError=iae;cu.InternalServerError=dae;cu.PermissionDeniedError=aae;cu.UnprocessableEntityError=lae;cu.toFile=$it;cu.fileFromPath=PTe;cu.Completions=VH;cu.Chat=Jk;cu.Embeddings=JH;cu.Audio=$A;cu.Models=WH;cu.Batches=HH;cu.Files=KH;Iyr=cu});function oso(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 Dyr(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(!ud.isInstance(t))throw new Error("Invalid generic chat message");return oso(t);default:throw new Error(`Unknown message type: ${t.type}`)}}function jyr(t){return t.map(e=>{let r={role:Dyr(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 qs(e)&&e.tool_calls?.length?r.tool_calls=e.tool_calls.map(_k):(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 iso(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 ud(t.content||"",t.role??"unknown")}}function aso(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 vv({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 Nr({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 _v({content:i,additional_kwargs:a,name:t.name,response_metadata:d}):o==="tool"?new Iw({content:i,additional_kwargs:a,tool_call_id:t.tool_call_id,response_metadata:d}):new bv({content:i,role:o,response_metadata:d})}function sso(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 tso,rso,nso,Yit,$yr=v(()=>{o_();A1();js();gm();Yu();Zv();Nyr();Ov();_O();lH();R1();tso=["frequency_penalty","function_call","functions","logit_bias","logprobs","max_completion_tokens","max_tokens","n","parallel_tool_calls","presence_penalty","reasoning_format"
${Dat(this.cause)}`:this.toString()}};XC.SDKValidationError=jat;function Dat(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(`${Dat(c,e+1)}`)})}}}return t.issues.length&&o("\u2514\u2500*"),n.slice(1)}});var Lat=S(UA=>{"use strict";var qlo=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]}),Blo=UA&&UA.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Ulo=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"&&qlo(r,e,n[o]);return Blo(r,e),r}}();Object.defineProperty(UA,"__esModule",{value:!0});UA.ResponseValidationError=void 0;var zlo=Ulo(te()),Hlo=iEe(),Vlo=aEe(),$at=class extends Hlo.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 zlo.ZodError?`${this.rawMessage}
${(0,Vlo.formatZodError)(this.cause)}`:this.toString()}};UA.ResponseValidationError=$at});var kat=S(sEe=>{"use strict";Object.defineProperty(sEe,"__esModule",{value:!0});sEe.SDKError=void 0;var Jlo=iEe(),Fat=class extends Jlo.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"}};sEe.SDKError=Fat});var ir=S(Fm=>{"use strict";Object.defineProperty(Fm,"__esModule",{value:!0});Fm.jsonErr=Glo;Fm.json=Zlo;Fm.jsonl=Xlo;Fm.jsonlErr=Ylo;Fm.textErr=Qlo;Fm.text=eco;Fm.bytesErr=tco;Fm.bytes=rco;Fm.streamErr=nco;Fm.stream=oco;Fm.sseErr=ico;Fm.sse=aco;Fm.nilErr=sco;Fm.nil=uco;Fm.fail=lco;Fm.match=cco;Fm.unpackHeaders=uEe;var Klo=Lat(),$br=kat(),Lbr=Sd(),Fbr=UG(),kbr=Tat(),Wlo={jsonl:"application/jsonl",json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function Glo(t,e,r){return{...r,err:!0,enc:"json",codes:t,schema:e}}function Zlo(t,e,r){return{...r,enc:"json",codes:t,schema:e}}function Xlo(t,e,r){return{...r,enc:"jsonl",codes:t,schema:e}}function Ylo(t,e,r){return{...r,err:!0,enc:"jsonl",codes:t,schema:e}}function Qlo(t,e,r){return{...r,err:!0,enc:"text",codes:t,schema:e}}function eco(t,e,r){return{...r,enc:"text",codes:t,schema:e}}function tco(t,e,r){return{...r,err:!0,enc:"bytes",codes:t,schema:e}}function rco(t,e,r){return{...r,enc:"bytes",codes:t,schema:e}}function nco(t,e,r){return{...r,err:!0,enc:"stream",codes:t,schema:e}}function oco(t,e,r){return{...r,enc:"stream",codes:t,schema:e}}function ico(t,e,r){return{...r,err:!0,enc:"sse",codes:t,schema:e}}function aco(t,e,r){return{...r,enc:"sse",codes:t,schema:e}}function sco(t,e,r){return{...r,err:!0,enc:"nil",codes:t,schema:e}}function uco(t,e,r){return{...r,enc:"nil",codes:t,schema:e}}function lco(t){return{enc:"fail",codes:t}}function cco(...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:Wlo[d.enc];if(p&&(0,Fbr.matchResponse)(r,f,p)){a=d;break}else if(!p&&(0,Fbr.matchStatusCode)(r,f)){a=d;break}}if(!a)return[{ok:!1,error:new $br.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 $br.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:uEe(r.headers)}:null,...(0,kbr.isPlainObject)(i)?i:null,request$:n,response$:r,body$:u}:l?c={...o?.extraFields,...a.hdrs?{Headers:uEe(r.headers)}:null,[l]:i}:a.hdrs?c={...o?.extraFields,...a.hdrs?{Headers:uEe(r.headers)}:null,...(0,kbr.isPlainObject)(i)?i:null}:c=i,"err"in a){let d=qbr(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[qbr(c,d=>a.schema.parse(d),"Response validation failed",{request:n,response:r,body:u}),i]}}var dco=/, */;function uEe(t){let e={};for(let[r,n]of t.entries())e[r]=n.split(dco);return e}function qbr(t,e,r,n){try{return(0,Lbr.OK)(e(t))}catch(o){return(0,Lbr.ERR)(new Klo.ResponseValidationError(r,{cause:o,rawValue:t,rawMessage:r,...n}))}}});var ae=S(tq=>{"use strict";Object.defineProperty(tq,"__esModule",{value:!0});tq.invariant=fco;tq.remap=pco;tq.combineSignals=mco;tq.abortSignalAny=Bbr;tq.compactMap=hco;tq.allRequired=gco;var qat=class extends Error{constructor(e){super(e),this.name="InvariantError"}};function fco(t,e){if(!t)throw new qat(e)}function pco(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 mco(...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):Bbr(e)}}function Bbr(t){let e=new AbortController,r=e.signal;i
`)),e(i)}});var TAr=S(yj=>{"use strict";var KAo=yj&&yj.__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]}),WAo=yj&&yj.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),uRe=yj&&yj.__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"&&KAo(r,e,n[o]);return WAo(r,e),r}}();Object.defineProperty(yj,"__esModule",{value:!0});yj.agentsStream=nIo;var GAo=uRe(te()),ZAo=fr(),XAo=Tq(),Hae=uRe(ir()),YAo=ae(),QAo=Q(),xAr=ar(),eIo=nr(),OAr=uRe(Dt()),tIo=uRe(Un()),rIo=sr();function nIo(t,e,r){return new rIo.APIPromise(oIo(t,e,r))}async function oIo(t,e,r){let n=(0,QAo.safeParse)(e,b=>OAr.AgentsCompletionStreamRequest$outboundSchema.parse(b),"Input validation failed");if(!n.ok)return[n,{status:"invalid"}];let o=n.value,i=(0,ZAo.encodeJSON)("body",o,{explode:!0}),a=(0,eIo.pathToFunc)("/v1/agents/completions#stream")(),s=new Headers((0,YAo.compactMap)({"Content-Type":"application/json",Accept:"text/event-stream"})),u=await(0,xAr.extractSecurity)(t._options.apiKey),l=u==null?{}:{apiKey:u},c=(0,xAr.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 Hae.match(Hae.sse(200,GAo.instanceof(ReadableStream).transform(b=>new XAo.EventStream(b,_=>_.data==="[DONE]"?{done:!0}:{value:OAr.CompletionEvent$inboundSchema.parse(_)}))),Hae.jsonErr(422,tIo.HTTPValidationError$inboundSchema),Hae.fail("4XX"),Hae.fail("5XX"))(h,p,{extraFields:g});return y.ok?[y,{status:"complete",request:p,response:h}]:[y,{status:"complete",request:p,response:h}]}});var PAr=S(lRe=>{"use strict";Object.defineProperty(lRe,"__esModule",{value:!0});lRe.Agents=void 0;var iIo=CAr(),aIo=TAr(),sIo=Ac(),EAr=Sd(),dut=class extends sIo.ClientSDK{async complete(e,r){return(0,EAr.unwrapAsync)((0,iIo.agentsComplete)(this,e,r))}async stream(e,r){return(0,EAr.unwrapAsync)((0,aIo.agentsStream)(this,e,r))}};lRe.Agents=dut});var Vae=S(fut=>{"use strict";Object.defineProperty(fut,"__esModule",{value:!0});fut.isReadableStream=uIo;function uIo(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 IAr=S(bj=>{"use strict";var lIo=bj&&bj.__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]}),cIo=bj&&bj.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),AAr=bj&&bj.__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 WAe=S(KAe=>{"use strict";Object.defineProperty(KAe,"__esModule",{value:!0});KAe.parseRecordDef=void 0;var Ase=te(),O$r=om(),dHo=JAe(),fHo=FAe();function pHo(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===Ase.ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:(0,O$r.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:(0,O$r.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===Ase.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=(0,dHo.parseStringDef)(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===Ase.ZodFirstPartyTypeKind.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===Ase.ZodFirstPartyTypeKind.ZodBranded&&t.keyType._def.type._def.typeName===Ase.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=(0,fHo.parseBrandedDef)(t.keyType._def,e);return{...r,propertyNames:o}}}return r}KAe.parseRecordDef=pHo});var Xut=S(GAe=>{"use strict";Object.defineProperty(GAe,"__esModule",{value:!0});GAe.parseMapDef=void 0;var T$r=om(),mHo=WAe();function hHo(t,e){if(e.mapStrategy==="record")return(0,mHo.parseRecordDef)(t,e);let r=(0,T$r.parseDef)(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=(0,T$r.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}}}GAe.parseMapDef=hHo});var Yut=S(ZAe=>{"use strict";Object.defineProperty(ZAe,"__esModule",{value:!0});ZAe.parseNativeEnumDef=void 0;function gHo(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}}ZAe.parseNativeEnumDef=gHo});var Qut=S(XAe=>{"use strict";Object.defineProperty(XAe,"__esModule",{value:!0});XAe.parseNeverDef=void 0;function yHo(){return{not:{}}}XAe.parseNeverDef=yHo});var elt=S(YAe=>{"use strict";Object.defineProperty(YAe,"__esModule",{value:!0});YAe.parseNullDef=void 0;function bHo(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}YAe.parseNullDef=bHo});var QAe=S(Rq=>{"use strict";Object.defineProperty(Rq,"__esModule",{value:!0});Rq.parseUnionDef=Rq.primitiveMappings=void 0;var _Ho=om();Rq.primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function vHo(t,e){if(e.target==="openApi3")return E$r(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(qs(i)&&i.tool_calls?.length)return i.tool_calls.map(a=>({...a,id:mae(a.id??"")})).map(_k)},o=new Set;for(let i of t)"tool_call_id"in i&&typeof i.tool_call_id=="string"&&o.add(mae(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:mae(i.tool_call_id)}];if(qs(i)){if(a===void 0)return[{role:e(i.getType()),content:s}];{let u=a.filter(l=>o.has(mae(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 fWo(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=Qit(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??qTe().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 au({content:o})}}function pWo(t,e){if(!t.content&&!t.toolCalls)return e?new Nr({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??qTe().replace(/-/g,""),type:"function"})):void 0,n="assistant";t.role&&(n=t.role);let o=Qit(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 vv({content:o}):n==="assistant"?new Nr({content:o,tool_call_chunks:a,additional_kwargs:i,usage_metadata:e?{input_tokens:e.promptTokens,output_tokens:e.completionTokens,total_tokens:e.totalTokens}:void 0}):n==="tool"?new Iw({content:o,additional_kwargs:i,tool_call_id:r?.[0].id??""}):n==="function"?new _v({content:o,additional_kwargs:i}):new bv({content:o,role:n})}function mFr(t){if(!(!t||!t.length))return t.map(e=>{if("function"in e)return{type:e.type??"function",function:e.function};if(yg(e)){let r=e.description??`Tool: ${e.name}`;return{type:"function",function:{name:e.name,description:r,parameters:Ga(e.schema)?Hi(e.schema):e.schema}}}throw new Error(`Unknown tool type passed to ChatMistral: ${JSON.stringify(e,null,2)}`)})}var hFr,gFr,Klt,yFr=v(()=>{Fyr();Hyr();hFr=L(pFr(),1),gFr=L(UG(),1);js();A1();gm();nz();Yu();_O();lH();Ov();o_();R1();Zv();Klt=class extends bh{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??dn("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=
`):[]}};dw=new WeakMap;qV.NEWLINE_CHARS=new Set([`
`,"\r"]);qV.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function uct(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 BFr=v(()=>{});async function*MWo(t,e){if(!t.body)throw e.abort(),new Mr("Attempted to iterate over a response with no body");let r=new lct,n=new qV,o=uct(t.body);for await(let i of RWo(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*RWo(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=kFr(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function AWo(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var uI,lct,ZIe=v(()=>{Vse();cw();qFr();BFr();Bi();cw();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 MWo(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 Bm(void 0,s.error,void 0,cct(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 Bm(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 qV,s=uct(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 rct({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?.()}})}};lct=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]=AWo(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function pct(t,e,r){if(t=await t,zFr(t))return t;if(UFr(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=eue(o)?[await o.arrayBuffer()]:[o];return new VIe(i,e,r)}let n=await NWo(t);if(e||(e=DWo(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new VIe(n,e,r)}async function NWo(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(eue(t))e.push(await t.arrayBuffer());else if($Wo(t))for await(let r of t)e.push(r);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${jWo(t)}`);return e}function jWo(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function DWo(t){return dct(t.name)||dct(t.filename)||dct(t.path)?.split(/[\\/]/).pop()}var UFr,zFr,eue,IWo,dct,$Wo,mct,s0,HFr,fct,XIe=v(()=>{Vse();Vse();UFr=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",zFr=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&eue(t),eue=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",IWo=t=>zFr(t)||UFr(t)||ict(t);dct=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},$Wo=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",mct=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody",s0=async t=>{let e=await HFr(t.body);return nct(e,t)},HFr=async t=>{let e=new tct;return await Promise.all(Object.entries(t||{}).map(([r,n])=>fct(e,r,n))),e},fct=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(IWo(r)){let n=await pct(r);t.append(e,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>fct(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>fct(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 ZFr(t){let{response:e}=t;if(t.options.stream)return RD("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 RD("response",e.status,e.url,e.headers,a),XFr(a,e)}let i=await e.text();return RD("response",e.status,e.url,e.headers,i),i}function XFr(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 UWo(){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 YFr(t){if(!t)return!0;for(let e in t)return!1;return!0}function QFr(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function WFr(t,e){fo
\r `.includes(t[n]);)n++};return a()},kct=t=>n8o(t,Rh.ALL^Rh.NUM)});function i8o(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 Mr(`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 Mr(`missing role for choice ${d}`);if(h){let{arguments:_,name:w}=h;if(_==null)throw new Mr(`missing function_call.arguments for choice ${d}`);if(!w)throw new Mr(`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:I,...j}=x||{};if(E==null)throw new Mr(`missing choices[${d}].tool_calls[${w}].id
${fNe(t)}`);if(O==null)throw new Mr(`missing choices[${d}].tool_calls[${w}].type
${fNe(t)}`);if(I==null)throw new Mr(`missing choices[${d}].tool_calls[${w}].function.name
${fNe(t)}`);if(R==null)throw new Mr(`missing choices[${d}].tool_calls[${w}].function.arguments
${fNe(t)}`);return{...T,id:E,type:O,function:{...j,name:I,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 akr(u,e)}function fNe(t){return JSON.stringify(t)}var J9,hu,Um,jD,K9,qq,qct,cNe,Bct,Uct,zct,dNe,Hct,pkr,W9,Vct=v(()=>{cw();$ct();ZIe();due();fkr();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},hu=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(),Um.add(this),jD.set(this,void 0),K9.set(this,void 0),qq.set(this,void 0),J9(this,jD,e,"f"),J9(this,K9,[],"f")}get currentChatCompletionSnapshot(){return hu(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())),hu(this,Um,"m",qct).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)hu(this,Um,"m",Bct).call(this,a);if(i.controller.signal?.aborted)throw new im;return this._addChatCompletion(hu(this,Um,"m",dNe).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),hu(this,Um,"m",qct).call(this),this._connected();let o=uI.fromReadableStream(e,this.controller),i;for await(let a of o)i&&i!==a.id&&this._addChatCompletion(hu(this,Um,"m",dNe).call(this)),hu(this,Um,"m",Bct).call(this,a),i=a.id;if(o.controller.signal?.aborted)throw new im;return this._addChatCompletion(hu(this,Um,"m",dNe).call(this))}[(jD=new WeakMap,K9=new WeakMap,qq=new WeakMap,Um=new WeakSet,qct=function(){this.ended||J9(this,qq,void 0,"f")},cNe=function(r){let n=hu(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},hu(this,K9,"f")[r.index]=n,n)},Bct=function(r){if(this.ended)return;let n=hu(this,Um,"m",pkr).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=hu(this,Um,"m",cNe).call(this,i);i.finish_reason&&(hu(this,Um,"m",zct).call(this,i),a.current_tool_call_index!=null&&hu(this,Um,"m",Uct).call(this,i,a.current_tool_call_index));for(let s of o.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(hu(this,Um,"m",zct).call(this,i),a.current_tool_call_index!=null&&hu(this,Um,"m",Uct).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 WV(this),this.chat=new ID(this),this.embeddings=new GV(this),this.files=new Uq(this),this.images=new tJ(this),this.audio=new cI(this),this.moderations=new nJ(this),this.models=new Hq(this),this.fineTuning=new fx(this),this.vectorStores=new mw(this),this.beta=new dx(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 Qlt(e,{arrayFormat:"brackets"})}};Nkr=jo;jo.OpenAI=Nkr;jo.DEFAULT_TIMEOUT=6e5;jo.OpenAIError=Mr;jo.APIError=Bm;jo.APIConnectionError=Iq;jo.APIConnectionTimeoutError=Nq;jo.APIUserAbortError=im;jo.NotFoundError=Gse;jo.ConflictError=Zse;jo.RateLimitError=Yse;jo.BadRequestError=Jse;jo.AuthenticationError=Kse;jo.InternalServerError=Qse;jo.PermissionDeniedError=Wse;jo.UnprocessableEntityError=Xse;jo.toFile=pct;jo.fileFromPath=JIe;jo.Completions=WV;jo.Chat=ID;jo.ChatCompletionsPage=$q;jo.Embeddings=GV;jo.Files=Uq;jo.FileObjectsPage=YV;jo.Images=tJ;jo.Audio=cI;jo.Moderations=nJ;jo.Models=Hq;jo.ModelsPage=rJ;jo.FineTuning=fx;jo.VectorStores=mw;jo.VectorStoresPage=oJ;jo.VectorStoreSearchResponsesPage=iJ;jo.Beta=dx;jo.Batches=Lq;jo.BatchesPage=BV;jo.Uploads=Wq;jo.Responses=Kq;jo.Evals=mI;jo.EvalListResponsesPage=XV;jkr=jo});var CNe,$kr=v(()=>{js();gm();fH();Dkr();Bt();CNe=class extends qC{constructor(e){let{enableReasoning:r=!1,reasoningEffort:n,...o}=e;super(o),this.enableReasoning=r,this.reasoningEffort=n,this.openaiClient=new jkr({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 H(`OpenRouter reasoning enabled with effort: ${n}`),{...r,reasoning:{effort:n}}}else return H("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 Oi({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){it(`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){it(`parseEventStreamBuffer: Invalid payload bounds at offset ${o}`);break}if(u<e.length){let c=e.subarray(u,l),d=this.decodeUtf8(c).trim();d.length>0&&r.push(d)}if(o+=a,a===0)break}let i=o<e.length?e.subarray(o):new Uint8Array(0);return{messages:r,remainingBytes:i}}decodeEventStreamMessages(e){let{messages:r}=this.parseEventStreamBuffer(e);return r}buildChunkMetadata(e){let r={provider:"amazon-bedrock"};typeof e?.type=="string"&&(r.event_type=e.type),e?.index!==void 0&&(r.event_index=e.index);let n=this.extractStopReason(e);n&&(r.stop_reason=n);let o=this.extractUsage(e);return o&&(r.usage=o),r}extractStreamText(e){if(!e||typeof e!="object")return null;let r=[e.delta?.thinking,e.content_block_delta?.delta?.thinking,e.contentBlockDelta?.delta?.thinking,e.delta?.reasoning_content,e.reasoning_content];for(let i of r)if(typeof i=="string"&&i.length>0)return i;let n=[e.text,e.outputText,e.completion,e.resultText,e.delta];for(let i of n)if(typeof i=="string"&&i.length>0)return i;let o=[e.delta?.text,e.delta?.output_text,e.delta?.content,e.contentBlockDelta?.delta?.text,e.contentBlockDelta?.delta?.output_text,e.contentBlockDelta?.delta?.content,e.content_block_delta?.delta?.text,e.content_block_delta?.delta?.output_text,e.content_block_delta?.delta?.content,e.message?.content,e.messageStop?.message?.content,e.message_stop?.message?.content,e.content];for(let i of o){let a=this.extractTextFromCandidate(i);if(a)return a}return null}extractTextFromCandidate(e){if(!e)return null;if(typeof e=="string")return e.length>0?e:null;if(Array.isArray(e)){let r=e.map(n=>{if(typeof n=="string")return n;if(n&&typeof n=="object"){if(typeof n.text=="string")return n.text;if(typeof n.value=="string")return n.value;if(Array.isArray(n.content))return n.content.map(o=>typeof o?.text=="string"?o.text:"").join("")}return""}).join("");return r.length>0?r:null}if(typeof e=="object"){let r=e;if(typeof r.text=="string")return r.text.length>0?r.text:null;if(r.text&&typeof r.text=="object"){let n=this.extractTextFromCandidate(r.text);if(n)return n}if(typeof r.value=="string")return r.value.length>0?r.value:null;if(Array.isArray(r.content))return this.extractTextFromCandidate(r.content);if(r.delta){let n=this.extractTextFromCandidate(r.delta);if(n)return n}if(r.message&&typeof r.message=="object"){let n=this.extractTextFromCandidate(r.message);if(n)return n}}return null}extractUsage(e){if(!(!e||typeof e!="object")){if(e.usage&&typeof e.usage=="object")return e.usage;if(e.metrics&&typeof e.metrics=="object")return e.metrics;if(e["amazon-bedrock-invocationMetrics"]&&typeof e["amazon-bedrock-invocationMetrics"]=="object")return e["amazon-bedrock-invocationMetrics"];if(e.messageStop&&typeof e.messageStop=="object")return this.extractUsage(e.messageStop);if(e.message_stop&&typeof e.message_stop=="object")return this.extractUsage(e.message_stop)}}extractStopReason(e){if(!e||typeof e!="object")return;let r=e.stop_reason||e.stopReason||e.completionReason||e.completion_reason||e.reason||e.messageStop?.stopReason||e.message_stop?.stop_reason||(e.type==="message_stop"?e.reason:void 0);return typeof r=="string"?r:void 0}buildTerminalMetadataChunk(e,r){let n=r?this.normaliseUsageMetadata(r):void 0,o={provider:"amazon-bedrock"};e&&(o.stop_reason=e),r&&(o.usage=r);let i=new Nr({content:"",response_metadata:o,usage_metadata:n});return new Oi({message:i,text:"",generationInfo:o})}normaliseUsageMetadata(e){let r=this.coerceNumber(e.inputTokens)??this.coerceNumber(e.input_tokens)??this.coerceNumber(e.inputTokenCount)??this.coerceNumber(e.promptTokens)??this.coerceNumber(e.prompt_tokens)??0,n=this.coerceNumber(e.outputTokens)??
`)),i!==void 0&&(u.max_tokens=i),this.anthropicVersion&&(u.anthropic_version=this.anthropicVersion),this.enableThinking?(u.thinking={type:"enabled",budget_tokens:2048},u.temperature=1,H("[BedrockChatModel] Enabled thinking mode for Claude model with temperature=1")):a!==void 0&&(u.temperature=a),s!==void 0&&(u.top_p=s),u}normaliseMessageContent(e){let{content:r}=e;return typeof r=="string"?r:Array.isArray(r)?r.some(o=>typeof o=="object"&&o!==null&&(o.type==="image_url"||o.type==="image"))?r.map(o=>{if(typeof o=="string")return{type:"text",text:o};if(typeof o=="object"&&o!==null){if(o.type==="text"||o.type==="image_url"||o.type==="image")return o;if("text"in o&&typeof o.text=="string")return{type:"text",text:o.text};if("content"in o&&typeof o.content=="string")return{type:"text",text:o.content}}return null}).filter(o=>o!==null):r.map(o=>{if(typeof o=="string")return o;if(typeof o=="object"&&o!==null){if("text"in o&&typeof o.text=="string")return o.text;if("content"in o&&typeof o.content=="string")return o.content}return""}).join(""):typeof r=="object"&&r!==null&&"text"in r?r.text??"":""}extractText(e){return typeof e?.outputText=="string"?e.outputText:Array.isArray(e?.content)?e.content.map(r=>{if(!r)return"";if(typeof r=="string")return r;if(typeof r=="object"){if(typeof r.text=="string")return r.text;if(r.text&&typeof r.text=="object"&&"text"in r.text)return r.text.text??""}return""}).join(""):typeof e?.completion=="string"?e.completion:typeof e?.resultText=="string"?e.resultText:""}}});var kkr={};Jn(kkr,{default:()=>gI});var Fkr,I8o,rd,gI,bue=v(()=>{Us();Zr();Jz();Bt();jt();yr();zhr();syr();TYe();lyr();kYe();Lyr();vFr();eQe();fH();SFr();Yw();Fkr=require("obsidian");$kr();Lkr();I8o={openai:qC,"azure openai":qC,anthropic:Cit,cohereai:CYe,google:LYe,xai:Wlt,openrouterai:CNe,ollama:YYe,"lm-studio":qC,groq:Yit,"3rd party (openai-format)":qC,siliconflow:qC,"copilot-plus":qC,mistralai:Klt,deepseek:xit,"amazon-bedrock":xNe},rd=class rd{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,siliconflow:()=>ce().siliconflowApiKey};this.buildModelMap(),Yl(()=>{this.buildModelMap(),this.validateCurrentModel()})}static getInstance(){return rd.instance||(rd.instance=new rd),rd.instance}getTemperatureForModel(e,r,n){if(!e.isThinkingEnabled)return e.isOSeries||e.isGPT5?rd.REASONING_MODEL_TEMPERATURE:r.temperature??n.temperature}async getModelConfig(e){let r=ce(),n=e.name,o=H6(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 wi(e.apiKey||r.openAIApiKey),configuration:{baseURL:e.baseUrl,fetch:e.enableCors?Ql:void 0,organization:await wi(e.openAIOrgId||r.openAIOrgId)},...this.getOpenAISpecialConfig(n,e.maxTokens??r.maxTokens,e.temperature??r.temperature,e)},anthropic:{anthropicApiKey:await wi(e.apiKey||r.anthropicApiKey),model:n,anthropicApiUrl:e.baseUrl,clientOptions:{defaultHeaders:{"anthropic-dangerous-direct-browser-access":"true"},fetch:e.enableCors?Ql:void 0},...i&&{thinking:{type:"enabled",budget_tokens:rd.ANTHROPIC_THINKING_BUDGET_TOKENS}}},"azure openai":{modelName:e.azureOpenAIApiDeploymentName||r.azureOpenAIApiDeploymentName,apiKey:await wi(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.azureOpenAIA
without CORS Error: `+Mo(n)+`
with CORS Error: `+Mo(o);throw new Error(i)}}}findModelByName(e){return ce().activeModels.find(n=>n.name===e)}};rd.ANTHROPIC_THINKING_BUDGET_TOKENS=2048,rd.REASONING_MODEL_TEMPERATURE=1;gI=rd});var ONe={};Jn(ONe,{TieredLexicalRetriever:()=>aJ});async function N8o(){try{if(!xdt){let e=await Promise.resolve().then(()=>(bue(),kkr));xdt=()=>e.default.getInstance()}return xdt().getChatModel()}catch{return null}}var Odt,xdt,aJ,m7=v(()=>{Bt();jt();vb();yr();G8();TOe();Odt=require("obsidian");EOe();GOe();xdt=null;aJ=class extends TH{constructor(r,n){super();this.app=r;this.options=n;this.lc_namespace=["tiered_lexical_retriever"];this.searchCore=new WOe(r,N8o),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=mL(r,this.app.vault),i=o.map(p=>p.basename),a=this.resolveTagTerms(r);if(this.options.returnAllTags&&a.length>0)return this.getAllTagDocuments(a,r,o);let s=[...new Set([...this.options.salientTerms,...i])];ce().debug&&H("TieredLexicalRetriever: Starting search",{query:r,salientTerms:s,maxK:this.options.maxK});let u=ce(),l=await this.searchCore.retrieve(r,{maxResults:this.options.returnAllTags?Lm: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&&H("TieredLexicalRetriever: Search complete",{totalResults:f.length,titleMatches:c.length,searchResults:l.length}),f}catch(o){return it("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&&H("TieredLexicalRetriever: Generated daily note titles",{startTime:new Date(n).toISOString(),endTime:new Date(o).toISOString(),titlesCount:i.length,firstTitle:i[0],lastTitle:i[i.length-1]});let a=i.join(", "),s=mL(a,this.app.vault).filter(h=>!K8(h)),l=(await this.getTitleMatches(s)).map(h=>(h.metadata.includeInContext=!0,h)),c=this.app.vault.getMarkdownFiles().filter(h=>!K8(h)),d=[],f=this.options.returnAll?Lm:Math.min(this.options.maxK,Lm);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 Dm({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){it(`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&&H("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:Lm,candidateLimit:Lm,salientTerms:r,enableLexicalBoosts:i.enableLexicalBoost
Question: {question}
Passage:`)}async getRelevantDocuments(r,n){return ih(async()=>{let o=mL(r,app.vault),i=o.map(h=>h.basename),a=[...new Set([...this.options.salientTerms,...i])],s=await this.getExplicitChunks(o),u=r;n?.runName!=="no_hyde"&&(u=await this.rewriteQuery(r));let l=await this.getOramaChunks(u,a,this.options.textWeight),c=this.filterAndFormatChunks(l,s),d=c;if(c.length===0)return 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 cc.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 khe(async()=>{let n=await this.queryRewritePrompt.format({question:r}),o=await ih(async()=>(await xg.instance.getCurrentChainManager().chatModelManager.getChatModelWithTemperature(0)).invoke(n));if(o&&"content"in o){let i=qz(o.content);return J6(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 V1.getInstance().getDb(),a=await TA.getDocsByPath(i,o.path);if(a){let s=a.map(u=>new Dm({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 V1.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);H("Daily note date range:",d[0],d[d.length-1]);let f=mL(d.join(", "),app.vault),m=(await this.getExplicitChunks(f)).map(_=>({..._,metadata:{..._.metadata,includeInContext:!0}}));H("Modified time range:",l,c),s.where={mtime:{between:[l,c]}};let g=(await P_(a,s)).hits.map(_=>new Dm({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)}H(`Orama search params:
`,s);let u=await P_(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 Dm({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 bd.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 Edt={};Jn(Edt,{MergedSemanticRetriever:()=>vue});var Xq,vue,ENe=v(()=>{TNe();GOe();m7();G8();TOe();Xq=class Xq extends TH{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?Lm:Math.min(this.originalMaxK*2,Lm),i={...n,maxK:o,returnAll:this.returnAll,returnAllTags:n.returnAllTags,tagTerms:n.tagTerms};this.lexicalRetriever=new aJ(r,i);let a=this.returnAll?Lm:Math.min(this.originalMaxK*2,Lm);this.semanticRetriever=new _ue({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?Lm: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"?Xq.LEXICAL_WEIGHT:Xq.SEMANTIC_WEIGHT,s=i*a;return n==="lexical"&&this.hasTagMatch(o)&&(s*=Xq.TAG_MATCH_BOOST),o.score=s,o.rerank_score=s,new Dm({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}};Xq.LEXICAL_WEIGHT=1,Xq.SEMANTIC_WEIGHT=1,Xq.TAG_MATCH_BOOST=1.1;vue=Xq});function Ukr(t,e=!0){return e?`
<guidance>
${Bkr}
IMAGE INCLUSION:
When the retrieved documents contain relevant images (in formats like ![alt](image.png) or ![[image.png]]), include them in your response at appropriate locations using their exact original markdown format from the source.
Source Catalog (for reference only):
${t.join(`
`)}
</guidance>`:`
<guidance>
IMAGE INCLUSION:
When the retrieved documents contain relevant images (in formats like ![alt](image.png) or ![[image.png]]), include them in your response at appropriate locations using their exact original markdown format from the source.
Source Catalog (for reference only):
${t.join(`
`)}
</guidance>`}function zkr(t,e=!0){return e?`
${Bkr}
Source Catalog (for reference only):
${t}`:""}function PNe(t,e,r=!0){if(!r||!e?.length||!t)return t||"";if($8o(t))return t;let n=e.slice(0,D8o).map((o,i)=>{let a=(o.title||o.path||"Untitled").replace(/^\[\[|\]\]$/g,"");return`[^${i+1}]: [[${a}]]`}).join(`
`);return`${t}
#### Sources:
${n}`}function MNe(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 $8o(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 Hkr(t){let e=t||"";return/\[\^\d+\]/.test(e)}function Vkr(t=!0){return t?`
${j8o}`:""}function L8o(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 F8o(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 k8o(t){return t.split(`
`).map(e=>e.trim()).filter(e=>/^\[\^\d+\]:/.test(e))}function q8o(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 B8o(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 U8o(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 z8o(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 H8o(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 V8o(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function J8o(t){return t!=null}function K8o(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=V8o(i),r.push({index:r.length+1,html:u})}),r}function qkr(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 Jkr(t,e=!0){if(!e)return t;let r=L8o(t);if(!r)return t;let{mainContent:n,sourcesBlock:o}=r;o=F8o(o);let i=k8o(o);if(i.length===0){let d=K8o(o);return qkr(n,d)}let a=q8o(n,i);n=B8o(n,a);let s=U8o(o,a),{uniqueItems:u,consolidationMap:l}=z8o(s);l.size>0&&(n=H8o(n,l),s=u);let c=s.map((d,f)=>d?{index:f+1,html:d}:null).filter(J8o);return qkr(n,c)}function RNe(t){return t.map(e=>{let r=e.title||e.path||"Untitled",n=e.path||r;return`- [[${r}]] (${n})`})}var Bkr,j8o,D8o,wue=v(()=>{Bkr=`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)`,j8o=`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`;D8o=20});var Sue,Kkr=v(()=>{Zr();rot();Cie();Bt();m7();ENe();_ot();jt();yr();Sie();wue();W1();OH();Us();Sue=class extends K1{async run(e,r,n,o,i){let a=ce(),s=Pv(),u=!1;try{u=!Qw(s,a.activeModels).capabilities?.includes("reasoning")}catch(p){H("Could not determine model capabilities, defaulting to include thinking blocks",p)}let l=new R_(n,void 0,u);try{let p=e.contextEnvelope;if(!p)throw new Error("[VaultQA] Context envelope is required but not available. Cannot proceed with VaultQA chain.");let h=p.layers.find(ee=>ee.id==="L5_USER")?.text||e.message,g=this.extractTagTerms(h);H("[VaultQA] Extracted tags before condensing:",g);let b=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),_=z6(b),w=h;_.length>0&&(H("[VaultQA] Condensing query with chat history for better retrieval"),w=await OOe(h,_),H("[VaultQA] Standalone question:",w));let x=ce(),O={minSimilarityScore:.01,maxK:x.maxSourceChunks,salientTerms:g.length>0?[...g]:[],timeRange:void 0,textWeight:void 0,returnAll:!1,useRerankerThreshold:void 0},T=await(x.enableSemanticSearchV3?new vue(app,{...O,returnAll:g.length>0,returnAllTags:g.length>0,tagTerms:g}):new aJ(app,{...O,returnAll:g.length>0,returnAllTags:g.length>0,tagTerms:g})).getRelevantDocuments(w);this.chainManager.storeRetrieverDocuments(T);let R=T.map(ee=>{let ie=ee.metadata?.title||"Untitled",Z=ee.metadata?.path||ie;return`<${N2e}>
<title>${ie}</title>
<path>${Z}</path>
<content>
${MNe(ee.pageContent)}
</content>
</${N2e}>`}).join(`
`),I=[],j=this.chainManager.chatModelManager.getChatModel(),F=T.slice(0,Math.max(5,Math.min(20,T.length))).map(ee=>({title:ee.metadata?.title||ee.metadata?.path||"Untitled",path:ee.metadata?.path||ee.metadata?.title||""})),B=RNe(F).join(`
`),U=`
Answer the question based only on the following context:
`+R+zkr(B,x.enableInlineCitations);H("[VaultQA] Using envelope-based context construction with LayerToMessagesConverter");let J=MA.convert(p,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),G=J.find(ee=>ee.role==="system");G&&I.push({role:kz(j),content:G.content});for(let ee of _)I.push({role:ee.role,content:ee.content});let oe=J.find(ee=>ee.role==="user");if(oe){let ee=U+`
`+oe.content;if(e.content&&Array.isArray(e.content)){let ie=e.content.map(Z=>Z.type==="text"?{...Z,text:ee}:Z);I.push({role:"user",content:ie})}else I.push({role:"user",content:ee})}let ne=j?.modelName;Rk({messages:I,modelName:ne,contextEnvelope:e.contextEnvelope}),H(`Final Request to AI:
`,I);let z=await ih(()=>this.chainManager.chatModelManager.getChatModel().stream(I,{signal:r.signal}));for await(let ee of z){if(r.signal.aborted){H("VaultQA stream iteration aborted",{reason:r.signal.reason});break}l.processChunk(ee)}}catch(p){p.name==="AbortError"||r.signal.aborted?H("VaultQA stream aborted by user",{reason:r.signal.reason}):await this.handleError(p,l.processErrorChunk.bind(l))}let c=l.close(),d={wasTruncated:c.wasTruncated,tokenUsage:c.tokenUsage??void 0};if(r.signal.aborted&&r.signal.reason==="new-chat")return n(""),"";let f=this.addSourcestoResponse(c.content);return await this.handleResponse(f,e,r,o,n,void 0,void 0,d),f}addSourcestoResponse(e){let r=ce();if(!Hkr(e))return e;let n=this.chainManager.getRetrievedDocuments(),o=jRt(n).map(i=>({title:i}));return PNe(e,o,r.enableInlineCitations)}extractTagTerms(e){return Rie(e)}}});var h7,ANe=v(()=>{h7=["@vault","@websearch","@composer","@memory"]});function px(){}function Wkr(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 Gkr(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 Zkr(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 Pdt(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 Mdt(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 Cue(t,e){return Pdt(t,e,"")}function INe(t,e){return Mdt(t,e,"")}function Xkr(t,e){return e.slice(0,W8o(t,e))}function W8o(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 Qkr(t,e,r){return r?.ignoreWhitespace!=null&&!r.ignoreWhitespace?Z8o(t,e,r):Oue.diff(t,e,r)}function Ykr(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=Gkr(o,a);t.value=Mdt(t.value,a,u),e.value=Cue(e.value,u),r.value=Cue(r.value,u)}if(n){var l=Zkr(i,s);n.value=Pdt(n.value,s,l),e.value=INe(e.value,l),r.value=INe(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=Gkr(c,d);e.value=Cue(e.value,p);var m=Zkr(Cue(c,p),f);e.value=INe(e.value,m),n.value=Pdt(n.value,c,m),t.value=Mdt(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=Xkr(g,h);e.value=INe(e.value,y)}else if(t){var b=t.value.match(/\s*$/)[0],_=e.value.match(/^\s*/)[0],w=Xkr(b,_);e.value=Cue(e.value,w)}}function Z8o(t,e,r){return eqr.diff(t,e,r)}function X8o(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 tqr(t,e,r){var n=X8o(r,{ignoreWhitespace:!0});return jNe.diff(t,e,n)}function Rdt(t){"@babel/helpers - typeof";return Rdt=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},Rdt(t)}function Adt(t,e,r,n,o){e=e||[],r=r||[],n&&(t=n(o,t));var i;for(i=0;i<e.l
`));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};jNe.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))),px.prototype.equals.call(this,t,e,r)};Y8o=new px;Y8o.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};Q8o=new px;Q8o.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};xue=new px;xue.useLongestToken=!0;xue.tokenize=jNe.tokenize;xue.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(Adt(t,null,null,o),o," ")};xue.equals=function(t,e,r){return px.prototype.equals.call(xue,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"),r)};Idt=new px;Idt.tokenize=function(t){return t.slice()};Idt.join=Idt.removeEmpty=function(t){return t}});function rqr(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 nqr=v(()=>{});var LD,Hn,oqr,iqr,Tue,DNe,aqr,eGo,jdt=v(()=>{Zn();Bt();Ndt();In();LD=require("obsidian"),Hn=L(X()),oqr=L(Sm());Fo();iqr=L(X());nqr();yr();Tue="obsidian-copilot-apply-view",DNe=class extends LD.ItemView{constructor(r){super(r);this.root=null;this.state=null;this.result=null}getViewType(){return Tue}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,oqr.createRoot)(n)),this.root.render(Hn.default.createElement(eGo,{app:this.app,state:this.state,close:o=>{this.result=o,this.leaf.detach()}}))}},aqr=(0,Hn.memo)(({oldLine:t,newLine:e})=>{let r=Qkr(t,e);return Hn.default.createElement(Hn.default.Fragment,null,r.map((n,o)=>n.added?Hn.default.createElement("span",{key:o,className:"tw-text-success"},n.value):n.removed?Hn.default.createElement("span",{key:o,className:"tw-text-error tw-line-through"},n.value):Hn.default.createElement("span",{key:o},n.value)))});aqr.displayName="WordDiff";eGo=({app:t,state:e,close:r})=>{let[n,o]=(0,iqr.useState)(()=>e.changes.map(m=>({...m,accepted:null}))),i=rqr(n),a=(0,Hn.useRef)([]);if(!e||!e.changes)return ue("Invalid state:",e),Hn.default.createElement("div",{className:"tw-flex tw-h-full tw-flex-col tw-items-center tw-justify-center"},Hn.default.createElement("div",{className:"tw-text-error"},"Error: Invalid state - missing changes"),Hn.default.createElement(we,{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 LD.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 LD.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 Qh(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 LD.TFile)?(ue("Error in getting file",e.path),new LD.Notice("Failed to create file"),!1):(await t.vault.modify(g,h),new LD.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 Hn.default.createElement("div",{className:"tw
`).replace(/\r/g,`
`)}function nGo(t,e,r){let n=(t.match(/\r\n/g)||[]).length,o=(t.match(/(?<!\r)\n/g)||[]).length,i=n>o,a=Eue(t),s=Eue(e),u=Eue(r),l=a.replaceAll(s,u);return i?l.replace(/\n/g,`\r
`):l}function oGo(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 g7,tGo,LNe,rGo,cqr,Ddt=v(()=>{g7=require("obsidian");jdt();Ndt();yI();mx();yr();tGo=mt.object({path:mt.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:mt.union([mt.string(),mt.object({}).passthrough()]).describe(`(Required) The content to write to the file. Can be either a string or an object.
ALWAYS provide the COMPLETE intended content of the file, without any truncation or omissions.
You MUST include ALL parts of the file, even if they haven't been modified.
# For string content
* Use when writing text files like .md, .txt, etc.
# For object content
* Use when writing structured data files like .json, .canvas, etc.
* The object will be automatically converted to JSON string format
# Canvas JSON Format (JSON Canvas spec 1.0)
Required node fields: id, type, x, y, width, height
Node types: "text" (needs text), "file" (needs file), "link" (needs url), "group" (optional label)
Optional node fields: color (hex #FF0000 or preset "1"-"6"), subpath (file nodes, starts with #)
Required edge fields: id, fromNode, toNode
Optional edge fields: fromSide/toSide ("top"/"right"/"bottom"/"left"), fromEnd/toEnd ("none"/"arrow"), color, label
All IDs must be unique. Edge nodes must reference existing node IDs.
Example:
{
"nodes": [
{"id": "1", "type": "text", "text": "Hello", "x": 0, "y": 0, "width": 200, "height": 50},
{"id": "2", "type": "file", "file": "note.md", "subpath": "#heading", "x": 250, "y": 0, "width": 200, "height": 100, "color": "2"},
{"id": "3", "type": "group", "label": "Group", "x": 0, "y": 100, "width": 300, "height": 150}
],
"edges": [
{"id": "e1-2", "fromNode": "1", "toNode": "2", "fromSide": "right", "toSide": "left", "color": "3", "label": "links to"}
]
}`),confirmation:mt.preprocess(t=>{if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t},mt.boolean()).optional().default(!0).describe("(Optional) Whether to ask for change confirmation with preview UI before writing changes. Default: true. Set to false to skip preview and apply changes immediately.")}),LNe=Vl({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:tGo,handler:async({path:t,content:e,confirmation:r=!0})=>{let n=typeof e=="string"?e:JSON.stringify(e,null,2);if(r===!1)try{let i=await uqr(t);return await app.vault.modify(i,n),JSON.stringify({result:"accepted",message:"File changes applied without preview. Do not retry or attempt alternative approaches to modify this file in response to the current user request."})}catch(i){return JSON.stringify({result:"failed",message:`Error writing to file without preview: ${i?.message||i}`})}let o=await lqr(t,n);return JSON.stringify({result:o,message:`File change result: ${o}. Do not retry or attempt alternative approaches to modify this file in response to the current user request.`})},timeoutMs:0}),rGo=mt.object({path:mt.string().describe("(Required) The path of the file to modify (relative to the root of the vault and include the file extension)."),diff:mt.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`)});cqr=Vl({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:rGo,handler:async({path:t,diff:e})=>{let r=app.vault.getAbstractFileByPath(t);if(!r||!(r instanceof g7.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=oGo(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=Eue(o),p=Eue(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=nGo(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 lqr(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 $dt,Ldt,FD,FNe=v(()=>{$dt=require("obsidian"),Ldt=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""}},FD=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 $dt.Notice(n.message):new $dt.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 iGo(t){let e=t.trim();return e.length<=dqr?e:`${e.slice(0,dqr)}\u2026`}function aGo(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?iGo(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 dqr,hx,Pue=v(()=>{dqr=180;hx=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=aGo(r);return n||(typeof e=="string"?e:JSON.stringify(e,null,2))}}});function sGo(t){return"children"in t&&"path"in t}function uGo(t){return"path"in t&&!("children"in t)}function lGo(t){let e=t.split(".");return e.length>1&&e.pop()?.toLowerCase()||""}function Fdt(t,e=!0){let r=[],n={},o={},{inclusions:i,exclusions:a}=td();for(let u of t.children)if(uGo(u)){if(cl(u,i,a)){e&&r.push(u.name);let l=lGo(u.name)||"unknown";l&&(n[l]=(n[l]||0)+1)}}else if(sGo(u)){let l=Fdt(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 fqr,pqr=v(()=>{vb();yI();mx();fqr=t=>Vl({name:"getFileTree",description:"Get the file tree as a nested structure of folders and files",schema:mt.void(),handler:async()=>{let e=Fdt(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=Fdt(t,!1);return r+JSON.stringify(o)}return r+n},isBackground:!0})});var y7,Yq,qNe=v(()=>{y7=require("obsidian");Bt();jt();yr();js();Yq=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 y7.TFile?this.recentConversationsContent=await this.app.vault.read(e):(this.recentConversationsContent="",H("[UserMemoryManager] Recent Conversations file not found, skipping memory load"));let r=this.app.vault.getAbstractFileByPath(this.getSavedMemoriesFilePath());r instanceof y7.TFile?this.savedMemoriesContent=await this.app.vault.read(r):(this.savedMemoriesContent="",H("[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){it("[UserMemoryManager] Recent history referencing is disabled, skipping analysis");return}if(e.length===0){it("[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){H("[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){H("[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 Qh(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 y7.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 th(a),new au(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 y7.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 y7.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 th(o),new au(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 cGo,BNe,kdt=v(()=>{yI();mx();qNe();Bt();bue();cGo=mt.object({statement:mt.string().min(1).describe("The user statement for explicitly updating saved memories")}),BNe=Vl({name:"updateMemory",description:"Update the user memory when the user explicitly asks to update the memory",schema:cGo,handler:async({statement:t})=>{try{let e=new Yq(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}`}}}})});function UNe(t){return t.replace(/\\/g,"/").toLowerCase()}function dGo(t){return t.replace(/\.[^/.]+$/,"")}function fGo(t,e){if(e.length===0)return!1;let n=UNe(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=dGo(s);if(!s.includes(a)&&!u.includes(a))return!1}else if(!s.includes(a))return!1}return!0}function Bdt(t){return/\.[^/]+$/.test(t)}async function pGo(t){let e=b=>{let _=app.vault.getAbstractFileByPath(b);return _ instanceof Mue.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(!Bdt(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(!Bdt(d))for(let _ of[".md",".canvas"])b.add(`${d}${_}`);for(let _ of b){let w=c.getFirstLinkpathDest?.(_,"");if(w instanceof Mue.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=UNe(d),m=new Set([p]);if(!Bdt(d))for(let b of[".md",".canvas"])m.add(UNe(`${d}${b}`));for(let b of f){let _=UNe(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=>fGo(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 mGo(t){try{return await app.vault.cachedRead(t)}catch(e){return it(`readNote: failed to read ${t.path}`,e),""}}function hGo(){let t=new Map,e=app.vault.getMarkdownFiles?.()??[];for(let r of e)if(r instanceof Mue.TFile){let n=t.get(r.basename)??[];n.push(r),t.set(r.basename,n)}return t}function gGo(t,e,r){let n=t.trim();if(!n)return[];let o=new Map,i=app.metadataCache.getFirstLinkpathDest?.(n,e);if(i instanceof Mue.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 yGo(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=hGo());let p=gGo(d,e.path,o);n.set(f,{linkText:d,displayText:u?.trim()||d,section:c?.trim()||void 0,c
`).trimEnd(),heading:d})}return i}var Mue,qdt,_Go,mqr,hqr=v(()=>{Mue=require("obsidian");yI();Bt();mx();qdt=200;_Go=mt.object({notePath:mt.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:mt.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},mt.number().int().min(0)).optional().describe("0-based chunk index to read. Omit to read the first chunk.")}),mqr=Vl({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:_Go,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 pGo(r);if(n.type==="not_found")return it(`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 it(`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 mGo(o),s=bGo(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];H(`readNote: returning chunk ${l.chunkIndex} of ${u} for ${i}`);let c=l.chunkIndex<u-1,d=yGo(l.content,o);return{notePath:i,noteTitle:o.basename,heading:l.heading,chunkId:l.id,chunkIndex:l.chunkIndex,totalChunks:u,hasMore:c,nextChunkIndex:c?l.chunkIndex+1:null,content:l.content,mtime:o.stat.mtime,linkedNotes:d.length>0?d:void 0}}})});async function Udt(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 DS())return{toolName:t.name,result:`Error: ${sJ(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 FD.callTool(o,i):s=await Promise.race([FD.callTool(o,i),new Promise((u,l)=>setTimeout(()=>l(new Error(`Tool execution timed out after ${a}ms`)),a))]),s==null?(it(`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: ${Mo(o)}`,success:!1}}}function sJ(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 b7(t){return{localSearch:"\u{1F50D}",webSearch:"\u{1F310}",getFileTree:"\u{1F4C1}",getCurrentTime:"\u{1F552}",getTimeRangeMs:"\u{1F4C5}",getTimeInfoByEpoch:"\u{1F570}\uFE0F",convertTimeBetweenTimezones:"\u{1F30D}",youtubeTranscription:"\u{1F4FA}",indexVault:"\u{1F4DA}",indexTool:"\u{1F4DA}",writeToFile:"\u270F\uFE0F",replaceInFile:"\u{1F504}",readNote:
`+JSON.stringify({success:!0,message:`Semantic search index has been refreshed with ${r} documents.`,documentCount:r})}catch(e){return JSON.stringify({success:!1,message:`Failed to index with semantic search: ${e.message}`})}else return`The tiered lexical retriever builds indexes on demand and doesn't require manual indexing.
`+JSON.stringify({success:!0,message:"Tiered lexical retriever uses on-demand indexing. No manual indexing required."})},isBackground:!0}),SGo=mt.object({query:mt.string().min(1).describe("The search query"),chatHistory:mt.array(mt.object({role:mt.enum(["user","assistant"]),content:mt.string()})).describe("Previous conversation turns")}),HNe=Vl({name:"webSearch",description:"Search the web for information",schema:SGo,isPlusOnly:!0,handler:async({query:t,chatHistory:e})=>{try{let r=await OOe(t,e),n=await cc.getInstance().webSearch(r),o=n.response.citations||[],a=[{type:"web_search",content:n.response.choices[0].message.content,citations:o,instruction:Vkr()}];return JSON.stringify(a)}catch(r){return console.error(`Error processing web search query ${t}:`,r),""}}})});function OGo(){return typeof app>"u"||!app?.metadataCache?null:app.metadataCache}function bqr(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 TGo(t,e,r){let n=t,o=bqr(n.getFrontmatterTags?.()),i=e?bqr(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 EGo(t){let e=t,r=JSON.stringify(e);if(r.length<=Kdt)return e;let n=e.tags.length;for(;r.length>Kdt&&n>yqr;)n=Math.max(yqr,Math.floor(n/2)),e={...e,tags:t.tags.slice(0,n),returnedTagCount:n,truncated:!0},r=JSON.stringify(e);return r.length>Kdt?{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 _qr(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 Kdt,CGo,yqr,xGo,vqr,wqr=v(()=>{yI();mx();Kdt=5e5,CGo=500,yqr=50,xGo=mt.object({includeInline:mt.boolean().optional().describe("Include inline tags in addition to frontmatter tags. Defaults to true."),maxEntries:mt.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.");vqr=()=>Vl({name:"getTagList",description:"Get the list of tags in the vault with occurrence statistics.",schema:xGo,handler:async t=>{let e=OGo(),r=t?.includeInline??!0,n=t?.maxEntries??CGo;if(!e)return _qr({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=TGo(e,r,n),i=EGo(o);return _qr(i)},isBackground:!0})});var Sqr=S((Wdt,Gdt)=>{(function(t,e){typeof Wdt=="object"&&typeof Gdt<"u"?Gdt.exports=e():typeof define=="function"&&define.amd?define(e):(t=typeof globalThis<"u"?globalThis:t||self).dayjs_plugin_quarterOfYear=e()})(Wdt,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 eB=S((Zdt,Xdt)=>{(function(t,e){typeof Zdt=="object"&&typeof Xdt<"u"?Xdt.exports=e():typeof define=="function"&&define.amd?define(e):(t=typeof globalThis<"u"?globalThis:t||self).dayjs=e()})(Zdt,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 J=String(F);return!J||J.length>=B?F:""+Array(B+1-J.length).join(U)+F},b={s:y,z:function(F){var B=-F.utcOffset(),U=Math.abs(B),J=Math.floor(U/60),G=U%60;return(B<=0?"+":"-")+y(J,2,"0")+":"+y(G,2,"0")},m:function F(B,U){if(B.date()<U.date())return-F(U,B);var J=12*(U.year()-B.year())+(U.month()-B.month()),G=B.clone().add(J,l),oe=U-G<0,ne=B.clone().add(J+(oe?-1:1),l);return+(-(J+(U-G)/(oe?G-ne:ne-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 I||!(!F||!F[x])},E=function F(B,U,J){var G;if(!B)return _;if(typeof B=="string"){var oe=B.toLowerCase();w[oe]&&(G=oe),U&&(w[oe]=U,G=oe);var ne=B.split("-");if(!G&&ne.length>1)return F(ne[0])}else{var z=B.name;w[z]=B,G=z}return!J&&G&&(_=G),G||!J&&_},T=function(F,B){if(O(F))return F.clone();var U=typeof B=="object"?B:{};return U.date=F,U.args=arguments,new I(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 I=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(J){var G=J.date,oe=J.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 ne=G.match(m);if(ne){var z=ne[2]-1||0,ee
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?(VNe(o,n),gx(o,n),e.timezoneOffset!==null&&o.assign("timezoneOffset",-e.instant.getTimezoneOffset())):(_7(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}},kD=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 Ja(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 eft(t,e,r="\\s{0,5},?\\s{0,5}"){let n=e.replace(/\((?!\?)/g,"(?:");return`${t}${n}(?:${r}${n}){0,10}`}function MGo(t){let e;return t instanceof Array?e=[...t]:t instanceof Map?e=Array.from(t.keys()):e=Object.keys(t),e}function jg(t){return`(?:${MGo(t).sort((r,n)=>n.length-r.length).join("|").replace(/\./g,"\\.")})`}var oB=v(()=>{});function KNe(t){return t<100&&(t>50?t=t+1900:t=t+2e3),t}function iB(t,e,r){let n=(0,Tqr.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 Tqr,w7=v(()=>{Tqr=L(eB(),1)});function RGo(t){let e=t.toLowerCase();return tft[e]!==void 0?tft[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 C7(t){let e=t.toLowerCase();return rft[e]!==void 0?rft[e]:(e=e.replace(/(?:st|nd|rd|th)$/i,""),parseInt(e))}function sB(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 KNe(e)}function l0(t){let e={},r=t,n=Eqr.exec(r);for(;n;)IGo(e,n),r=r.substring(n[0].length).trim(),n=Eqr.exec(r);return Object.keys(e).length==0?null:e}function IGo(t,e){if(e[0].match(/^[a-zA-Z]+$/))return;let r=RGo(e[1]),n=Iue[e[2].toLowerCase()];t[n]=r}var nft,oft,u0,tft,rft,Pqr,Iue,Mqr,S7,aB,Rqr,Eqr,AGo,Aqr,qD,uB,zm=v(()=>{oB();w7();nft={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},oft={january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12},u0={...oft,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},tft={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})=>lZo(t),isBackground:!0}),fzr={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};pzr=Vl({name:"getTimeRangeMs",description:"Convert natural language time expressions to date ranges for use with localSearch",schema:mt.object({timeExpression:mt.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})=>yZo(t),isBackground:!0});mzr=Vl({name:"getTimeInfoByEpoch",description:"Convert a Unix timestamp (in seconds or milliseconds) to detailed time information",schema:mt.object({epoch:mt.number().describe("Unix timestamp in seconds or milliseconds")}),handler:async({epoch:t})=>bZo(t),isBackground:!0});hzr=Vl({name:"convertTimeBetweenTimezones",description:"Convert a specific time from one timezone to another using UTC offsets",schema:mt.object({time:mt.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:mt.string().describe(`Source UTC offset. Must be numeric, not timezone name.
Examples: "-8" for PT, "+0" for London, "+8" for Beijing`),toOffset:mt.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})=>_Zo(t,e,r),isBackground:!0})});var yzr,bzr,_zr=v(()=>{CA();yr();yI();mx();yzr=5e4,bzr=Vl({name:"youtubeTranscription",description:"Get transcripts of YouTube videos when the user provides YouTube URLs",schema:mt.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>yzr)return JSON.stringify({success:!1,message:`Input too long: Maximum allowed length is ${yzr} characters`});let r=LRt(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 cc.getInstance().youtube4llm(i);return a.response.transcript?{url:i,success:!0,transcript:a.response.transcript,elapsed_time_ms:a.elapsed_time_ms}:{url:i,success:!1,message:"Transcript not available. Only English videos with auto transcript enabled are supported"}}catch(a){return console.error(`Error transcribing YouTube video ${i}:`,a),{url:i,success:!1,message:"An error occurred while transcribing the YouTube video"}}})),o=n.some(i=>i.success);return JSON.stringify({success:o,results:n,total_urls:r.length})}})});function wZo(t){vd.getInstance().register({tool:fqr(t.getRoot()),metadata:{id:"getFileTree",displayName:"File Tree",description:"Browse vault file structure",category:"file",isAlwaysEnabled:!0,requiresVault:!0,customPromptInstructions:`For getFileTree:
- Use to browse the vault's file structure including paths of notes and folders
- Always call this tool to explore the exact path of notes or folders when you are not given the exact path.
- DO NOT use this tool to look up note contents or metadata - use localSearch or readNote instead.
- No parameters needed
Example usage:
<use_tool>
<name>getFileTree</name>
</use_tool>
Example queries that should use getFileTree:
- "Create a new note in the projects folder" -> call getFileTree to get the exact folder path of projects folder
- "Create a new note using the quick note template" -> call getFileTree to look up the exact folder path of the quick note template
- "How many files are in the projects folder" -> call getFileTree to list all files in the projects folder
`}})}function SZo(){vd.getInstance().register({tool:vqr(),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 CZo(){vd.getInstance().register({tool:BNe,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 J7(t){let e=vd.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(vZo),t&&(wZo(t),SZo()),r.enableSavedMemory&&CZo())}var vZo,w1e=v(()=>{jt();Ddt();pqr();kdt();hqr();Jdt();wqr();gzr();xH();_zr();vZo=[{tool:zNe,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:HNe,metadata:{id:"webSearch",displayName:"Web Search",description:"Search the INTERNET (NOT vault notes) when user explicitly asks for web/online information",category:"search",copilotCommands:["@websearch","@web"],customPromptInstructions:`For webSearch:
- ONLY use when the user's query contains explicit web-search intent like:
* "web search", "internet search", "online search"
* "Google", "search online", "look up online", "search the web"
- Always provide an empty chatHistory array
Example - "search the web for python tutorials":
<use_tool>
<name>webSearch</name>
<query>python tutorials</query>
<chatHistory>[]</chatHistory>
</use_tool>`}},{tool:dzr,metadata:{id:"getCurrentTime",displayName:"Get Current Time",description:"Get the current time in any timezone",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For time queries (IMPORTANT: Always use UTC offsets, not timezone names):
- If the user mentions a specific city, country, or timezone name (e.g., "Tokyo", "Japan", "JST"), you MUST convert it to the correct UTC offset and pass it via the timezoneOffset parameter (e.g., "+9").
- Only omit timezoneOffset when the user asks for the current local time without naming any location or timezone.
- If you cannot confidently determine the offset from the user request, ask the user to clarify before calling the tool.
Example 1 - "what time is it" (local time):
<use_tool>
<name>getCurrentTime</name>
</use_tool>
Example 2 - "what time is it in Tokyo" (UTC+9):
<use_tool>
<name>getCurrentTime</name>
<timezoneOffset>+9</timezoneOffset>
</use_tool>
Example 3 - "what time is it in New York" (UTC-5 or UTC-4 depending on DST):
<use_tool>
<name>getCurrentTime</name>
<timezoneOffset>-5</timezoneOffset>
</use_tool>`}},{tool:mzr,metadata:{id:"getTimeInfoByEpoch",displayName:"Get Time Info",description:"Convert epoch timestamp to human-readable format",category:"time",isAlwaysEnabled:!0}},{tool:pzr,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:hzr,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:mqr,metadata:{id:"readNote",displayName:"Read Note",description:"Read a specific note in sequential chunks using its own line-chunking logic.",category:"file",requiresVault:!0,isAlwaysEnabled:!0,customPromptInstructions:`For readNote:
- Decide based on the user's request: only call this tool when the question requires reading note content.
- If the user asks about a note title that is already mentioned in the current or previous turns of the conversation, or linked in <active_note> or <note_context> blocks, call readNote directly\u2014do not use localSearch to look it up. Even if the note title mention is partial but similar to what you have seen in the context, try to infer the correct note path from context. Skip the tool when a note is irrelevant to the user query.
- If the user asks about notes linked from that note, read the original note first, then follow the "linkedNotes" paths returned in the tool result to inspect those linked notes.
- Always start with chunk 0 (omit <chunkIndex> or set it to 0). Only request the next chunk if the previous chunk did not answer the question.
- Pass vault-relative paths without a leading slash. If a call fails, adjust the path (for example, add ".md" or use an alternative candidate) and retry only if necessary.
- Every tool result may include a "linkedNotes" array. If the user needs information from those linked notes, call readNote again with one of the provided candidate paths, starting again at chunk 0. Do not expand links you don't need.
- Stop calling readNote as soon as you have the required information.
- Always call getFileTree to get the exact note path if it is not provided in the context before calling readNote.
Example (first chunk):
<use_tool>
<name>readNote</name>
<notePath>Projects/launch-plan.md</notePath>
</use_tool>
Example (next chunk):
<use_tool>
<name>readNote</name>
<notePath>Projects/launch-plan.md</notePath>
<chunkIndex>1</chunkIndex>
</use_tool>`}},{tool:LNe,metadata:{id:"writeToFile",displayName:"Write to File",description:"Create or modify files in your vault",category:"file",requiresVault:!0,copilotCommands:["@composer"],customPromptInstructions:`For writeToFile:
- NEVER display the file content directly in your response
- Always pass the complete file content to the tool
- Include the full path to the file
- You MUST explicitly call writeToFile for any intent of updating or creating files
- Do not call writeToFile tool again if the result is not accepted
- Do not call writeToFile tool if no change needs to be made
- Always create new notes in root folder or folders the user explicitly specifies
- When creating a new note in a folder, you MUST use getFileTree to get the exact folder path first
Example usage:
<use_tool>
<name>writeToFile</name>
<path>path/to/note.md</path>
<content>FULL CONTENT OF THE NOTE</content>
</use_tool>
Example usage with user explicitly asks to skip preview or confirmation:
<use_tool>
<name>writeToFile</name>
<path>path/to/note.md</path>
<content>FULL CONTENT OF THE NOTE</content>
<confirmation>false</confirmation>
</use_tool>
`}},{tool:cqr,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:bzr,metadata:{id:"youtubeTranscription",displayName:"YouTube Transcription",description:"Get transcripts from YouTube videos",category:"media",customPromptInstructions:`For youtubeTranscription:
- Use when user provides YouTube URLs
- No parameters needed - the tool will process URLs from the conversation
Example usage:
<use_tool>
<name>youtubeTranscription</name>
</use_tool>`}}]});var S1e,vzr=v(()=>{Pue();S1e=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=hx.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 apt(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=xZo(r);n&&e.push({role:n,content:r.content})}}return e}function xZo(t){return t.role==="human"||t.role==="user"||t.sender==="user"?"user":t.role==="ai"||t.role==="assistant"||t.sender==="AI"?"assistant":null}function C1e(t,e){let r=apt(t);for(let n of r)e.push({role:n.role,content:n.content})}function wzr(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 x1e=v(()=>{});function spt(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 Szr(t){try{let e=JSON.parse(t);return Array.isArray(e)?spt(e):"Invalid search results format."}catch(e){return it("Failed to format localSearch result string:",e),"Error processing search results."}}function Czr(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 OZo(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 TZo(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 xzr(t){if(!Array.isArray(t)||t.length===0){H("Search Results: (none)");return}let e=0,r=t.map((u,l)=>{let c=OZo(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=TZo(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;H(`Search Results (debug table): ${n} rows; in-context ${e}/${n}`),CRt(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)} |`);Ihe(["",`Results: ${n} rows; in-context ${e}/${n}`,"",i,a,...s,""])}var Ozr=v(()=>{Bt()});function Tzr(t,e){return[t,e].map(n=>n?.trim()).filter(n=>!!n).join(`
`)}function Ezr(t,e){let r=t?`
${t}
`:"";return`<localSearch${e?` timeRange="${e}"`:""}>${r}</localSearch>`}function upt(t,e){let r=t.trim();return r?`${r}
${e}`:e}function Pzr(t,e){let r=e.trim();return!r||t.includes(r)?t:upt(t,`[User query]:
${r}`)}var lpt=v(()=>{});function bJ(t){return t.map(e=>e.content).filter(e=>e&&e.trim().length>0).join(`
`)}function O1e(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 ppt,yJ,cpt,dpt,fpt,SB,zle=v(()=>{Bt();ppt=50;yJ=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 bJ(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
### Handle ambiguity in folder/note paths
When user mentions a folder name (e.g., "meetings folder") or a note name (e.g., "meeting note template") without providing an exact path,
you MUST first call getFileTree to find the folder or notes best matching the user's query.
If multiple results or no result, you should ask the user to provide a more specific path.
`}),a.length>0&&u.push({id:"tool-specific-instructions",label:"Tool-specific instructions",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildToolSpecificInstructions",content:a}),u.push({id:"general-guidelines",label:"General guidelines",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildSystemPromptSections",content:`## General Guidelines
- Think hard about whether a query could potentially be answered from personal knowledge or notes, if yes, call a vault search (localSearch) first
- NEVER mention tool names like "localSearch", "webSearch", etc. in your responses. Use natural language like "searching your vault", "searching the web", etc.
You can use multiple tools in sequence. After each tool execution, you'll receive the results and can decide whether to use more tools or provide your final response.
Always explain your reasoning before using tools. Be conversational and clear about what you're doing.
When you've gathered enough information, provide your final response without any tool calls.
IMPORTANT: Do not include any code blocks (\`\`\`) or tool_code blocks in your responses. Only use the <use_tool> format for tool calls.
NOTE: Use individual XML parameter tags. For arrays, use JSON format like ["item1", "item2"].`}),u}enhanceUserMessage(e,r){return e}needsSpecialHandling(){return!1}},cpt=class extends yJ{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}},dpt=class extends yJ{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>ppt}},fpt=class extends yJ{buildSystemPromptSections(e,r,n,o){let i=super.buildSystemPromptSections(e,r,n,o),u=[`\u{1F6A8} CRITICAL INSTRUCTIONS FOR GEMINI - AUTONOMOUS AGENT MODE \u{1F6A8}
You MUST use tools to complete tasks. DO NOT ask the user questions about how to proceed.
${(n||[]).includes("localSearch")?`
When the user mentions "my notes" or "my vault", use the localSearch tool.
\u274C WRONG:
"Let's start by searching your notes. What kind of information should I look for?"
\u2705 CORRECT:
<use_tool>
<name>localSearch</name>
<query>piano</query>
<salientTerms>["piano"]</salientTerms>
</use_tool>`:""}`.trim()];return u.push(`GEMINI SPECIFIC RULES:
1. When user mentions "my notes" about X \u2192 use localSearch with query "X"
2. DO NOT ask clarifying questions about search terms
3. DO NOT wait for permission to use tools
4. Use tools based on the user's request
\u{1F6A8} CRITICAL: SEQUENTIAL vs PARALLEL TOOL CALLS \u{1F6A8}
When one tool's OUTPUT is needed as INPUT to another tool, you MUST make them in SEPARATE responses:
1. Call the FIRST tool
2. STOP and wait for the result
3. In the NEXT response, use the result from step 1 in the SECOND tool call
\u274C WRONG (DO NOT DO THIS):
User: "Recap my last week"
Your response:
<use_tool>
<name>getTimeRangeMs</name>
<timeExpression>last week</timeExpression>
</use_tool>
<use_tool>
<name>localSearch</name>
<timeRange>{"startTime":1234567890,"endTime":9876543210}</timeRange>
</use_tool>
This is WRONG because you're hallucinating the timeRange values! You don't know what getTimeRangeMs will return yet!
\u2705 CORRECT (DO THIS):
User: "Recap my last week"
Your FIRST response:
<use_tool>
<name>getTimeRangeMs</name>
<timeExpression>last week</timeExpression>
</use_tool>
[STOP HERE - WAIT FOR RESULT]
System provides: {"startTime":1753660800000,"endTime":1754265600000}
Your SECOND response:
<use_tool>
<name>localSearch</name>
<query>recap my last week</query>
<salientTerms>[]</salientTerms>
<timeRange>{"startTime":1753660800000,"endTime":1754265600000}</timeRange>
</use_tool>
RULE: NEVER make up or guess parameter values. If you need a tool's output, call that tool FIRST, then WAIT for the result.
PATTERN FOR MULTI-STEP REQUESTS:
User: "based on my project roadmap notes and create summary"
Your response:
<use_tool>
<name>localSearch</name>
<query>project roadmap</query>
<salientTerms>["project", "roadmap"]</salientTerms>
</use_tool>
Remember: The user has already told you what to do. Execute it NOW with the available tools.`),i.push({id:"gemini-specific-guidelines",label:"Gemini-specific guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#GeminiModelAdapter.buildSystemPromptSections",content:u.join(`
`)}),i}enhanceUserMessage(e,r){return r?`${e}
REMINDER: Use the tools immediately. Do not ask questions. For "my notes", use localSearch.`:e}needsSpecialHandling(){return!0}},SB=class{static createAdapter(e){let r=(e.modelName||e.model||"").toLowerCase();if(H(`Creating model adapter for: ${r}`),r.includes("gpt")){let n=new cpt(r);return n.isGPT5Model()?H("Using GPTModelAdapter with GPT-5 specific enhancements"):H("Using GPTModelAdapter"),n}return r.includes("claude")?(H("Using ClaudeModelAdapter"),new dpt(r)):r.includes("gemini")||r.includes("google/gemini")?(H("Using GeminiModelAdapter"),new fpt(r)):r.includes("copilot-plus")?(H("Using BaseModelAdapter for Copilot Plus"),new yJ(r)):(H("Using BaseModelAdapter (default)"),new yJ(r))}}});function K7(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){it("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]=mpt(p,f))}a||it(`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 mpt(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 mpt(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,mpt(u)])}return i.length>0?Object.fromEntries(i):t}function Mzr(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 Hle(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 T1e=v(()=>{Bt()});var bI,E1e=v(()=>{ANe();Zr();Cie();Vnt();Bt();Lv();jt();Ddt();FNe();Pue();xH();w1e();Jdt();kdt();yr();yr();Sie();vzr();x1e();wue();Ozr();lpt();OH();Rue();W1();zle();T1e();mx();Ik();Us();bI=class t extends K1{constructor(){super(...arguments);this.lastCitationSources=null}getAvailableToolsForPlanning(){let r=vd.getInstance();return r.getAllTools().length===0&&J7(this.chainManager.app?.vault),r.getAllTools().map(o=>o.tool).filter(o=>o.name==="getCurrentTime"||o.name==="convertTimeBetweenTimezones"||o.name==="getTimeInfoByEpoch"||o.name==="getTimeRangeMs"||o.name==="getFileTree")}static generateToolDescriptions(r){return r.map(n=>{let o="",i=$Ne(n.schema);return Object.keys(i).length>0&&(o=Object.entries(i).map(([a,s])=>`<${a}>${s}</${a}>`).join(`
`)),`<${n.name}>
<description>${n.description}</description>
<parameters>
${o}
</parameters>
</${n.name}>`}).join(`
`)}async planToolCalls(r,n){let o=this.getAvailableToolsForPlanning(),i=SB.createAdapter(n),a=t.generateToolDescriptions(o),s=vd.getInstance(),u=o.map(y=>s.getToolMetadata(y.name)).filter(y=>y!==void 0),l=i.buildSystemPromptSections("You are a helpful AI assistant. Analyze the user's message and determine if any tools should be called.",a,o.map(y=>y.name),u),c=bJ(l);c+=`
IMPORTANT: Respond ONLY with XML blocks. Do not include any natural language explanations, apologies, or commentary.
Your response must contain:
1. Tool calls (if needed): <use_tool>...</use_tool>
2. Salient terms (always): <salient_terms><term>keyword</term></salient_terms>
Format for salient terms:
<salient_terms>
<term>first keyword</term>
<term>second keyword</term>
</salient_terms>
Guidelines for salient terms:
- Extract meaningful nouns, topics, and specific concepts
- Exclude common words like "what", "how", "my", "the", "a", "an"
- Exclude time expressions (those are handled separately)
- If the message has no meaningful search terms, output empty <salient_terms></salient_terms>
- Use the EXACT words from the user's message (preserve language/spelling)
OUTPUT ONLY XML - NO OTHER TEXT.`;let d=[{role:kz(n),content:c},{role:"user",content:r}];H("[CopilotPlus] Requesting tool planning from model...");let f=await ih(()=>n.invoke(d)),p=typeof f.content=="string"?f.content:String(f.content);H("[CopilotPlus] Model planning response:",p.substring(0,500));let m=K7(p),h=this.extractSalientTerms(p),g=[];for(let y of m){let b=o.find(_=>_.name===y.name);b&&g.push({tool:b,args:y.args})}return{toolCalls:g,salientTerms:h}}extractSalientTerms(r){let n=r.match(/<salient_terms>([\s\S]*?)<\/salient_terms>/);if(!n)return[];let i=n[1].matchAll(/<term>(.*?)<\/term>/g),a=[];for(let s of i){let u=s[1].trim();u&&a.push(u)}return a}async processAtCommands(r,n,o){let i=r.toLowerCase(),a=this.removeAtCommands(r),s=[...n];if(i.includes("@vault")&&(s.some(l=>l.tool.name==="localSearch")||s.push({tool:zNe,args:{query:a,salientTerms:o.salientTerms,timeRange:o.timeRange}})),(i.includes("@websearch")||i.includes("@web"))&&!s.some(l=>l.tool.name==="webSearch")){let c=await xg.instance.getCurrentChainManager().memoryManager.getMemory().loadMemoryVariables({}),d=z6(c);s.push({tool:HNe,args:{query:a,chatHistory:d}})}return i.includes("@memory")&&(s.some(l=>l.tool.name==="updateMemory")||s.push({tool:BNe,args:{statement:a}})),s}removeAtCommands(r){return r.split(" ").filter(n=>!h7.includes(n.toLowerCase())).join(" ").trim()}async processImageUrls(r){let n=[],o=await CH.processUrlBatch(r,n,this.chainManager.app.vault);return CH.showFailedImagesNotice(n),o}async processChatInputImages(r){let n=[],o=await CH.processChatImageBatch(r,n,this.chainManager.app.vault);return CH.showFailedImagesNotice(n),o}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):(it(`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=n.contextEnvelope;if(!d)throw new Error("[CopilotPlus] Context envelope is required but not available. Cannot extract images.");let f=d.layers.find(p=>p.id==="L3_TURN");if(f){let m=/<active_note>([\s\S]*?)<\/active_note>/.exec(f.text);if(m){let h=m[1],y=/<path>(.*?)<\/path>/.exec(h),b=y?y[1]:void 0,w=/<content>([\s\S]*?)<\/content>/.exec(h),x=w?w[1]:"";if(x){H("[CopilotPlus] Extracting images from active note only:",b||"no source path");let O=await this.extractEmbeddedImages(x,b);O.length>0&&s.push({urls:O,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>
${URt}
</OUTPUT_FORMAT>`;return`${r}
${o}`}async streamMultimodalResponse(r,n,o,i,a,s){let c=(await this.chainManager.memoryManager.getMemory().loadMemoryVariables({})).history||[],d=this.chainManager.chatModelManager.getChatModel(),f=this.isMultimodalModel(d),p=[],m=n.contextEnvelope;if(!m)throw new Error("[CopilotPlus] Context envelope is required but not available. Cannot proceed with CopilotPlus chain.");H("[CopilotPlus] Using envelope-based context construction");let h=MA.convert(m,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),g=h.find(x=>x.role==="system");g&&p.push({role:kz(d),content:g.content}),C1e(c,p);let y=h.find(x=>x.role==="user");if(y){let x,O=o.length>0,E=R=>{let I="[User query]:";if(R.includes(I))return R;let j=R.trimEnd(),F=[];j.length>0&&F.push(j);let B=s.trim()||n.message?.trim()||n.originalMessage?.trim()||"";return B.length>0?F.push(`${I}
${B}`):F.push(I),F.join(`
`)};if(O){let R=this.formatAllToolOutputs(o),I=E(y.content);x=upt(R,I)}else x=E(y.content);if(r.includes("<OUTPUT_FORMAT>")&&!x.includes("<OUTPUT_FORMAT>")){let R=r.match(/<OUTPUT_FORMAT>[\s\S]*?<\/OUTPUT_FORMAT>/);R&&(x+=`
`+R[0])}let T=f?await this.buildMessageContent(x,n):x;p.push({role:"user",content:T})}H("Final request to AI",{messages:p.length});let b=d?.modelName;Rk({messages:p,modelName:b,contextEnvelope:n.contextEnvelope});let _=new S1e(FD,LNe),w=await ih(()=>this.chainManager.chatModelManager.getChatModel().stream(p,{signal:i.signal}));for await(let x of w){if(i.signal.aborted){H("CopilotPlus multimodal stream iteration aborted",{reason:i.signal.reason});break}for await(let O of _.processChunk(x))a.processChunk(O)}}async run(r,n,o,i,a){let{updateLoadingMessage:s}=a,u=this.chainManager.chatModelManager.getChatModel(),c=!this.hasCapability(u,"reasoning"),d=new R_(o,void 0,c),f=[];if(!await DS({isCopilotPlus:!0})){await this.handleError(new Error("Invalid license key"),d.processErrorChunk.bind(d));let _=d.close().content;return this.handleResponse(_,r,n,i,o,void 0)}try{H("==== Step 1: Planning tools ====");let _,w=r.contextEnvelope;if(!w)throw new Error("[CopilotPlus] Context envelope is required but not available. Cannot proceed with CopilotPlus chain.");let O=w.layers.find(F=>F.id==="L5_USER")?.text||r.originalMessage||r.message;try{let F=this.chainManager.chatModelManager.getChatModel(),B=await this.planToolCalls(O,F),U,J=B.toolCalls.find(oe=>oe.tool.name==="getTimeRangeMs");J&&(U=await FD.callTool(J.tool,J.args),H("[CopilotPlus] Executed getTimeRangeMs, result:",U));let G=B.toolCalls.filter(oe=>oe.tool.name==="getFileTree"&&Wz()?(H("Skipping getFileTree in project mode"),!1):oe.tool.name==="getTimeRangeMs"&&U?(H("Skipping getTimeRangeMs - already executed during planning"),!1):!0);_=await this.processAtCommands(O,G,{salientTerms:B.salientTerms,timeRange:U})}catch(F){return this.handleResponse(PRt(F),r,n,i,o)}let E=this.removeAtCommands(r.message),{toolOutputs:T,sources:R}=await this.executeToolCalls(_,s);f=R;let I=T.filter(F=>F.output!=null),j=this.appendComposerInstructionsIfNeeded(E,r);H("Invoking LLM with envelope-based context construction"),await this.streamMultimodalResponse(j,r,I,n,d,E)}catch(_){s?.(EO.DEFAULT),_.name==="AbortError"||n.signal.aborted?H("CopilotPlus stream aborted by user",{reason:n.signal.reason}):await this.handleError(_,d.processErrorChunk.bind(d))}if(n.signal.aborted&&n.signal.reason==="new-chat")return o(""),"";let m=d.close(),h=m.content,g={wasTruncated:m.wasTruncated,tokenUsage:m.tokenUsage??void 0},y=ce(),b=this.lastCitationSources&&this.lastCitationSources.length>0?this.lastCitationSources:(f||[]).map(_=>({title:_.title,path:_.path}));return h=PNe(h,b,y.enableInlineCitations),await this.handleResponse(h,r,n,i,o,f,void 0,g),h}async executeToolCalls(r,n){let o=[],i=[],a=r.some(s=>s.tool.name==="localSearch");for(let s of r){if(s.tool.name==="getFileTree"&&a){H("Skipping getFileTree since localSearch is already active");continue}H(`Step 2: Calling tool: ${s.tool.name}`),s.tool.name==="localSearch"?n?.(EO.READING_FILES):s.tool.name==="webSearch"?n?.(EO.SEARCHING_WEB):s.tool.name==="getFileTree"&&n?.(EO.READING_FILE_TREE);let u=await FD.callTool(s.tool,s.args);if(s.tool.name==="localSearch"){let c={result:typeof u=="string"?u:JSON.stringify(u),success:u!=null},d=this.getTimeExpression(r),f=this.processLocalSearchResult(c,d);i.push(...f.sources),o.push({tool:s.tool.name,output:f.formattedForLLM})}else o.push({tool:s.tool.name,output:u})}return{toolOutputs:o,sources:Qq(i)}}getTimeExpression(r){let n=r.find(o=>o.tool.name==="getTimeRangeMs");return n?n.args.timeExpression:""}prepareLocalSearchResult(r,n){let o=r.filter(g=>g.includeInContext),i=o.reduce((g,y)=>g+(y.content?.length||0),0),a=o;if(i>D2e){let g=D2e/i;H("Truncating document contents to fit context length. Truncation ratio:",g),a=o.map(y=>({...y,content:y.content?.slice(0,Math.floor((y.content?.length||0)*g))||""}))}let s=a.map((g,y)=>({...g,__sourceId:y+1,content:MNe(g.content||"")})),u=spt(s),l=s.slice(0,Math.min(20,s.length)).map(g=>({title:g.title||g.path||"Untitled",path:g.path||g.title||""})),c=RNe(l);this.lastCitationSources=s.slice(0,Math.min(20,s.length)).map(g=>({title:g.title||g.path||"Untitled",path:g.path||void 0}));let d=ce(),f=Uk
${f}`:m;return Ezr(h,n)}processLocalSearchResult(r,n){let o=[],i,a;if(!r.success)return i=`<localSearch>
Search failed.
</localSearch>`,a=`Search failed: ${r.result}`,{formattedForLLM:i,formattedForDisplay:a,sources:o};try{let s=JSON.parse(r.result),u=s&&typeof s=="object"&&s.type==="local_search"&&Array.isArray(s.documents)?s.documents:null;if(!Array.isArray(u))return i=`<localSearch>
Invalid search results format.
</localSearch>`,a="Search results were in an unexpected format.",{formattedForLLM:i,formattedForDisplay:a,sources:o};xzr(u),o=Czr(u),i=this.prepareLocalSearchResult(u,n||""),a=hx.format("localSearch",i)}catch(s){it("Failed to parse localSearch results:",s);let u=Szr(r.result);i=n?`<localSearch timeRange="${n}">
${u}
</localSearch>`:`<localSearch>
${u}
</localSearch>`,a=hx.format("localSearch",i)}return{formattedForLLM:i,formattedForDisplay:a,sources:o}}async getSystemPrompt(){return ON(this.chainManager.userMemoryManager)}formatAllToolOutputs(r){return r.length===0?"":`# Additional context:
`+r.map(o=>{let i=o.output;return typeof i!="string"&&(i=JSON.stringify(i)),`<${o.tool}>
${i}
</${o.tool}>`}).join(`
`)}}});var Vle,Rzr=v(()=>{E1e();Vle=class extends bI{}});function EZo(t){let{systemSections:e,rawHistory:r,adapterName:n,originalUserMessage:o,enhancedUserMessage:i}=t,a=[...e];if(r&&r.length>0){let u=apt(r);if(u.length>0){let c=wzr(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 PZo(t){return t.map(e=>`${`[Section: ${e.label} | Source: ${e.source}]`}
${e.content}`).join(`
`)}function Azr(t){let e=EZo(t),r=PZo(e),n=bJ(t.systemSections);return{sections:e,annotatedPrompt:r,systemPrompt:n}}var Izr=v(()=>{zle();x1e()});async function MZo(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=O1e(s.message),m=r.enhanceUserMessage(s.message,p);return Azr({systemSections:u,rawHistory:d,adapterName:r.constructor?.name||"ModelAdapter",originalUserMessage:f,enhancedUserMessage:m})}async function RZo(t){return ON(t.userMemoryManager)}async function Nzr(t){let{chainManager:e,adapter:r,availableTools:n,toolDescriptions:o,userMessage:i}=t,a=vd.getInstance(),s=n.map(c=>c.name),u=n.map(c=>a.getToolMetadata(c.name)).filter(c=>c!==void 0),l=await RZo(e);return MZo({chainManager:e,adapter:r,basePrompt:l,toolDescriptions:o,toolNames:s,toolMetadata:u,userMessage:i})}var jzr=v(()=>{jt();xH();zle();Izr()});var Jle,Dzr=v(()=>{Zr();Bt();Lv();jt();w1e();mx();xH();Pue();yr();xOe();js();E1e();x1e();zle();OH();vie();Rue();lpt();Cie();jzr();W1();T1e();Jle=class t extends bI{constructor(){super(...arguments);this.llmFormattedMessages=[];this.lastDisplayedContent=""}getAvailableTools(){let r=ce(),n=vd.getInstance();n.getAllTools().length===0&&J7(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=$Ne(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 ON(o),a=t.generateToolDescriptions(r),s=r.map(c=>c.name),u=vd.getInstance(),l=r.map(c=>u.getToolMetadata(c.name)).filter(c=>c!==void 0);return n.enhanceSystemPrompt(i,a,s,l)}async buildToolPromptDebugReport(r){let n=this.getAvailableTools(),o=SB.createAdapter(this.chainManager.chatModelManager.getChatModel()),i=t.generateToolDescriptions(n);return Nzr({chainManager:this.chainManager,adapter:o,availableTools:n,toolDescriptions:i,userMessage:r})}applyCiCOrderingToLocalSearchResult(r,n){return Pzr(r,n)}getTemporaryToolCallId(r,n){return`temporary-tool-call-id-${r}-${n}`}async run(r,n,o,i,a){this.llmFormattedMessages=[],this.lastDisplayedContent="";let s="",u,l=await DS({isAutonomousAgent:!0}),c=this.chainManager.chatModelManager.getChatModel(),d=SB.createAdapter(c),p=!this.hasCapability(c,"reasoning"),m=new R_(o,d,p);if(!l){await this.handleError(new Error("Invalid license key"),m.processErrorChunk.bind(m));let b=m.close().content;return this.handleResponse(b,r,n,i,o,void 0)}let h=c?.modelName;if(!r.contextEnvelope)throw new Error("[Agent] Context envelope is required but not available. Cannot proceed with autonomous agent.");H("[Agent] Using envelope-based context construction");let y=await this.prepareAgentConversation(r,c);try{let b=await this.executeAgentLoop({...y,adapter:d,abortController:n,updateCurrentAiMessage:o});s=b.fullAIResponse,u=b.responseMetadata,y.iterationHistory=b.iterationHistory,y.collectedSources=b.collectedSources,this.llmFormattedMessages=b.llmMessages}catch(b){if(b.name==="AbortError"||n.signal.aborted)H("Autonomous agent stream aborted by user",{reason:n.signal.reason});else{ue("Autonomous agent failed, falling back to regular Plus mode:",b);try{return await new bI(this.chainManager).run(r,n,o,i,a)}catch(_){ue("Fallback to regular Plus mode also failed:",_),this.lastDisplayedContent&&m.processChunk({content:this.lastDisplayedContent});let w=Mo(b),x=`
Fallback to regular Plus mode also failed: `+Mo(_);return await this.handleError(new Error(w+x),m.processErrorChunk.bind(m)),s=m.close().content,this.handleResponse(s,r,n,i,o,void 0,s)}}}return await this.finalizeAgentRun({...y,userMessage:r,abortController:n,addMessage:i,updateCurrentAiMessage:o,modelNameForLog:h,responseMetadata:u,fullAIResponse:s})}async prepareAgentConversation(r,n){let o=[],i=[],a=[],s=this.getAvailableTools(),u={availableTools:s,getTemporaryToolCallId:this.getTemporaryToolCallId.bind(this),processLocalSearchResult:this.processLocalSearchResult.bind(this),applyCiCOrderingToLocalSearchResult:this.applyCiCOrderingToLocalSearchResult.bind(this)},l=r.contextEnvelope,c=MA.convert(l,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),p=(await this.chainManager.memoryManager.getMemory().loadMemoryVariables({})).history||[],m=c.find(I=>I.role==="system"),h=SB.createAdapter(n),g=t.generateToolDescriptions(s),y=vd.getInstance(),b=s.map(I=>y.getToolMetadata(I.name)).filter(I=>I!==void 0),w=h.buildSystemPromptSections("",g,s.map(I=>I.name),b).filter(I=>I.id!=="base-system-prompt"),x=bJ(w);if(m||x){let I=[m?.content||"",x||""].filter(Boolean).join(`
`);o.push({role:kz(n),content:I})}C1e(p,o);let E=l.layers.find(I=>I.id==="L5_USER")?.text||"",T=E||r.originalMessage||r.message,R=c.find(I=>I.role==="user");if(R){let I=this.isMultimodalModel(n),j=O1e(E),F=h.enhanceUserMessage(R.content,j),B=I?await this.buildMessageContent(F,r):F;o.push({role:"user",content:B})}return{conversationMessages:o,iterationHistory:i,collectedSources:a,originalUserPrompt:T,loopDeps:u}}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,H(`=== Autonomous Agent Iteration ${g} ===`);let _=[],w=await this.streamResponse(n,l,J=>this.updateStreamingDisplay(J,d,_,c,s),u);b={wasTruncated:w.wasTruncated,tokenUsage:w.tokenUsage??void 0};let x=w.content;if(!x)break;let O=K7(x),E=u.detectPrematureResponse?.(x);if(E?.hasPremature&&g===1&&(E.type==="before"?(it("\u26A0\uFE0F Model provided premature response BEFORE tool calls!"),it("Sanitizing response to keep only tool calls for first iteration")):E.type==="after"&&(it("\u26A0\uFE0F Model provided hallucinated response AFTER tool calls!"),it("Truncating response at last tool call for first iteration"))),O.length===0){let J=Hle(x),G=[...d];J.trim()&&G.push(J),y=G.join(`
`);let oe=wOe(x);n.push({role:"assistant",content:oe}),p.push(x);break}let T=x;u.sanitizeResponse&&E?.hasPremature&&(T=u.sanitizeResponse(x,g));let R=Hle(T);R.trim()&&d.push(R);let I=[],j=new Map;_.splice(O.length);for(let J=0;J<O.length;J+=1){let G=O[J];if(this.isAbortRequested(l))break;zdt(G,g);let ne=m.find(ie=>ie.name===G.name)?.isBackground||!1,z;if(!ne){let ie=b7(G.name),Z=sJ(G.name);if(G.name==="readNote"){let D=typeof G.args?.notePath=="string"?G.args.notePath:null;D&&D.trim().length>0&&(Z=kNe(D))}let $=gqr(G.name);z=`${G.name}-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,j.set(J,z);let q=SOe(z,G.name,Z,ie,$||"",!0,"",""),Y=_.findIndex(D=>D.includes(s.getTemporaryToolCallId(G.name,J)));Y!==-1?_[Y]=q:(_.push(q),it("Created tool call marker for tool call that was not created during streaming",G.name)),c([...d,..._].join(`
`))}let ee=await Udt(G,m,a);if(ee.success||(ee.displayResult=rG(ee.result,"Tool execution failed")),G.name==="localSearch"){if(ee.success){let ie=s.processLocalSearchResult(ee);f.push(...ie.sources),ee.result=s.applyCiCOrderingToLocalSearchResult(ie.formattedForLLM,a||""),ee.displayResult=ie.formattedForDisplay}}else G.name==="readNote"&&ee.success&&(ee.displayResult=hx.format("readNote",ee.result));if(I.push(ee),z&&!ne){let ie=_.findIndex(Z=>Z.includes(z));ie!==-1&&(_[ie]=Qnt(_[ie],z,ee.displayResult??ee.result)),c([...d,..._].join(`
`))}Hdt(G.name,ee)}_.length>0&&d.push(_.join(`
`));let F=T;if(p.push(F),I.length>0){let J=tot(I,!0);J&&p.push(J)}let B=wOe(T);n.push({role:"assistant",content:B});let U=tot(I,!1);n.push({role:"user",content:U}),H("Tool results added to conversation")}if(g>=h&&!y){it(`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=Hle(r),u=[...n];s.trim()&&u.push(s);let l=K7(r),c=new Set(a.availableTools.filter(h=>h.isBackground).map(h=>h.name));if(o.length>0&&c.size>0){let h=Array.from(c).map(g=>`temporary-tool-call-id-${g}-`);for(let g=o.length-1;g>=0;g-=1){let y=o[g];h.some(b=>y.includes(b))&&o.splice(g,1)}}let d=[];l.forEach(h=>{c.has(h.name)||d.push(h.name)});let f=Mzr(r);if(f){let h=r.lastIndexOf(f);r.length-h>ppt&&(c.has(f)||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 _=SOe(y,h,sJ(h),b7(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=Qq(i);!p&&o.length>0&&(it("fullAIResponse was empty, using iteration history"),p=o.join(`
`)),n.length>0&&Rk({messages:[...n],modelName:c,contextEnvelope:a.contextEnvelope}),await Promise.resolve().then(()=>(vie(),eot));let h=this.llmFormattedMessages.join(`
`);return await this.handleResponse(p,a,s,u,l,m.length>0?m:void 0,h,d),this.lastDisplayedContent="",p}async streamResponse(r,n,o,i){let a=this.chainManager.chatModelManager.getChatModel(),u=!this.hasCapability(a,"reasoning"),l=new R_(o,i,u),c=2,d=0;for(;d<=c;)try{let p=r.map(g=>g.role==="user"?new au(g.content):new li(g.content)),m=await ih(()=>this.chainManager.chatModelManager.getChatModel().stream(p,{signal:n.signal}));for await(let g of m){if(n.signal.aborted)break;l.processChunk(g)}let h=l.close();return{content:h.content,wasTruncated:h.wasTruncated,tokenUsage:h.tokenUsage}}catch(p){if(p.name==="AbortError"||n.signal.aborted){let h=l.close();return{content:h.content,wasTruncated:h.wasTruncated,tokenUsage:h.tokenUsage}}if((p?.message?.includes("overloaded")||p?.message?.includes("Overloaded")||p?.error?.type==="overloaded_error")&&d<c){d++,H(`Retrying autonomous agent request (attempt ${d}/${c+1}) due to overloaded error`),await new Promise(h=>setTimeout(h,1e3*d));continue}throw p}let f=l.close();return{content:f.content,wasTruncated:f.wasTruncated,tokenUsage:f.tokenUsage}}}});var $zr=v(()=>{Sie();rhr();Kkr();E1e();Rzr();Dzr();OH();T1e();Rue()});var AZo,Lzr,IZo,Fzr,NZo,kzr,jZo,qzr,P1e=v(()=>{Ev();AZo=`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:`,Lzr=new su({inputVariables:["summary","new_lines"],template:AZo}),IZo=`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:`,Fzr=new su({inputVariables:["entities","history","input"],template:IZo}),NZo=`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:`,kzr=new su({inputVariables:["history","input"],template:NZo}),jZo=`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):`,qzr=new su({inputVariables:["entity","summary","history","input"],template:jZo})});var DZo,$Zo,Bzr,Kle,hpt=v(()=>{Do();F$();z0();U$();js();DZo={};Tt(DZo,{BaseChatMessageHistory:()=>$Zo,BaseListChatMessageHistory:()=>Bzr,InMemoryChatMessageHistory:()=>Kle});$Zo=class extends Wh{async addMessages(t){for(let e of t)await this.addMessage(e)}},Bzr=class extends Wh{addUserMessage(t){return this.addMessage(new au(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.")}},Kle=class extends Bzr{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 M1e(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 LZo,_J,Uzr,vJ,Wle,Gle=v(()=>{Do();LZo={};Tt(LZo,{BaseMemory:()=>_J,getInputValue:()=>vJ,getOutputValue:()=>Wle,getPromptInputKey:()=>M1e});_J=class{},Uzr=(t,e)=>{if(e!==void 0)return t[e];let r=Object.keys(t);if(r.length===1)return t[r[0]]},vJ=(t,e)=>{let r=Uzr(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},Wle=(t,e)=>{let r=Uzr(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 FZo,Ab,CB=v(()=>{Ohe();hpt();Gle();FZo={};j6(FZo,{BaseChatMemory:()=>Ab});Ab=class extends _J{constructor(e){super();M(this,"chatHistory");M(this,"returnMessages",!1);M(this,"inputKey");M(this,"outputKey");this.chatHistory=e?.chatHistory??new Kle,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(vJ(e,this.inputKey)),await this.chatHistory.addAIMessage(Wle(r,this.outputKey))}async clear(){await this.chatHistory.clear()}}});function gpt(t,e){let r=new Set;for(let n of e)t.has(n)&&r.add(n);return r}function zzr(t,e){let r=new Set(t);for(let n of e)r.add(n);return r}function Zle(t,e){let r=new Set(t);for(let n of e)r.delete(n);return r}var Hzr=v(()=>{});var ypt={};Jn(ypt,{SequentialChain:()=>kZo,SimpleSequentialChain:()=>qZo});function Xle(t){return Array.from(t).map(e=>`"${e}"`).join(", ")}var kZo,qZo,bpt=v(()=>{W7();Hzr();kZo=class Vzr extends $y{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=gpt(n,o);if(i.size>0)throw new Error(`The following keys: ${Xle(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=zzr(n,o);for(let s of this.chains){let u=Zle(new Set(s.inputKeys),a);if(s.memory&&(u=Zle(u,new Set(s.memory.memoryKeys))),u.size>0)throw new Error(`Missing variables for chain "${s._chainType()}": ${Xle(u)}. Only got the following variables: ${Xle(a)}.`);let l=new Set(s.outputKeys),c=gpt(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 Kzr({llmChain:await jh.deserialize(r.llm_chain)})}serialize(){return{_type:this._chainType(),llm_chain:this.llmChain.serialize()}}},Wzr=class Gzr extends $y{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 Gzr({llmChain:await jh.deserialize(r.llm_chain),combineDocumentChain:await R1e.deserialize(r.combine_document_chain)})}serialize(){return{_type:this._chainType(),llm_chain:this.llmChain.serialize(),combine_document_chain:this.combineDocumentChain.serialize()}}},Zzr=class Xzr extends $y{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 su({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"]}),zZo=`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}`,HZo=[Zw.fromTemplate(zZo),a_.fromTemplate("{question}")],VZo=pd.fromMessages(HZo),s4r=new Z7(UZo,[[X7,VZo]])});var l4r=v(()=>{Ev();N1e()});var c4r=v(()=>{Ev();N1e()});function d4r(t,e={}){let{prompt:r=s4r.getPrompt(t),verbose:n}=e,o=new jh({prompt:r,llm:t,verbose:n});return new R1e({llmChain:o,verbose:n})}var f4r=v(()=>{wJ();Yle();u4r();l4r();c4r()});var m4r={};Jn(m4r,{VectorDBQAChain:()=>JZo});var JZo,h4r=v(()=>{W7();f4r();JZo=class p4r extends $y{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 p4r({combineDocumentsChain:await $y.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=d4r(r);return new this({vectorstore:n,combineDocumentsChain:i,...o})}}});var g4r,y4r,KZo,b4r,_4r=v(()=>{Ev();g4r=`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:`,y4r=new su({inputVariables:["api_docs","question"],template:g4r}),KZo=`${g4r} {api_url}
Here is the response from the API:
{api_response}
Summarize this response to answer the original question.
Summary:`,b4r=new su({inputVariables:["api_docs","question","api_url","api_response"],template:KZo})});var w4r={};Jn(w4r,{APIChain:()=>WZo});var WZo,S4r=v(()=>{W7();wJ();_4r();WZo=class v4r extends $y{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 v4r({apiAnswerChain:await jh.deserialize(o),apiRequestChain:await jh.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=y4r,apiResponsePrompt:a=b4r}=o,s=new jh({prompt:i,llm:r}),u=new jh({prompt:a,llm:r});return new this({apiAnswerChain:u,apiRequestChain:s,apiDocs:n,...o})}}});var $y,W7=v(()=>{Ov();Gv();gm();H$();$y=class extends IW{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 Gl.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,uN,{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,...aN(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 Dm({pageContent:o,metadata:n})])}}});var j4r,D4r=v(()=>{F$();j4r=class extends Wh{}});var $4r,L4r=v(()=>{D4r();$4r=class extends j4r{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 F4r,k4r=v(()=>{wJ();P1e();CB();L4r();js();Gle();F4r=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 jh({llm:this.llm,prompt:e.entityExtractionPrompt??kzr}),this.entitySummarizationChain=new jh({llm:this.llm,prompt:e.entitySummarizationPrompt??qzr}),this.entityStore=e.entityStore??new $4r,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??M1e(e,this.memoryVariables),n=await this.chatHistory.getMessages(),o=Xu(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??M1e(e,this.memoryVariables),o=await this.chatHistory.getMessages(),i=Xu(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 q4r,B4r=v(()=>{CB();q4r=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 U4r,z4r=v(()=>{CB();js();U4r=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=pd.fromMessages([Zw.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 J4r,rce,K4r=v(()=>{Us();Hc();Zr();$zr();Bt();jt();yr();Yw();Ev();J4r=require("obsidian");bue();H4r();V4r();qNe();rce=class{constructor(e){this.retrievedDocuments=[];this.pendingModelError=null;this.app=e,this.memoryManager=ece.getInstance(),this.chatModelManager=gI.getInstance(),this.promptManager=tce.getInstance(),this.userMemoryManager=new Yq(e),this.initialize(),Yl(async()=>{await this.createChainWithNewModel()})}getRetrievedDocuments(){return this.retrievedDocuments}async initialize(){await this.createChainWithNewModel()}getChain(){return this.chain}getRetrievalChain(){return this.retrievalChain}validateChainType(e){if(e==null)throw new Error("No chain type set")}validateChatModel(){if(this.pendingModelError)throw this.pendingModelError;if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){let e="Chat model is not initialized properly, check your API key in Copilot setting and make sure you have API access.";throw new k6(e)}}validateChainInitialization(){(!this.chain||!MRt(this.chain))&&(H("Reinitializing chat chain after detecting missing or unsupported instance."),this.createChainWithNewModel({},!1))}storeRetrieverDocuments(e){this.retrievedDocuments=e}async createChainWithNewModel(e={},r=!0){let n,o=RO(),i=tl();if(!(o==="project"&&!i))try{if(n=o==="project"?i?.projectModelKey:Pv(),!n)throw new k6("No model key found. Please select a model in settings.");if(r){let a=Qw(n,ce().activeModels);if(a||(console.error("Resetting default model. No model configuration found for: ",n),a=SO[0],n=a.name+"|"+a.provider),o==="project"&&!a.projectEnabled){let u=ce().activeModels.find(l=>l.enabled&&l.projectEnabled);if(u)a=u,n=u.name+"|"+u.provider,new J4r.Notice(`Model ${a.name} is not available in project mode. Switching to ${u.name}.`);else throw new Error("No project-enabled models available. Please enable a model for project mode in settings.")}let s={...a,...i?.modelConfigs};await this.chatModelManager.setChatModel(s),this.pendingModelError=null}this.setChain(o,e),H(`Setting model to ${n}`)}catch(a){this.pendingModelError=a instanceof Error?a:new Error(String(a)),ue(`createChainWithNewModel failed: ${a}`),H(`modelKey: ${n||Pv()}`)}}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=nee.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),bL("llm_chain");break}case"vault_qa":{await this.initializeQAChain(r);let a=ce(),s=a.enableSemanticSearchV3?new(await Promise.resolve().then(()=>(TNe(),Tdt))).HybridRetriever({minSimilarityScore:.01,maxK:a.maxSourceChunks,salientTerms:[]}):new(await Promise.resolve().then(()=>(m7(),ONe))).TieredLexicalRetriever(app,{minSimilarityScore:.01,maxK:a.maxSourceChunks,salientTerms:[],timeRange:void 0,textWeight:void 0,returnAll:!1,useRerankerThreshold:void 0});this.retrievalChain=nee.createConversationalRetrievalChain({llm:n,retriever:s,systemMessage:jz()},this.storeRetrieverDocuments.bind(this),ce().debug),bL("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=nee.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),bL("copilot_plus");break}case"project":{await this.initializeQAChain(r),this.chain=nee.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),bL("project");break}default:this.validateChainType(e);break}}getC
`,e.message),this.validateChatModel(),this.validateChainInitialization();let s=this.chatModelManager.getChatModel();if(a||tee(s)){let l=pd.fromMessages([new vO("history"),a_.fromTemplate("{input}")]);tee(s)&&(l=pd.fromMessages([[Zs,jz()||""],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===Zs&&await this.memoryManager.getMemory().saveContext({input:n.message},{output:o.message})}}}});var L1e,W4r=v(()=>{Us();Bt();jt();yr();bie();L1e=class t{constructor(e){this.app=e}static getInstance(e){return t.instance||(t.instance=new t(e)),t.instance}clearAllLoadStates(){aHe({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=J1(o)?"Rate limit exceeded. (Rate limit: 50 files or 100MB per 3 hours, whichever is reached first)":Mo(o);throw this.setFileOrUrlProcessFailed(e,r,i),o}}setFileOrUrlStartProcess(e){Kn.set(RN,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){Y0("processingFiles",r=>r.filter(n=>n!==e)),Y0("success",r=>r.includes(e)?r:[...r,e])}setFileOrUrlProcessFailed(e,r,n){Y0("processingFiles",o=>o.filter(i=>i!==e)),Y0("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){H(`[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])];Y0("total",s=>a),H(`[preComputeAllItems] Project ${e.name}: Added ${n.length} items to tracking (${a.length} total unique items)`)}}markAllCachedItemsAsSuccess(e,r,n){H(`[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&&H(`[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&&H(`[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&&H(`[markAllCachedItemsAsSuccess] Project ${e.name}: Marked ${s.length} cached files that match current project patterns as successful.`)}}markCachedItemAsSuccess(e){Y0("total",r=>r.includes(e)?r:[...r,e]),Y0("success",r=>r.includes(e)?r:[...r,e])}makeItemFailed(e,r,n){Y0("total",o=>o.includes(e)?o:[...o,e]),Y0("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 SJ,xg,Ik=v(()=>{Us();yie();Hc();Zr();Bt();Jnt();vb();jt();vOe();yr();bie();SJ=require("obsidian");CA();K4r();W4r();xg=class t{constructor(e,r){this.app=e,this.plugin=r,this.currentProjectId=null,this.chainMangerInstance=new rce(e),this.projectContextCache=zC.getInstance(),this.fileParserManager=new Mk(cc.getInstance(),this.app.vault,!0,null),this.loadTracker=L1e.getInstance(this.app),tHe(async()=>{await this.getCurrentChainManager().createChainWithNewModel()}),rHe(async()=>{if(Wz())return;let n=ce(),o=n.enableSemanticSearchV3&&n.indexVaultToVectorStore==="ON MODE SWITCH"&&(RO()==="vault_qa"||RO()==="copilot_plus");await this.getCurrentChainManager().createChainWithNewModel({refreshIndex:o})}),Kz(async n=>{await this.switchProject(n)}),this.setupProjectListChangeMonitor()}setupProjectListChangeMonitor(){Yl(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(),X0(!0),H("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 Mk(cc.getInstance(),this.app.vault,!0,e),await this.loadProjectContext(e),this.refreshChatView(),H(`Switched to project: ${e.name}`)}catch(r){throw ue(`Failed to switch project: ${r}`),r}finally{X0(!1)}}async saveCurrentProjectMessage(){await this.plugin.autosaveCurrentChat()}async loadNextProjectMessage(){await this.plugin.chatUIState.handleProjectSwitch()}async loadProjectContext(e,r=!1){r&&(this.loadTracker.clearAllLoadStates(),X0(!0));try{if(!e.contextSource)return it(`[loadProjectContext] Project ${e.name}: No contextSource. Aborting.`),null;H(`[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),H(`[loadProjectContext] Completed for project: ${e.name}.`),i}catch(n){throw ue(`[loadProjectContext] Failed for project ${e.name}:`,n),n}finally{r&&X0(!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(Cc)[0]?.view;e&&e.updateView()}async getProjectContext(e){let r=ce().projectList.find(o=>o.id===e);if(!r)return it(`[getProjectContext] Project not found for ID: ${e}`),null;H(`[getProjectContext] Getting context for project: ${r.name} (ID: ${e})`);let n=this.projectContextCache.getSync(r);if(!n||n.markdownNeedsReload){n?H(`[getProjectContext] Project ${r.name}: Markdown needs reload. Triggering full load.`):H(`[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 H(`[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(H(`[processMarkdownFiles] Starting for project: ${e.name}`),r.markdownNeedsReload||!r.markdownContext||!r.markdownContext.trim()){H(`[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,H(`[processMarkdownFiles] Project ${e.name}: Markdown content updated.`)}else H(`[processMarkdownFiles] Project ${e.name}: Markdown content already up-to-date.`);return H(`[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");H(`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,H(`Completed processing markdown file: ${o.path}`)}catch(s){ue(`Error processing file ${o.path}: ${s}`),i=`[Error: ${Mo(s)}]`}return`${a}
${i}`}));return H("All markdown files processed for project context"),n.join(`
`)}async processWebUrls(e,r){H(`[processWebUrls] Starting for project: ${e.name}`);let n=e.contextSource?.webUrls?.trim()||"";if(!n)return Object.keys(r.webContexts).length>0&&(H(`[processWebUrls] Project ${e.name}: Clearing all Web contexts as none are configured.`),r.webContexts={}),r;let o=n.split(`
`).filter(c=>c.trim());H(`[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&&H(`[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){H(`[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&&H(`[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&&it(`[processWebUrls] Project ${e.name}: Fetched empty content for Web URL: ${c.url}`)}),H(`[processWebUrls] Completed for project: ${e.name}. Total Web contexts: ${Object.keys(r.webContexts).length}`),r}async processYoutubeUrls(e,r){H(`[processYoutubeUrls] Starting for project: ${e.name}`);let n=e.contextSource?.youtubeUrls?.trim()||"";if(!n)return Object.keys(r.youtubeContexts).length>0&&(H(`[processYoutubeUrls] Project ${e.name}: Clearing all YouTube contexts as none are configured.`),r.youtubeContexts={}),r;let o=n.split(`
`).filter(c=>c.trim());H(`[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&&H(`[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){H(`[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&&H(`[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&&it(`[processYoutubeUrls] Project ${e.name}: Fetched empty transcript for YouTube URL: ${c.url}`)}),H(`[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=Y8.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()=>cc.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 SJ.Notice(`Failed to process YouTube URL ${e}: ${Mo(r)}`),""}}async processNonMarkdownFiles(e,r){let n=r.filter(i=>i.extension!=="md");if(H(`[loadProjectContext] Project ${e.name}: Checking for non-markdown processing: ${n.length} files .`),n.length<=0)return;this.fileParserManager=new Mk(cc.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)||(H(`[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),J1(s))throw s}}o>0&&H(`[loadProjectContext] Project ${e.name}: Processed and cached ${o} non-markdown files.`)}async retryFailedItem(e){try{if(!this.currentProjectId){it("[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(H(`[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:it(`[retryFailedItem] Unknown item type: ${e.type}`);return}H(`[retryFailedItem] Successfully retried ${e.type} item: ${e.path}`),new SJ.Notice(`Retry successful: ${e.path}`)}catch(r){ue(`[retryFailedItem] Failed to retry ${e.type} item ${e.path}:`,r),new SJ.Notice(`Retry failed: ${Mo(r)}`)}}async retryWebUrl(e,r){let n=await this.processWebUrlContext(r);if(!n){it(`[retryWebUrl] Project ${e.name}: Fetched empty content for Web URL: ${r}`);return}H(`[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){it(`[retryYoutubeUrl] Project ${e.name}: Fetched empty transcript for YouTube URL: ${r}`);return}H(`[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 SJ.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()=>{}),H(`[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 SJ.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)),H(`[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}=td({inclusions:e.contextSource.inclusions,exclusions:e.contextSource.exclusions,isProject:!0});return this.app.vault.getFiles().filter(o=>cl(o,r,n,!0))}onunload(){this.projectContextCache.cleanup()}}});var fde=S((DGr,h$e)=>{((t,e)=>{typeof define=="function"&&define.amd?define([],e):typeof h$e=="object"&&h$e.exports?h$e.exports=e():t.fuzzysort=e()})(DGr,t=>{"use strict";var e=($,q)=>{if(!$||!q)return z;var Y=p($);J(q)||(q=f(q));var D=Y.bitflags;retu
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 oZ=require("obsidian");jt();CN();CN();var xJ=$6(),OJ=oh([]),Lpt=new Set;function TJ(t){Lpt.add(t)}function EJ(t){Lpt.delete(t)}function nce(t){return Lpt.has(t)}function oce(t){let e=xJ.get(OJ);xJ.set(OJ,e.filter(r=>r.title!==t))}function PJ(t,e){let r=xJ.get(OJ),n;(e?r.findIndex(i=>i.title===e):-1)!==-1?n=r.map(i=>i.title===e?t:i):n=[...r,t],xJ.set(OJ,n)}function V1e(t){xJ.set(OJ,t)}function J1e(){return Xw(OJ,{store:xJ})}function K_(){return xJ.get(OJ)}oee();yr();Zr();function K1e(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 iZ(t){return encodeURIComponent(t.toLowerCase())}function PB(){return(0,oZ.normalizePath)(ce().customPromptsFolder)}function aZ(t){return`${PB()}/${t}.md`}function sZ(t){if(!(t instanceof oZ.TFile)||t.extension!=="md")return!1;let e=PB();return!(!t.path.startsWith(e+"/")||t.path.slice(e.length+1).includes("/"))}function xXo(t){if(t.startsWith("---")){let e=t.indexOf("---",3);if(e!==-1)return t.slice(e+3).trimStart()}return t}function S2r(t){return app.metadataCache.getFileCache(t)?.frontmatter?.[SI]!=null}async function ice(t){let e=await app.vault.read(t),r=xXo(e),n=app.metadataCache.getFileCache(t),o=n?.frontmatter?.[KD]??wI.showInContextMenu,i=n?.frontmatter?.[WD]??wI.showInSlashMenu,a=n?.frontmatter?.[ZD]??wI.lastUsedMs,s=n?.frontmatter?.[SI]??wI.order,u=n?.frontmatter?.[GD]??wI.modelKey;return{title:t.basename,modelKey:u,content:r,showInContextMenu:o,showInSlashMenu:i,order:s,lastUsedMs:a}}async function W1e(){let t=app.vault.getFiles().filter(r=>sZ(r)),e=await Promise.all(t.map(ice));return V1e(e),e}function ace(t){return[...t].sort((e,r)=>e.order===r.order?e.title.localeCompare(r.title):e.order-r.order)}function OXo(t){return[...t].sort((e,r)=>e.lastUsedMs===r.lastUsedMs?e.title.localeCompare(r.title):r.lastUsedMs-e.lastUsedMs)}function TXo(t){return[...t].sort((e,r)=>e.title.localeCompare(r.title))}function G1e(t){switch(ce().promptSortStrategy){case"timestamp":return OXo(t);case"alphabetical":return TXo(t);case"manual":return ace(t);default:return t}}async function Fpt(t,e,r=!1){let o=(await kpt(t,e,app.vault,app.workspace.getActiveFile())).processedPrompt;if(o.includes(`{${s_}}`)||r)return o;let i=o.indexOf($pt);return i===-1&&e.trim()?o+`
<`+s_+">"+e+"</"+s_+">":o.slice(0,i)+e+o.slice(i+$pt.length)}var EXo=/\{(?!copilot-selection\}|\[\[)([^}]+)\}/g;async function PXo(t,e,r){let n=new Map,o=new Set,i;for(;(i=EXo.exec(t))!==null;){let a=i[1].trim(),s={content:"",files:[]};if(a.toLowerCase()==="activenote")if(r){let u=await B6(r,e);u&&(s.content=`<${Uz}>
<path>${r.path}</path>
## ${jhe(r)}
${u}
</${Uz}>`,s.files.push(r))}else new oZ.Notice("No active note found.");else if(a.startsWith("#")){let u=a.slice(1).split(",").map(d=>d.trim()),l=await Nhe(e,u),c=[];for(let d of l){let f=await B6(d,e);f&&(c.push(`<${Uz}>
<path>${d.path}</path>
## ${jhe(d)}
${f}
</${Uz}>`),s.files.push(d))}s.content=c.join(`
`)}else{let u=NRt(a),l=await QQ(e,u),c=[];for(let d of l){let f=await B6(d,e);f&&(c.push(`<${Uz}>
<path>${d.path}</path>
## ${jhe(d)}
${f}
</${Uz}>`),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 kpt(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 PXo(t,r,n);s.forEach(f=>i.add(f));let u=t,l="",c=null;u.includes("{}")&&(u=u.replace(/\{\}/g,`{${s_}}`),e?l+=`<${s_}>
${e}
</${s_}>`:n?(c=await B6(n,r),l+=`<${s_} type="active_note">
${c||""}
</${s_}>`,i.add(n)):l+=`<${s_}>
(No selected text or active note available)
</${s_}>`);for(let[f,p]of a.entries())f.toLowerCase()==="activenote"&&c!==null||(l?l+=`
<${aee} name="${f}">
${p}
</${aee}>`:l+=`<${aee} name="${f}">
${p}
</${aee}>`);let d=IRt(u,r);for(let f of d)if(!i.has(f)){let p=await B6(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=`<${iee}>
<title>${f.basename}</title>
<path>${f.path}</path>
<ctime>${h}</ctime>
<mtime>${g}</mtime>
<content>
${p}
</content>
</${iee}>`;l&&(l+=`
`),l+=`${y}`,i.add(f)}}return{processedPrompt:l?`${u}
${l}`:`${u}
`,includedFiles:Array.from(i)}}function C2r(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 Z1e(){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 qpt(t,e){try{TJ(t.path),await app.fileManager.processFrontMatter(t,r=>{r[KD]==null&&(r[KD]=e.showInContextMenu),r[WD]==null&&(r[WD]=e.showInSlashMenu),r[SI]==null&&(r[SI]=e.order),r[GD]==null&&(r[GD]=e.modelKey),r[ZD]==null&&(r[ZD]=e.lastUsedMs)})}finally{EJ(t.path)}}function X1e(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()===`\`\`\`${nZ}`){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 MXo({commands:t,command:e,onConfirm:r,onCancel:n}){let i=Wn().activeModels.filter(f=>f.enabled).map(f=>({label:H1e(f),value:Qn(f)})),[a,s]=(0,As.useState)(e),[u,l]=(0,As.useState)({}),c=(f,p)=>{s(m=>({...m,[f]:p})),l(m=>({...m,[f]:void 0}))},d=()=>{let f={},p=K1e(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 As.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4 tw-p-4"},As.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},As.default.createElement(Ib,{htmlFor:"title"},"Name"),As.default.createElement(yi,{id:"title",value:a.title,onChange:f=>c("title",f.target.value),placeholder:"Enter command name"}),u.title&&As.default.createElement("div",{className:"tw-text-sm tw-text-error"},u.title)),As.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},As.default.createElement(Ib,{htmlFor:"content"},"Prompt"),As.default.createElement(v2r,null),As.default.createElement(xx,{id:"content",value:a.content,onChange:f=>c("content",f.target.value),placeholder:"Enter command prompt",className:"tw-min-h-[200px]"}),u.content&&As.default.createElement("div",{className:"tw-text-sm tw-text-error"},u.content)),As.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},As.default.createElement(Ib,{htmlFor:"modelKey"},"Model (Optional)"),As.default.createElement("div",{className:"tw-group tw-relative tw-w-full"},As.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")},As.default.createElement("option",{value:""},"Inherit from chat model"),i.map(f=>As.default.createElement("option",{key:f.value,value:f.value.toString()},f.label))),As.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")},As.default.createElement(Ys,{className:"tw-size-4"})))),As.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},As.default.createElement(od,{id:"showInContextMenu",checked:a.showInContextMenu,onCheckedChange:f=>c("showInContextMenu",f)}),As.default.createElement(Ib,{htmlFor:"showInContextMenu"},"Show in context menu")),As.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},As.default.createElement(od,{id:"showInSlashMenu",checked:a.showInSlashMenu,onCheckedChange:f=>c("showInSlashMenu",f)}),As.default.createElement(Ib,{htmlFor:"showInSlashMenu"},"Show in slash menu")),As.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},As.default.createElement(we,{variant:"secondary",onClick:n},"Cancel"),As.default.createElement(we,{variant:"default",onClick:d},"Save")))}var MB=class extends x2r.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,O2r.createRoot)(r);let n=o=>{this.onUpdate(o),this.close()};this.root.render(As.default.createElement(MXo,{commands:this.commands,command:this.command,onConfirm:n,onCancel:()=>this.close()}))}onClose(){this.root.unmount()}};var sce=require("obsidian");Yw();yr();var Lg=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=aZ(e.title);try{TJ(o);let i=e.order;n.autoOrder&&(i=Z1e()),e={...e,order:i};let a=PB();await Qh(a);let
Source: ${d.url}
${d.transcript}`;await navigator.clipboard.writeText(w),new uZ.Notice("Transcript copied to clipboard!")}catch(w){ue("Failed to copy to clipboard:",w),new uZ.Notice("Failed to copy to clipboard")}},y=async()=>{if(d)try{let w=`# YouTube Video Transcript
Source: ${d.url}
${d.transcript}`;await Fz(w,!1),t()}catch(w){ue("Failed to insert to note:",w),new uZ.Notice("Failed to insert to note")}},b=()=>{r("input"),o(""),u(""),f(null)},_=w=>{w.key==="Enter"&&!i&&l&&h()};return e==="display"&&d?Mu.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Mu.createElement("div",{className:"tw-rounded tw-bg-secondary tw-p-3"},Mu.createElement("a",{href:d.url,className:"tw-text-sm tw-text-muted hover:tw-text-normal",target:"_blank",rel:"noopener noreferrer"},d.url)),Mu.createElement("div",{className:"tw-max-h-96 tw-overflow-y-auto tw-rounded tw-border tw-border-border tw-bg-primary tw-p-4"},Mu.createElement("div",{className:"tw-whitespace-pre-wrap tw-text-sm tw-leading-relaxed"},d.transcript)),Mu.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},Mu.createElement(we,{variant:"ghost",onClick:b},"Download Another"),Mu.createElement(we,{variant:"default",onClick:g},"Copy to Clipboard"),Mu.createElement(we,{variant:"default",onClick:y},"Insert at Cursor"),Mu.createElement(we,{variant:"secondary",onClick:t},"Close"))):Mu.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Mu.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Mu.createElement("div",{className:"tw-text-sm tw-text-muted"},"Enter a valid YouTube video URL"),Mu.createElement(yi,{placeholder:"https://www.youtube.com/watch?v=...",value:n,onChange:w=>m(w.target.value),onKeyDown:_,disabled:i}),s&&Mu.createElement("div",{className:"tw-text-sm tw-text-error"},s)),Mu.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},Mu.createElement(we,{variant:"secondary",onClick:t,disabled:i},"Cancel"),Mu.createElement(we,{variant:"default",onClick:h,disabled:i||!l},i?"Downloading...":"Download Transcript")))}var eje=class extends uZ.Modal{constructor(e){super(e),this.setTitle("Download YouTube Script (plus)")}onOpen(){let{contentEl:e}=this;this.root=(0,E2r.createRoot)(e);let r=()=>{this.close()};this.root.render(Mu.createElement(IXo,{onClose:r}))}onClose(){this.root.unmount()}};Lv();vb();yr();var Ka=require("obsidian");kU();Zr();function Fg(t,e,r){t.addCommand({id:e,name:qhe[e],callback:r})}function P2r(t,e,r){t.addCommand({id:e,name:qhe[e],editorCallback:r})}function NXo(t,e,r){t.addCommand({id:e,name:qhe[e],checkCallback:r})}function Bpt(t,e,r){P2r(t,Gn.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 Ka.Notice(`Selected text contains ${i} words and ${a} tokens.`)}),Fg(t,Gn.COUNT_TOTAL_VAULT_TOKENS,async()=>{try{let n=await Int(t.app),o=await t.projectManager.getCurrentChainManager().chatModelManager.countTokens(n);new Ka.Notice(`Total tokens in your vault: ${o}`)}catch(n){ue("Error counting tokens: ",n),new Ka.Notice("An error occurred while counting tokens.")}}),Fg(t,Gn.TOGGLE_COPILOT_CHAT_WINDOW,()=>{t.toggleView()}),Fg(t,Gn.OPEN_COPILOT_CHAT_WINDOW,()=>{t.activateView()}),Fg(t,Gn.NEW_CHAT,()=>{tG(),t.newChat()}),NXo(t,Gn.TRIGGER_QUICK_COMMAND,n=>{let o=t.app.workspace.getActiveViewOfType(Ka.MarkdownView);if(n)return!!(!P2e()&&o&&o.editor);if(P2e())return new Ka.Notice("Quick command is not available in source mode."),!1;if(!o||!o.editor)return new Ka.Notice("No active editor found."),!1;let i=o.editor;if(!i.getSelection().trim())return new Ka.Notice("Please select some text first. Selected text is required for quick commands."),!1;X1e(i);let u=i.getCursor("from").line,l=`\`\`\`${nZ}
\`\`\`
`;return i.replaceRange(l,{line:u,ch:0}),!0}),Fg(t,Gn.CLEAR_LOCAL_COPILOT_INDEX,async()=>{try{await(await Promise.resolve().then(()=>($m(),Cg))).default.getInstance().clearIndex(),new Ka.Notice("Cleared local Copilot semantic index.")}catch(n){ue("Error clearing semantic index:",n),new Ka.Notice("Failed to clear semantic index.")}}),Fg(t,Gn.GARBAGE_COLLECT_COPILOT_INDEX,async()=>{try{let o=await(await Promise.resolve().then(()=>($m(),Cg))).default.getInstance().garbageCollectVectorStore();new Ka.Notice(`Garbage collection completed. Removed ${o} stale documents.`)}catch(n){ue("Error during garbage collection:",n),new Ka.Notice("Failed to garbage collect semantic index.")}}),Fg(t,Gn.INDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let{getSettings:n}=await Promise.resolve().then(()=>(jt(),GQ));if(n().enableSemanticSearchV3){let a=await(await Promise.resolve().then(()=>($m(),Cg))).default.getInstance().indexVaultToVectorStore(!1);new Ka.Notice(`Semantic search index refreshed with ${a} documents.`)}else new Ka.Notice("Lexical search builds indexes on demand. No manual indexing required.")}catch(n){ue("Error building index:",n),new Ka.Notice("An error occurred while building the index.")}}),Fg(t,Gn.FORCE_REINDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let{getSettings:n}=await Promise.resolve().then(()=>(jt(),GQ));if(n().enableSemanticSearchV3){let a=await(await Promise.resolve().then(()=>($m(),Cg))).default.getInstance().indexVaultToVectorStore(!0);new Ka.Notice(`Semantic search index rebuilt with ${a} documents.`)}else new Ka.Notice("Lexical search builds indexes on demand. No manual indexing required.")}catch(n){ue("Error rebuilding index:",n),new Ka.Notice("An error occurred while rebuilding the index.")}}),Fg(t,Gn.LOAD_COPILOT_CHAT_CONVERSATION,()=>{t.loadCopilotChatHistory()}),Fg(t,Gn.LIST_INDEXED_FILES,async()=>{try{let o=await(await Promise.resolve().then(()=>($m(),Cg))).default.getInstance().getIndexedFiles(),{getMatchingPatterns:i,shouldIndexFile:a}=await Promise.resolve().then(()=>(vb(),Omr)),{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 Qh(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 Ka.Notice(`Listed ${p.size} indexed files`))}catch(n){ue("Error listing indexed files:",n),new Ka.Notice("Failed to list indexed files.")}}),Fg(t,Gn.INSPECT_COPILOT_INDEX_BY_NOTE_PATHS,async()=>{try{let n=t.app.workspace.getActiveFile();if(!n){new Ka.Notice("No active file. Please open a note first.");return}let o=(await Promise.resolve().then(()=>($m(),Cg))).default,{DBOperations:i}=await Promise.resolve().then(()=>(fie(),Pmr)),a=await o.getInstance().getDb(),s=await i.getDocsByPath(a,n.path);if(!s||s.length===0){new Ka.Notice(`No embedding data found for: ${n.path}`);return}let u=s.map(h=>h.document),l=[`# Embedding Debug: ${n.basename}`,"",`**Path:** ${n.path}`,`**Chunks:** ${u.length}`,`**Embedding Model:** ${u[0]?.embeddingModel||"unknown"}`,"",...u.flatMap((h,g)=>{let y=h.embedding||[],b=y.slice(0,10).map(_=>_.toFixed(6)).join(", ");return[`## Chunk ${g+1}`,`- **ID:** ${h.id}`,`- **Content Preview:** "${(h.content||"").substring(0,200)}..."`,`- **Vector Length:** ${y.length}`,`- **Vector Preview:** [${b}${y.length>10?", ...":""}]`,`- **Tags:** ${(h.tags||[]).join(", ")||"none"}`,`- **Characters:** ${h.nchars||0}`,""]})].join(`
`),c=`Copilot-Embedding-Debug-${n.basename.replace(/[\\/:*?"<>|]/g,"_")}.md`,d="copilot",f=`${d}/${c}`;await Qh(d);let p=t.app.vault.getAbstractFileByPath(f);p?await t.app.vault.modify(p,l):await t.app.vault.create(f,l);let m=t.app.vault.getAbstractFileByPath(f);m&&(await t.app.workspace.getLeaf().openFile(m),new Ka.Notice(`Embedding debug info for ${u.length} chunk(s)`))}catch(n){ue("Error inspecting embeddings:",n),new Ka.Notice("Failed to inspect embeddings. Is the index loaded?")}}),Fg(t,Gn.CLEAR_COPILOT_CACHE,async()=>{try{await t.fileParserManager.clearPDFCache(),await zC.getInstance().clearAllCache(),await X8.getInstance().clear(),new Ka.Notice("All Copilot caches cleared successfully")}catch(n){ue("Error clearing Copilot caches:",n),new Ka.Notice("Failed to clear Copilot caches")}}),Fg(t,Gn.OPEN_LOG_FILE,async()=>{try{await COe(),await bm.openLogFile()}catch(n){ue("Error creating Copilot log file:",n),new Ka.Notice("Failed to create Copilot log file.")}}),Fg(t,Gn.CLEAR_LOG_FILE,async()=>{try{await bm.clear(),new Ka.Notice("Copilot log cleared.")}catch(n){ue("Error clearing Copilot log file:",n),new Ka.Notice("Failed to clear Copilot log file.")}}),P2r(t,Gn.ADD_SELECTION_TO_CHAT_CONTEXT,async n=>{let o=n.getSelection();if(!o){new Ka.Notice("No text selected");return}let i=t.app.workspace.getActiveFile();if(!i){new Ka.Notice("No active file");return}let a=n.listSelections()[0];if(!a){new Ka.Notice("Could not determine selection range");return}let s=a.anchor.line+1,u=a.head.line+1,l={id:gv(),content:o,noteTitle:i.basename,notePath:i.path,startLine:Math.min(s,u),endLine:Math.max(s,u)},{setSelectedTextContexts:c}=await Promise.resolve().then(()=>(Us(),hAt));c([l]),t.activateView()}),Fg(t,Gn.ADD_CUSTOM_COMMAND,async()=>{let n=K_(),o={...wI};new MB(t.app,n,o,async a=>{await Lg.getInstance().createCommand(a)}).open()}),Fg(t,Gn.APPLY_CUSTOM_COMMAND,()=>{new Y1e(t.app).open()}),Fg(t,Gn.DOWNLOAD_YOUTUBE_SCRIPT,async()=>{if(!await DS()){new Ka.Notice("Download YouTube Script (plus) is a Copilot Plus feature");return}new eje(t.app).open()})}Us();Hc();Hc();Us();function tje(){let[t]=l_(),[e]=pee(),[r]=mee();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"})()}Bt();Us();yie();Hc();Fo();var M2r=require("obsidian"),MJ=L(X()),R2r=L(Sm());function jXo({content:t,onConfirm:e,onCancel:r,confirmButtonText:n,cancelButtonText:o}){return MJ.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-5"},MJ.default.createElement("div",{className:"tw-whitespace-pre-wrap"},t),MJ.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},o&&MJ.default.createElement(we,{variant:"secondary",onClick:r},o),n&&MJ.default.createElement(we,{variant:"default",onClick:e},n)))}var sm=class extends M2r.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,R2r.createRoot)(r);let n=()=>{this.onConfirm(),this.close()},o=()=>{this.close()};this.root.render(MJ.default.createElement(jXo,{content:this.content,onConfirm:n,onCancel:o,confirmButtonText:this.confirmButtonText,cancelButtonText:this.cancelButtonText}))}onClose(){this.root.unmount()}};Fo();var Ru=L(X());var Vm=L(X(),1);var yfs=!!(typeof window<"u"&&window.document&&window.document.createElement);function uce(t,e,{checkForDefaultPrevented:r=!0}={}){return function(o){if(t?.(o),r===!1||!o.defaultPrevented)return e?.(o)}}var DXo=L(X(),1);function A2r(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function I2r(...t){return e=>{let r=!1,n=t.map(o=>{let i=A2r(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():A2r(t[o],null)}}}}var XD=L(X(),1),N2r=L(ht(),1);function j2r(t,e=[]){let r=[];function n(i,a){let s=XD.createContext(a),u=r.length;r=[...r,a];let l=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?
.`.concat(gmt,` {
overflow: hidden `).concat(n,`;
padding-right: `).concat(s,"px ").concat(n,`;
}
body[`).concat(bZ,`] {
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(Rx,` {
right: `).concat(s,"px ").concat(n,`;
}
.`).concat(Ax,` {
margin-right: `).concat(s,"px ").concat(n,`;
}
.`).concat(Rx," .").concat(Rx,` {
right: 0 `).concat(n,`;
}
.`).concat(Ax," .").concat(Ax,` {
margin-right: 0 `).concat(n,`;
}
body[`).concat(bZ,`] {
`).concat(ymt,": ").concat(s,`px;
}
`)},WVr=function(){var t=parseInt(document.body.getAttribute(bZ)||"0",10);return isFinite(t)?t:0},kQo=function(){_Z.useEffect(function(){return document.body.setAttribute(bZ,(WVr()+1).toString()),function(){var t=WVr()-1;t<=0?document.body.removeAttribute(bZ):document.body.setAttribute(bZ,t.toString())}},[])},qJ=function(t){var e=t.noRelative,r=t.noImportant,n=t.gapMode,o=n===void 0?"margin":n;kQo();var i=_Z.useMemo(function(){return Smt(o)},[o]);return _Z.createElement(LQo,{styles:FQo(i,!e,o,r?"":"!important")})};var Cmt=!1;if(typeof window<"u")try{yce=Object.defineProperty({},"passive",{get:function(){return Cmt=!0,!0}}),window.addEventListener("test",yce,yce),window.removeEventListener("test",yce,yce)}catch{Cmt=!1}var yce,BJ=Cmt?{passive:!1}:!1;var qQo=function(t){return t.tagName==="TEXTAREA"},GVr=function(t,e){if(!(t instanceof Element))return!1;var r=window.getComputedStyle(t);return r[e]!=="hidden"&&!(r.overflowY===r.overflowX&&!qQo(t)&&r[e]==="visible")},BQo=function(t){return GVr(t,"overflowY")},UQo=function(t){return GVr(t,"overflowX")},xmt=function(t,e){var r=e.ownerDocument,n=e;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var o=ZVr(t,n);if(o){var i=XVr(t,n),a=i[1],s=i[2];if(a>s)return!0}n=n.parentNode}while(n&&n!==r.body);return!1},zQo=function(t){var e=t.scrollTop,r=t.scrollHeight,n=t.clientHeight;return[e,r,n]},HQo=function(t){var e=t.scrollLeft,r=t.scrollWidth,n=t.clientWidth;return[e,r,n]},ZVr=function(t,e){return t==="v"?BQo(e):UQo(e)},XVr=function(t,e){return t==="v"?zQo(e):HQo(e)},VQo=function(t,e){return t==="h"&&e==="rtl"?-1:1},YVr=function(t,e,r,n,o){var i=VQo(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=XVr(t,s),m=p[0],h=p[1],g=p[2],y=h-g-i*m;(m||y)&&ZVr(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 Aje=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},QVr=function(t){return[t.deltaX,t.deltaY]},eJr=function(t){return t&&"current"in t?t.current:t},JQo=function(t,e){return t[0]===e[0]&&t[1]===e[1]},KQo=function(t){return`
.block-interactivity-`.concat(t,` {pointer-events: none;}
.allow-interactivity-`).concat(t,` {pointer-events: all;}
`)},WQo=0,vZ=[];function tJr(t){var e=pl.useRef([]),r=pl.useRef([0,0]),n=pl.useRef(),o=pl.useState(WQo++)[0],i=pl.useState(r$)[0],a=pl.useRef(t);pl.useEffect(function(){a.current=t},[t]),pl.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var h=yZ([t.lockRef.current],(t.shards||[]).map(eJr),!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=pl.useCallback(function(h,g){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!a.current.allowPinchZoom;var y=Aje(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=xmt(E,O);if(!T)return!0;if(T?x=E:(x=E==="v"?"h":"v",T=xmt(E,O)),!T)return!1;if(!n.current&&"changedTouches"in h&&(_||w)&&(n.current=x),!x)return!0;var R=n.current||x;return YVr(R,g,h,R==="h"?_:w,!0)},[]),u=pl.useCallback(function(h){var g=h;if(!(!vZ.length||vZ[vZ.length-1]!==i)){var y="deltaY"in g?QVr(g):Aje(g),b=e.current.filter(function(x){return x.name===g.type&&(x.target===g.target||g.target===x.shadowParent)&&JQo(x.delta,y)})[0];if(b&&b.should){g.cancelable&&g.preventDefault();return}if(!b){var _=(a.current.shards||[]).map(eJr).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=pl.useCallback(function(h,g,y,b){var _={name:h,delta:g,target:y,should:b,shadowParent:GQo(y)};e.current.push(_),setTimeout(function(){e.current=e.current.filter(function(w){return w!==_})},1)},[]),c=pl.useCallback(function(h){r.current=Aje(h),n.current=void 0},[]),d=pl.useCallback(function(h){l(h.type,QVr(h),h.target,s(h,t.lockRef.current))},[]),f=pl.useCallback(function(h){l(h.type,Aje(h),h.target,s(h,t.lockRef.current))},[]);pl.useEffect(function(){return vZ.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,BJ),document.addEventListener("touchmove",u,BJ),document.addEventListener("touchstart",c,BJ),function(){vZ=vZ.filter(function(h){return h!==i}),document.removeEventListener("wheel",u,BJ),document.removeEventListener("touchmove",u,BJ),document.removeEventListener("touchstart",c,BJ)}},[]);var p=t.removeScrollBar,m=t.inert;return pl.createElement(pl.Fragment,null,m?pl.createElement(i,{styles:KQo(o)}):null,p?pl.createElement(qJ,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function GQo(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var rJr=kJ(Rje,tJr);var nJr=Ije.forwardRef(function(t,e){return Ije.createElement(gce,Ks({},t,{ref:e,sideCar:rJr}))});nJr.classNames=gce.classNames;var Omt=nJr;var vo=L(ht(),1),Tmt=["Enter"," "],ZQo=["ArrowDown","PageUp","Home"],iJr=["ArrowUp","PageDown","End"],XQo=[...ZQo,...iJr],YQo={ltr:[...Tmt,"ArrowRight"],rtl:[...Tmt,"ArrowLeft"]},QQo={ltr:["ArrowLeft"],rtl:["ArrowRight"]},wce="Menu",[_ce,eei,tei]=V2r(wce),[UJ,Emt]=lZ(wce,[tei,amt,mmt]),Sce=amt(),aJr=mmt(),[sJr,JB]=UJ(wce),[rei,Cce]=UJ(wce),uJr=t=>{let{__scopeMenu:e,open:r=!1,children:n,dir:o,onOpenChange:i,modal:a=!0}=t,s=Sce(e),[u,l]=Dr.useState(null),c=Dr.useRef(!1),d=W_(i),f=J2r(o);return Dr.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)(sJr,{scope:e,open:r,onOpenChange:d,content:u,onContentChange:l,children:(0,vo.jsx)(rei,{scope:e,onClose:Dr.useCallba
.block-interactivity-`.concat(t,` {pointer-events: none;}
.allow-interactivity-`).concat(t,` {pointer-events: all;}
`)},$ri=0,EZ=[];function o5r(t){var e=ml.useRef([]),r=ml.useRef([0,0]),n=ml.useRef(),o=ml.useState($ri++)[0],i=ml.useState(r$)[0],a=ml.useRef(t);ml.useEffect(function(){a.current=t},[t]),ml.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var h=yZ([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=ml.useCallback(function(h,g){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!a.current.allowPinchZoom;var y=Xje(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=Cht(E,O);if(!T)return!0;if(T?x=E:(x=E==="v"?"h":"v",T=Cht(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=ml.useCallback(function(h){var g=h;if(!(!EZ.length||EZ[EZ.length-1]!==i)){var y="deltaY"in g?r5r(g):Xje(g),b=e.current.filter(function(x){return x.name===g.type&&(x.target===g.target||g.target===x.shadowParent)&&jri(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=ml.useCallback(function(h,g,y,b){var _={name:h,delta:g,target:y,should:b,shadowParent:Lri(y)};e.current.push(_),setTimeout(function(){e.current=e.current.filter(function(w){return w!==_})},1)},[]),c=ml.useCallback(function(h){r.current=Xje(h),n.current=void 0},[]),d=ml.useCallback(function(h){l(h.type,r5r(h),h.target,s(h,t.lockRef.current))},[]),f=ml.useCallback(function(h){l(h.type,Xje(h),h.target,s(h,t.lockRef.current))},[]);ml.useEffect(function(){return EZ.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,HJ),document.addEventListener("touchmove",u,HJ),document.addEventListener("touchstart",c,HJ),function(){EZ=EZ.filter(function(h){return h!==i}),document.removeEventListener("wheel",u,HJ),document.removeEventListener("touchmove",u,HJ),document.removeEventListener("touchstart",c,HJ)}},[]);var p=t.removeScrollBar,m=t.inert;return ml.createElement(ml.Fragment,null,m?ml.createElement(i,{styles:Dri(o)}):null,p?ml.createElement(qJ,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function Lri(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var i5r=kJ(Zje,o5r);var a5r=Yje.forwardRef(function(t,e){return Yje.createElement(Rce,Ks({},t,{ref:e,sideCar:i5r}))});a5r.classNames=Rce.classNames;var xht=a5r;var cm=L(ht(),1),Qje="Popover",[s5r,Nbs]=Vje(Qje,[yht]),Ice=yht(),[Fri,ZB]=s5r(Qje),u5r=t=>{let{__scopePopover:e,children:r,open:n,defaultOpen:o,onOpenChange:i,modal:a=!1}=t,s=Ice(e),u=Jl.useRef(null),[l,c]=Jl.useState(!1),[d,f]=X6r({prop:n,defaultProp:o??!1,onChange:i,caller:Qje});return(0,cm.jsx)(V6r,{...s,children:(0,cm.jsx)(Fri,{scope:e,contentId:R6r(),triggerRef:u,open:d,onOpenChange:f,onOpenToggle:Jl.useCallback(()=>f(p=>!p),[f]),hasCustomAnchor:l,onCustomAnchorAdd:Jl.useCallback(()=>c(!0),[]),onCustomAnchorRemove:Jl.useCallback(()=>c(!1),[]),modal:a,children:r})})};u5r.displayName=Qje;var l5r="PopoverAnchor",kri=Jl.forwardRef((t,e)=>{let{__scopePopover:r,...n}=t,o=ZB(l5r,r),i=Ice(r),{onCustomAnchorAdd:a,onCustomAnchorRemove:s}=o;return Jl.useEffect(()=>(a(),()=>s()),[a,s]),(0,cm.jsx)(_ht,{...i,...n,ref:e})});kri.displayName=l5r;var c5r="PopoverTrigger",d5r=Jl.forwardRef((t,e)=>{let{__scopePopover:r,...n}=t,o=ZB(c5r,r),i=Ice(r),a=vw(e,o.triggerRef),s=(0,cm.jsx)(Db.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"dat
`,jni=ZJ?"\xA0":kDe,VKr="\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC",JKr="A-Za-z\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u0300-\u0590\u0800-\u1FFF\u200E\u2C00-\uFB1C\uFE00-\uFE6F\uFEFD-\uFFFF",Dni=new RegExp("^[^"+JKr+"]*["+VKr+"]"),$ni=new RegExp("^[^"+VKr+"]*["+JKr+"]"),ky={bold:1,capitalize:1024,code:16,highlight:FDe,italic:2,lowercase:256,strikethrough:Vce,subscript:32,superscript:64,underline:Jce,uppercase:512},Lni={directionless:1,unmergeable:2},Y5r={center:_gt,end:Cgt,justify:wgt,left:bgt,right:vgt,start:Sgt},Fni={[_gt]:"center",[Cgt]:"end",[wgt]:"justify",[bgt]:"left",[vgt]:"right",[Sgt]:"start"},kni={normal:0,segmented:2,token:1},qni={[Tni]:"normal",[Pni]:"segmented",[Eni]:"token"},Bni="$",Q5r="$config";function KKr(t,e,r,n,o,i){let a=t.getFirstChild();for(;a!==null;){let s=a.__key;a.__parent===e&&(Ve(a)&&KKr(a,s,r,n,o,i),r.has(s)||i.delete(s),o.push(s)),a=a.getNextSibling()}}var Uni=100,Vht=!1,xgt=0;function zni(t){xgt=t.timeStamp}function Iht(t,e,r){let n=t.nodeName==="BR",o=e.__lexicalLineBreak;return o&&(t===o||n&&t.previousSibling===o)||n&&JDe(t,r)!==void 0}function Hni(t,e,r){let n=DI(P0(r)),o=null,i=null;n!==null&&n.anchorNode===t&&(o=n.anchorOffset,i=n.focusOffset);let a=t.nodeValue;a!==null&&Hgt(e,a,o,i,!1)}function Vni(t,e,r){if(en(t)){let n=t.anchor.getNode();if(n.is(r)&&t.format!==n.getFormat())return!1}return $I(e)&&r.isAttached()}function Jni(t,e,r,n){for(let o=t;o&&!g8r(o);o=nde(o)){let i=JDe(o,e);if(i!==void 0){let a=Km(i,r);if(a)return Au(a)||!kb(o)?void 0:[o,a]}else if(o===n)return[n,e8r(r)]}}function WKr(t,e,r){Vht=!0;let n=performance.now()-xgt>Uni;try{ww(t,()=>{let o=Is()||function(f){return f.getEditorState().read(()=>{let p=Is();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=Jni(h,t,s,a);if(!g)continue;let[y,b]=g;if(m==="characterData")n&&wr(b)&&$I(h)&&Vni(o,h,b)&&Hni(h,b,t);else if(m==="childList"){l=!0;let _=p.addedNodes;for(let O=0;O<_.length;O++){let E=_[O],T=YWr(E),R=E.parentNode;if(R!=null&&E!==u&&T===null&&!Iht(E,R,t)){if(ZJ){let I=(kb(E)?E.innerText:null)||E.nodeValue;I&&(c+=I)}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];(Iht(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"||Iht(y,h,t)||b.removeChild(y)}}r.takeRecords()}o!==null&&(l&&cv(o),ZJ&&a8r(t)&&o.insertRawText(c))})}finally{Vht=!1}}function GKr(t){let e=t._observer;e!==null&&WKr(t,e.takeRecords(),e)}function ZKr(t){(function(e){xgt===0&&P0(e).addEventListener("textInput",zni,!0)})(t),t._observer=new MutationObserver((e,r)=>{WKr(t,e,r)})}var Jht=class{constructor(e,r){this.key=e,this.parse=r.parse.bind(r),this.unparse=(r.unparse||Zni).bind(r),this.isEqual=(r.isEqual||Object.is).bind(r),this.defaultValue=this.parse(void 0)}};function Kni(t,e){return new Jht(t,e)}function SDe(t,e,r="latest"){let n=(r==="latest"?t.getLatest():t).__state;return n?n.getValue(e):e.defaultValue}function Wni(t,e,r){let n=SDe(t,r,"direct"),o=SDe(e,r,"direct");return r.isEqual(n,o)?null:[n,o]}function Gni(t,e,r){let n;if(kh(),typeof r=="function"){let i=t.getLatest(),a=SDe(i,e);if(n=r(a),e.isEqual(a,n))return i}else n=r;let o=t.getWritable();return Ogt(o).updateFromKnown(e,n),o}function XKr(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}=Zgt(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 Kht=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(),ur(n,Fce,!1);else if(u===g$)r.preventDefault(),ur(n,egt,void 0);else if(u==null&&r.dataTransfer){let p=r.dataTransfer.getData("text/plain");r.preventDefault(),a.insertRawText(p)}else u!=null&&PWr(a,i,u,r.timeStamp,!0)?(r.preventDefault(),ur(n,FZ,u)):$Z=u;TWr=r.timeStamp}})}(t,e)]);var kce=0,OWr=null,TWr=0,$Z=null,PDe=new WeakMap,igt=!1,agt=!1,qce=!1,Dce=!1,jht=!1,Dht="",WJ=null,EWr=[0,"",0,"root",0];function PWr(t,e,r,n,o){let i=t.anchor,a=t.focus,s=i.getNode(),u=Kl(),l=DI(P0(u)),c=l!==null?l.anchorNode:null,d=i.key,f=u.getElementByKey(d),p=r.length;return d!==a.key||!wr(s)||(!o&&(!_De||TWr<n+50)||s.isDirty()&&p<2||t8r(r))&&i.offset!==a.offset&&!s.isComposing()||c$(s)||s.isDirty()&&p>1||(o||!_De)&&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=tU(h);return g===0?!h.canInsertTextBefore()||!y.canInsertTextBefore()&&!h.isComposing()||b||function(_){let w=_.getPreviousSibling();return(wr(w)||Ve(w)&&w.isInline())&&!w.canInsertTextAfter()}(h):g===h.getTextContentSize()&&(!h.canInsertTextAfter()||!y.canInsertTextAfter()&&!h.isComposing()||b)}(t,s)}function lKr(t,e){return $I(t)&&t.nodeValue!==null&&e!==0&&e!==t.nodeValue.length}function cKr(t,e,r){let{anchorNode:n,anchorOffset:o,focusNode:i,focusOffset:a}=t;igt&&(igt=!1,lKr(n,o)&&lKr(i,a)&&!WJ)||ww(e,()=>{if(!r)return void cv(null);if(!tde(e,n,i))return;let s=Is();if(WJ&&en(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,en(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]=EWr,y=lv(),b=e.isComposing()===!1&&y.getTextContent()==="";if(d<g+200&&u.offset===m&&u.key===h)gDe(s,f,p);else if(u.type==="text")wr(l)||Ke(141),MWr(s,l);else if(u.type==="element"&&!b){Ve(l)||Ke(259);let _=u.getNode();_.isEmpty()?function(w,x){let O=x.getTextFormat(),E=x.getTextStyle();gDe(w,O,E)}(s,_):gDe(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,_=HKr,w=!1;for(let x=0;x<p;x++){let O=f[x],E=O.getTextContentSize();if(wr(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}}ur(e,Tgt,void 0)})}function gDe(t,e,r){t.format===e&&t.style===r||(t.format=e,t.style=r,t.dirty=!0)}function MWr(t,e){gDe(t,e.getFormat(),e.getStyle())}function RWr(t){if(!t.getTargetRanges)return null;let e=t.getTargetRanges();return e.length===0?null:e[0]}function cDe(t,e){let r=t._compositionKey;if(qh(null),r!==null&&e!=null){if(e===""){let n=Km(r),o=t3(t.getElementByKey(r));return void(o!==null&&o.nodeValue!==null&&wr(n)&&Hgt(n,o.nodeValue,null,null,!0))}if(e[e.length-1]===`
`){let n=Is();if(en(n)){let o=n.focus;return n.anchor.set(o.key,o.offset,o.type),void ur(t,EDe,null)}}}zgt(!0,t,e)}function AWr(t){let e=t.__lexicalEventHandles;return e===void 0&&(e=[],t.__lexicalEventHandles=e),e}var kZ=new Map;function IWr(t){let e=d8r(t.target);if(e===null)return;let r=Bgt(e.anchorNode);if(r===null)return;agt&&(agt=!1,ww(r,()=>{let u=n3(),l=e.anchorNode;(kb(l)||$I(l))&&cv(zDe(u,e,r,t))}));let n=Ugt(r),o=n[n.length-1],i=o._key,a=kZ.get(i),s=a||o;s!==r&&cKr(e,s,!1),cKr(e,r,!0),r!==o?kZ.set(i,r):a&&kZ.delete(i)}function dKr(t){t._lexicalHandled=!0}function fKr(t){return t._lexicalHandled===!0}var loi=()=>{};function coi(t){let e=t.ownerDocument,r=PDe.get(e);if(r===void 0)return void loi();let n=r-1;n>=0||Ke(164),PDe.set(e,n),n===0&&e.removeEventListener("selectionchange",IWr);let o=rde(t);VDe(o)?(function(a){if(a._parentEditor!==null){let s=Ugt(a),u=s[s.length-1]._key;kZ.get(u)===a&&kZ.delete(u)}else kZ.delete(a._key)}(o),t.__lexicalEditor=null):o&&Ke(198);let i=AWr(t);for(let a=0;a<i.length;a++)i[a]();t.__lexicalEventHandles=[]}function sgt(t,e,r){kh();let n=t.__key,o=t.getParent();if(o===null)return;let i=function(s){let u=Is();if(!en(u)||!Ve(s))return u;let{anchor:l,focus:c}=u,d=l.getNode(),f=c.getNode();return $De(d,s)&&l.set(s.__key,0,"element"),$De(f,s)&&c.set(s.__key,0,"element"),u}(t),a=!1;if(en(i)&&e){let s=i.anchor,u=i.focus;s.key===n&&(ADe(s,t,o,t.getPreviousSibling(),t.getNextSibling()),a=!0),u.key===n&&(ADe(u,t,o,t.getPreviousSibling(),t.getNextSibling()),a=!0)}else UDe(i)&&e&&t.isSelected()&&t.selectPrevious();if(en(i)&&e&&!a){let s=t.getIndexWithinParent();rU(t),RDe(i,o,s,-1)}else rU(t);r||kx(o)||o.canBeEmpty()||!o.isEmpty()||sgt(o,e),e&&i&&sv(o)&&o.isEmpty()&&o.selectEnd()}function doi(t){return t}var oU=class{static getType(){let{ownNodeType:e}=Zgt(this);return e===void 0&&Ke(64,this.name),e}static clone(e){Ke(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}),XWr(this,e)}getType(){return this.__type}isInline(){Ke(137,this.constructor.name)}isAttached(){let e=this.__key;for(;e!==null;){if(e==="root")return!0;let r=Km(e);if(r===null)break;e=r.__parent}return!1}isSelected(e){let r=e||Is();if(r==null)return!1;let n=r.getNodes().some(o=>o.__key===this.__key);if(wr(this))return n;if(en(r)&&r.anchor.type==="element"&&r.focus.type==="element"){if(r.isCollapsed())return!1;let o=this.getParent();if(Au(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:Km(e)}getParentOrThrow(){let e=this.getParent();return e===null&&Ke(66,this.__key),e}getTopLevelElement(){let e=this;for(;e!==null;){let r=e.getParent();if(kx(r))return Ve(e)||e===this&&Au(e)||Ke(194),e;e=r}return null}getTopLevelElementOrThrow(){let e=this.getTopLevelElement();return e===null&&Ke(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:Km(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&&pgt(n)){let o=n.firstChild;if(o===r||o.nextSibling===r&&dDe(o)){let i=n.lastChild;if(i===r||i.previousSibling===r&&dDe(i))return!0}}return!1}(e)||function(r){let n=r.parentElement;if(n!==null&&pgt(n)){let o=n.firstChild;if(o===r||o.nextSibling===r&&dDe(o))return!1;let i=n.lastChild;if(i===r||i.previousSibling===r&&dDe(i))return!0}return!1}(e)?null:{conversion:foi,priority:0}}}static importJSON(e){return HZ().updateFromJSON(e)}};function foi(t){return{node:HZ()}}function HZ(){return ode(new zZ)}function GJ(t){return t instanceof zZ}function dDe(t){return $I(t)&&/^( |\t|\r?\n)+$/.test(t.textContent||"")}function $ht(t,e){return 16&e?"code":e&FDe?"mark":32&e?"sub":64&e?"sup":null}function Lht(t,e){return 1&e?"strong":2&e?"em":"span"}function NWr(t,e,r,n,o){let i=n.classList,a=qZ(o,"base");a!==void 0&&i.add(...a),a=qZ(o,"underlineStrikethrough");let s=!1,u=e&Jce&&e&Vce;a!==void 0&&(r&Jce&&r&Vce?(s=!0,u||i.add(...a)):u&&i.remove(...a));for(let l in ky){let c=ky[l];if(a=qZ(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 jWr(t,e,r){let n=e.firstChild,o=r.isComposing(),i=t+(o?kDe:"");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 pKr(t,e,r,n,o,i){jWr(o,t,e);let a=i.theme.text;a!==void 0&&NWr(0,0,n,t,a)}function fDe(t,e){let r=document.createElement(e);return r.appendChild(t),r}var QJ=class t extends oU{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 qni[e.__mode]}getStyle(){return this.getLatest().__style}isToken(){return this.getLatest().__mode===1}isComposing(){return this.__key===eU()}isSegmented(){return this.getLatest().__mode===2}isDirectionless(){return!!(1&this.getLatest().__detail)}isUnmergeable(){return!!(2&this.getLatest().__detail)}hasFormat(e){let r=ky[e];return!!(this.getFormat()&r)}isSimpleText(){return this.__type==="text"&&this.__mode===0}getTextContent(){return this.getLatest().__text}getFormatFlags(e,r){return jDe(this.getLatest().__format,e,r)}canHaveFormat(){return!0}isInline(){return!0}createDOM(e,r){let n=this.__format,o=$ht(0,n),i=Lht(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)),pKr(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=$ht(0,i),u=$ht(0,a),l=Lht(0,i),c=Lht(0,a);if((s===null?l:s)!==(u===null?c:u))return!0;if(s===u&&l!==c){let h=r.firstChild;h==null&&Ke(48);let g=document.createElement(c);return pKr(g,this,0,a,o,n),r.replaceChild(g,h),!1}let d=r;u!==null&&s!==null&&(d=r.firstChild,d==null&&Ke(49)),jWr(o,d,this);let f=n.theme.text;f!==void 0&&i!==a&&NWr(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:goi,priority:0}),b:()=>({conversion:moi,priority:0}),code:()=>({conversion:u$,priority:0}),em:()=>({conversion:u$,priority:0}),i:()=>({conversion:u$,priority:0}),mark:()=>({conversion:u$,priority:0}),s:()=>({conversion:u$,priority:0}),span:()=>({conversion:poi,priority:0}),strong:()=>({conversion:u$,priority:0}),sub
`||s===`\r
`?o.push(HZ()):s===" "?o.push(BDe()):s!==""&&o.push(Fh(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=hKr(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=hKr(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:Fh(r)}}function hKr(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===""&&!p8r(r)||i!==""&&!i.startsWith("inline"))return null}let o=r;for(;(o=e?r.firstChild:r.lastChild)!==null;)r=o;if($I(r))return r;if(r.nodeName==="BR")return null}}var yoi={code:"code",em:"italic",i:"italic",mark:"highlight",s:"strikethrough",strong:"bold",sub:"subscript",sup:"superscript",u:"underline"};function u$(t){let e=yoi[t.nodeName.toLowerCase()];return e===void 0?{node:null}:{forChild:Igt(t.style,e),node:null}}function Fh(t=""){return ode(new QJ(t))}function wr(t){return t instanceof QJ}function Igt(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=>(wr(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 VZ=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=qZ(e.theme,"tab");return n!==void 0&&r.classList.add(...n),r}static importJSON(e){return BDe().updateFromJSON(e)}setTextContent(e){return e!==" "&&e!==""&&Ke(126),super.setTextContent(" ")}spliceText(e,r,n,o){return n===""&&r===0||n===" "&&r===1||Ke(286),this}setDetail(e){return e!==2&&Ke(127),this}setMode(e){return e!=="normal"&&Ke(128),this}canInsertTextBefore(){return!1}canInsertTextAfter(){return!1}};function BDe(){return ode(new VZ)}function Ngt(t){return t instanceof VZ}var ugt=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:eyt(jx(uU(this,"next")),jx(uU(e,"next")))<0}getNode(){let e=Km(this.key);return e===null&&Ke(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,tX()||(eU()===a&&qh(e),i!==null&&(i.setCachedNodes(null),i.dirty=!0)))}};function Fx(t,e,r){return new ugt(t,e,r)}function Fht(t,e){let r=e.__key,n=t.offset,o="element";if(wr(e)){o="text";let i=e.getTextContentSize();n>i&&(n=i)}else if(!Ve(e)){let i=e.getNextSibling();if(wr(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 gKr(t,e){if(Ve(e)){let r=e.getLastDescendant();Ve(r)||wr(r)?Fht(t,r):Fht(t,e)}else Fht(t,e)}var MDe=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(!UDe(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,wr(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!Au(f)&&!GJ(f)||f===n&&this.isCollapsed()||(l+=f.getTextContent())}return l}applyDOMRange(e){let r=Kl(),n=r.getEditorState()._selection,o=$Wr(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),CDe(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=jDe(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=ky[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(HZ()):a===" "?n.push(BDe()):n.push(Fh(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=Fh(),E=sv(w)?m$().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"&&eX(s,jx(uU(s,"next")));let u=a.offset,l=s.offset,c=this.getNodes(),d=c.length,f=c[0];wr(f)||Ke(26);let p=f.getTextContent().length,m=f.getParentOrThrow(),h=c[d-1];if(d===1&&s.type==="element"&&(l=p,s.set(a.key,l,"text")),this.isCollapsed()&&u===p&&(c$(f)||!f.canInsertTextAfter()||!m.canInsertTextAfter()&&f.getNextSibling()===null)){let g=f.getNextSibling();if(wr(g)&&g.canInsertTextBefore()&&!c$(g)||(g=Fh(),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&&(c$(f)||!f.canInsertTextBefore()||!m.canInsertTextBefore()&&f.getPreviousSibling()===null)){let g=f.getPreviousSibling();if(wr(g)&&!c$(g)||(g=Fh(),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=Fh(f.getTextContent());g.setFormat(o),f.replace(g),f=g}else if(!this.isCollapsed()&&e!==""){let g=h.getParent();if(!m.canInsertTextBefore()||!m.canInsertTextAfter()||Ve(g)&&(!g.canInsertTextBefore()||!g.canInsertTextAfter()))return this.insertText(""),DWr(this.anchor,this.focus,null),void this.insertText(e)}if(d===1){if(tU(f)){let _=Fh(e);return _.select(),void f.replace(_)}let g=f.getFormat(),y=f.getStyle();if(u!==l||g===o&&y===i){if(Ngt(f)){let _=Fh(e);return _.setFormat(o),_.setStyle(i),_.select(),void f.replace(_)}}else{if(f.getTextContent()!==""){let _=Fh(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=Ve(f)?f:f.getParentOrThrow(),b=Ve(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(wr(h)&&!tU(h)&&l!==h.getTextContentSize()){if(h.isSegmented()){let T=Fh(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)||Ve(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 I=T.getChildren(),j=I.length;(j===0||I[j-1].is(R))&&(g.delete(T.__key),R=T),T=T.getParent()}}if(tU(f))if(u===p)f.select();else{let T=Fh(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],I=R.__key;g.has(I)||R.remove()}}}removeText(){let e=Is()===this;zce(this,v8r(ygt(this))),e&&Is()!==this&&cv(this)}formatText(e,r=null){if(this.isCollapsed())return this.toggleFormat(e),void qh(null);let n=this.getNodes(),o=[];for(let w of n)wr(w)&&o.push(w);let i=w=>{n.forEach(x=>{if(Ve(x)){let O=x.getFormatFlags(e,w);x.setTextFormat(O)}})},a=o.length;if(a===0)return this.toggleFormat(e),qh(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||iX(l)||l.remove(),o-=u+a,n=i}else{let l=n.getKey(),c=t.getEditorState().read(()=>{let p=M8r(l);return Ui(p)&&p.isSimpleText()?p.getTextContent():null}),d=u-o,f=s.slice(0,d);if(c!==null&&c!==s){let p=ade(),m=n;if(n.isSimpleText())n.setTextContent(c);else{let h=Sw(c);n.replace(h),m=h}if(Tr(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=Sw(f);n.replace(p)}o=0}}}function Yii(t){let e=t.getStyle(),r=f9r(e);x$e.set(e,r)}function Eyt(t,e){(Tr(t)?t.isCollapsed():Ui(t)||oi(t))||Ryt(280);let r=O$e(Tr(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=p9r(n);Tr(t)||Ui(t)?t.setStyle(o):t.setTextStyle(o),x$e.set(o,n)}function Qii(t,e){if(Tr(t)&&t.isCollapsed()){Eyt(t,e);let r=t.anchor.getNode();oi(r)&&r.isEmpty()&&Eyt(r,e)}h9r(r=>{Eyt(r,e)})}function h9r(t){let e=an();if(!e)return;let r=new Map;if(Tr(e))for(let i of C8r(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&&(syt(i)||a===0&&s===i.getTextContentSize()?t(i):t(i.splitText(a,s)[a===0?0:1]))}var o;Tr(e)&&e.anchor.type==="text"&&e.focus.type==="text"&&e.anchor.key===e.focus.key&&g9r(e)}function g9r(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 y9r(t,e){let r=t.getFormatType(),n=t.getIndent();r!==e.getFormatType()&&e.setFormat(r),n!==e.getIndent()&&e.setIndent(n)}function eai(t,e,r=y9r){if(t===null)return;let n=t.getStartEndPoints(),o=new Map,i=null;if(n){let[a,s]=n;i=GDe(),i.anchor.set(a.key,a.offset,a.type),i.focus.set(s.key,s.offset,s.type);let u=Myt(a.getNode(),cde),l=Myt(s.getNode(),cde);oi(u)&&o.set(u.getKey(),u),oi(l)&&o.set(l.getKey(),l)}for(let a of t.getNodes())if(oi(a)&&cde(a))o.set(a.getKey(),a);else if(n===null){let s=Myt(a,cde);oi(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(an())&&i3(i)}function d9r(t){return t.getNode().isAttached()}function tai(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 rai(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)?(Pyt(t,u,u.length,e,r),u=[],s=c):s===null||s!==null&&A8r(c,s)?u.push(c):(Pyt(t,u,u.length,e,r),u=[c])}Pyt(t,u,u.length,e,r)}function Pyt(t,e,r,n,o=null){if(e.length===0)return;let i=e[0],a=new Map,s=[],u=oi(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];oi(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&&N8r(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()),oi(_)&&_.getChildrenKeys().forEach(w=>d.add(w))}),tai(g)}}else if(c.has(h.getKey())){oi(h)||Ryt(179);let y=n();y.setFormat(h.getFormatType()),y
`||c===`\r
`?l.insertParagraph():c===" "?l.insertNodes([x8r()]):l.insertText(c)}}}else e.insertRawText(a)}function Uyt(t,e,r){t.dispatchCommand(fGr,{nodes:e,selection:r})||(r.insertNodes(e),function(n){if(Tr(n)&&n.isCollapsed()){let o=n.anchor,i=null,a=oX(o,"previous");if(a)if(QDe(a))i=a.origin;else{let s=T8r(a,fU(es(),"next").getFlipped());for(let u of s){if(Ui(u.origin)){i=u.origin;break}if(oi(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 Z9r(t,e,r,n=[]){let o=e===null||r.isSelected(e),i=oi(r)&&r.excludeFromCopy("html"),a=r;if(e!==null){let l=dU(r);l=Ui(l)&&e!==null?T$e(e,l):l,a=l}let s=oi(a)?a.getChildren():[],u=function(l){let c=l.exportJSON(),d=l.constructor;if(c.type!==d.getType()&&P$e(58,d.name),oi(l)){let f=c.children;Array.isArray(f)||P$e(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=Z9r(t,e,c,u.children);!o&&oi(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 X9r(t,e){let r=[],n=es().getChildren();for(let o=0;o<n.length;o++)Z9r(t,e,n[o],r);return{namespace:t._config.namespace,nodes:r}}function Y9r(t){let e=[];for(let r=0;r<t.length;r++){let n=t[r],o=L8r(n);Ui(o)&&v9r(o),e.push(o)}return e}var hX=null;async function nsi(t,e,r){if(hX!==null)return!1;if(e!==null)return new Promise((l,c)=>{t.update(()=>{l(K9r(t,e,r))})});let n=t.getRootElement(),o=t._window||window,i=window.document,a=cyt(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(r$e,f=>(Sde(f,ClipboardEvent)&&(d(),hX!==null&&(window.clearTimeout(hX),hX=null),l(K9r(t,f,r))),!0),t$e);hX=window.setTimeout(()=>{d(),hX=null,l(!1)},50),i.execCommand("copy"),s.remove()})}function K9r(t,e,r){if(r===void 0){let o=cyt(t._window);if(!o)return!1;let i=o.anchorNode,a=o.focusNode;if(i!==null&&a!==null&&!wGr(t,i,a))return!1;let s=an();if(s===null)return!1;r=Q9r(s)}e.preventDefault();let n=e.clipboardData;return n!==null&&(e7r(n,r),!0)}var osi=[["text/html",W9r],["application/x-lexical-editor",G9r]];function Q9r(t=an()){let e={"text/plain":t?t.getTextContent():""};if(t){let r=ZDe();for(let[n,o]of osi){let i=o(r,t);i!==null&&(e[n]=i)}}return e}function e7r(t,e){for(let r in e){let n=e[r];n!==void 0&&t.setData(r,n)}}var qI=zyt,vOs=qI.$generateJSONFromSelectedNodes,wOs=qI.$generateNodesFromSerializedNodes,SOs=qI.$getClipboardDataFromSelection,t7r=qI.$getHtmlContent,COs=qI.$getLexicalContent,Hyt=qI.$insertDataTransferForPlainText,xOs=qI.$insertDataTransferForRichText,OOs=qI.$insertGeneratedNodes,TOs=qI.copyToClipboard,EOs=qI.setLexicalClipboardDataTransfer;var Vyt={};Jn(Vyt,{registerPlainText:()=>csi});var gX=typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0,isi=gX&&"documentMode"in document?document.documentMode:null,asi=!(!gX||!("InputEvent"in window)||isi)&&"getTargetRanges"in new window.InputEvent("input"),ssi=gX&&/Version\/[\d.]+.*Safari/.test(navigator.userAgent),r7r=gX&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,usi=gX&&/^(?=.*Chrome).*/i.test(navigator.userAgent),lsi=gX&&/AppleWebKit\/[\d.]+/.test(navigator.userAgent)&&!usi;function n7r(t,e){e.update(()=>{if(t!==null){let r=Sde(t,KeyboardEvent)?null:t.clipboardData,n=an();if(n!==null&&r!=null){t.preventDefault();let o=t7r(e);o!==null&&r.setData("text/html",o),r.setData("text/plain",n.getTextContent())}}})}function csi(t){return S$(t.registerCommand(aX,e=>{let r=an();return!!Tr(r)&&(r.deleteCharacter(e),!0)},Vu),t.registerCommand(Z8r,e=>{let r=an();return!!Tr(r)&&(r.deleteWord(e),!0)},Vu),t.registerCommand(G8r,e=>{let r=an();return!!Tr(r)&&(r.deleteLine(e),!0)},Vu),t.registerCommand(K8r,e=>{let r=an();if(!Tr(r))return!1;if(ty
.block-interactivity-`.concat(t,` {pointer-events: none;}
.allow-interactivity-`).concat(t,` {pointer-events: all;}
`)},gli=0,xX=[];function NXr(t){var e=hl.useRef([]),r=hl.useRef([0,0]),n=hl.useRef(),o=hl.useState(gli++)[0],i=hl.useState(r$)[0],a=hl.useRef(t);hl.useEffect(function(){a.current=t},[t]),hl.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var h=yZ([t.lockRef.current],(t.shards||[]).map(IXr),!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=hl.useCallback(function(h,g){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!a.current.allowPinchZoom;var y=rLe(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=Nbt(E,O);if(!T)return!0;if(T?x=E:(x=E==="v"?"h":"v",T=Nbt(E,O)),!T)return!1;if(!n.current&&"changedTouches"in h&&(_||w)&&(n.current=x),!x)return!0;var R=n.current||x;return RXr(R,g,h,R==="h"?_:w,!0)},[]),u=hl.useCallback(function(h){var g=h;if(!(!xX.length||xX[xX.length-1]!==i)){var y="deltaY"in g?AXr(g):rLe(g),b=e.current.filter(function(x){return x.name===g.type&&(x.target===g.target||g.target===x.shadowParent)&&mli(x.delta,y)})[0];if(b&&b.should){g.cancelable&&g.preventDefault();return}if(!b){var _=(a.current.shards||[]).map(IXr).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=hl.useCallback(function(h,g,y,b){var _={name:h,delta:g,target:y,should:b,shadowParent:yli(y)};e.current.push(_),setTimeout(function(){e.current=e.current.filter(function(w){return w!==_})},1)},[]),c=hl.useCallback(function(h){r.current=rLe(h),n.current=void 0},[]),d=hl.useCallback(function(h){l(h.type,AXr(h),h.target,s(h,t.lockRef.current))},[]),f=hl.useCallback(function(h){l(h.type,rLe(h),h.target,s(h,t.lockRef.current))},[]);hl.useEffect(function(){return xX.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(){xX=xX.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 hl.createElement(hl.Fragment,null,m?hl.createElement(i,{styles:hli(o)}):null,p?hl.createElement(qJ,{gapMode:t.gapMode}):null)}function yli(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var jXr=kJ(tLe,NXr);var DXr=nLe.forwardRef(function(t,e){return nLe.createElement(Ode,Ks({},t,{ref:e,sideCar:jXr}))});DXr.classNames=Ode.classNames;var Ede=DXr;var ln=L(ht(),1),bli=[" ","Enter","ArrowUp","ArrowDown"],_li=[" ","Enter"],Mde="Select",[iLe,aLe,vli]=HZr(Mde),[OX,WAs]=xB(Mde,[vli,Obt]),sLe=Obt(),[wli,xU]=OX(Mde),[Sli,Cli]=OX(Mde),$Xr=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=sLe(e),[g,y]=zt.useState(null),[b,_]=zt.useState(null),[w,x]=zt.useState(!1),O=VZr(l),[E=!1,T]=VD({prop:n,defaultProp:o,onChange:i}),[R,I]=VD({prop:a,defaultProp:s,onChange:u}),j=zt.useRef(null),F=g?m||!!g.closest("form"):!0,[B,U]=zt.useState(new Set),J=Array.from(B).map(G=>G.props.value).join(";");return(0,ln.jsx)(_Xr,{...h,children:(0,ln.jsxs)(wli,{required:p,scope:e,trigger:g,onTriggerChange:y,valueNode:b,onValueNodeChange:_,valueNodeHasChildren:w,onValueNodeHasChildrenChange:x,contentId:HI(),value:R,onValueChange:I,open:E,onOpenChange:T,dir:O,triggerPointerDownPosRef:j,disabled:f,children:[(0,ln.jsx)(iLe.Provider,{scope:e,children:(0,ln.jsx)(Sli,{scope:t.__scopeSelect,onNativeOptionAdd:zt.useCallback(G=>{U(oe=>new Set(oe).add(G))},[]),onN
\u2026 (truncated ${(r.length-Rde).toLocaleString()} characters for display)`:r}catch{return e.length>Rde?`Tool '${t}' returned ${e.length.toLocaleString()} characters. The full output is preserved in chat history but omitted here to keep the UI responsive.`:e}},IYr=({toolName:t,displayName:e,emoji:r,isExecuting:n,result:o,confirmationMessage:i,onAccept:a,onReject:s})=>{let[u,l]=(0,Ju.useState)(!1),c=(0,Ju.useMemo)(()=>Yli(t,o),[t,o]),d=n&&!o,f=!d&&c!==null;return Ju.default.createElement(Zx,{open:f?u:!1,onOpenChange:l,disabled:!f,"aria-disabled":!f,className:"tw-my-3 tw-w-full sm:tw-max-w-sm"},Ju.default.createElement("div",{className:Oe("tw-rounded-md tw-border tw-border-border tw-bg-secondary/50",d&&"tw-relative tw-overflow-hidden")},d&&Ju.default.createElement("div",{className:"tw-absolute tw-inset-0 tw-z-[1] tw-overflow-hidden"},Ju.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:Xli}})),Ju.default.createElement(P$,{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",f&&"hover:tw-bg-secondary/70",!f&&"tw-cursor-default")},Ju.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Ju.default.createElement("span",{className:"tw-text-base"},r),Ju.default.createElement("span",{className:"tw-font-medium"},t==="readNote"?`${d?"Reading":"Read"} ${e}`:`${d?"Calling":"Called"} ${e}`,d&&t!=="readNote"&&"..."),d&&i&&Ju.default.createElement("span",{className:"tw-text-xs tw-text-muted"},"\u2022 ",i,"...")),Ju.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},!d&&a&&s&&Ju.default.createElement(Ju.default.Fragment,null,Ju.default.createElement("button",{onClick:p=>{p.stopPropagation(),a()},className:"hover:tw-bg-green-rgb/20 tw-rounded tw-p-1",title:"Accept"},Ju.default.createElement(Lu,{className:"tw-size-4 tw-text-success"})),Ju.default.createElement("button",{onClick:p=>{p.stopPropagation(),s()},className:"hover:tw-bg-red-rgb/20 tw-rounded tw-p-1",title:"Reject"},Ju.default.createElement(ci,{className:"tw-size-4 tw-text-error"}))),f&&Ju.default.createElement(og,{className:Oe("tw-size-4 tw-text-muted tw-transition-transform",u&&"tw-rotate-90")}))),Ju.default.createElement(Xx,null,Ju.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"},Ju.default.createElement("div",{className:"tw-text-sm tw-text-muted"},Ju.default.createElement("pre",{className:"tw-overflow-x-auto tw-whitespace-pre-wrap tw-font-mono tw-text-xs"},c??"No result available"))))))};Bt();var NYr=60*60*1e3,Ade=()=>(window.__copilotToolCallRoots||(window.__copilotToolCallRoots=new Map),window.__copilotToolCallRoots),Ide=()=>(window.__copilotErrorBlocks||(window.__copilotErrorBlocks=new Map),window.__copilotErrorBlocks),jYr=(t,e,r)=>{if(e.size>0)return;r.get(t)===e&&r.delete(t)},i_t=(t,e,r,n,o,i)=>{try{n.root.unmount()}catch(a){it(`Error unmounting tool call root during ${o}`,r,a)}n.isUnmounting=!1,e.get(r)===n&&e.delete(r),jYr(t,e,i)},RX=(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,jYr(t,e,i);return}i_t(t,a,r,s,o,i)},0))},DYr=(t,e,r,n,o)=>{let i=e.get(r);return i?.isUnmounting&&(i_t(t,e,r,i,`${o} (finalizing stale root)`,Ade()),i=void 0),i||(i={root:(0,o_t.createRoot)(n),isUnmounting:!1},e.set(r,i)),i},$Yr=(t,e,r,n,o)=>{let i=e.get(r);return i?.isUnmounting&&(i_t(t,e,r,i,`${o} (finalizing stale error root)`,Ide()),i=void 0),i||(i={root:(0,o_t.createRoot)(n),isUnmounting:!1},e.set(r,i)),i},LYr=(t,e)=>{t.root.render(n_t.default.createElement(IYr,{toolName:e.toolName,displayName:e.displayName,emoji:e.emoji,isExecuting:e.isExecuting,result:e.result||null,confirmationMessage:e.confirmationMessage}))},FYr=(t,e)=>{t.root.render(n_t.default.createElement(SYr,{errorContent:e.errorContent}))},kYr=(t,e,r,n)=>{let o=e.get(r);o&&RX(t,e,r,o,n,Ade())},qYr=(t,e,r,n)=>{let o=e.get(r);o&&RX
<summary style="${Pe}">${se}</summary>
<div class="tw-text-muted" style="${pt}">${Ie.trim()}</div>
</details>
`);let Vt=new RegExp(`<${K}>([\\s\\S]*)$`);return V=V.replace(Vt,(gt,Ie)=>`<div style="${xe}">
<div style="${Pe}">${be}</div>
<div class="tw-text-muted" style="${pt}">${Ie.trim()}</div>
</div>`),V}let Ze=new RegExp(`<${K}>([\\s\\S]*?)<\\/${K}>`,"g");return V.replace(Ze,(Yr,Vt)=>`<details style="${xe}">
<summary style="${Pe}">${se}</summary>
<div class="tw-text-muted" style="${pt}">${Vt.trim()}</div>
</details>
`)},oe=V=>G(V,"think","Thought for a while","Thinking..."),ne=V=>{let K=xe=>{let Pe=/```(?:xml)?\s*([\s\S]*?<writeToFile>[\s\S]*?<\/writeToFile>[\s\S]*?)\s*```/g;return xe.replace(Pe,(pt,Ht)=>Ht.trim())},se=xe=>{if(!r)return xe;let Pe=/```xml\s*([\s\S]*?<writeToFile>[\s\S]*?)$/g;return xe.replace(Pe,(pt,Ht)=>Ht.trim())},be=K(V);return be=se(be),G(be,"writeToFile","Generated new content","Generating changes...")},z=(V,K,se)=>V.split(/(```[\s\S]*?```|`[^`]*`)/g).map((xe,Pe)=>Pe%2===0?xe.replace(K,(pt,Ht)=>{let Ze=e.metadataCache.getFirstLinkpathDest(Ht,B);return Ze?se(Ze):pt}):xe).join(""),ee=U(j),Z=J(ee).replace(/\\\[\s*/g,"$$").replace(/\s*\\\]/g,"$$").replace(/\\\(\s*/g,"$").replace(/\s*\\\)/g,"$"),$=z(Z,/!\[\[(.*?)]]/g,V=>`![](${e.vault.getResourcePath(V)})`),q=b?oe($):$,Y=ne(q),D=Jkr(Y,g.enableInlineCitations);return z(D,/(?<!!)\[\[([^\]]+)]]/g,V=>`<a href="obsidian://open?file=${encodeURIComponent(V.path)}">${V.basename}</a>`)},[e,r,b,g.enableInlineCitations]);(0,Cr.useEffect)(()=>{if(f.current=!1,c.current&&t.sender!==Zs){d.current||(d.current=new x3.Component);let j=t.message,F=w(j),B=Ynt(F,p.current);if(!f.current){let U=new Set,J=new Set;c.current.querySelectorAll('[id^="tool-call-"]').forEach(Z=>{let $=Z.id.replace("tool-call-","");U.add($)}),c.current.querySelectorAll('[id^="error-block-"]').forEach(Z=>{let $=Z.id.replace("error-block-","");J.add($)}),c.current.querySelectorAll(".message-segment").forEach(Z=>Z.remove());let z=0;B.segments.forEach(Z=>{if(Z.type==="text"&&Z.content.trim()){let $=c.current.children[z],q=document.createElement("div");q.className="message-segment",$?c.current.insertBefore(q,$):c.current.appendChild(q),x3.MarkdownRenderer.renderMarkdown(Z.content,q,"",d.current),eci(q),z++}else if(Z.type==="toolCall"&&Z.toolCall){let $=Z.toolCall.id,q=document.getElementById(`tool-call-${$}`);if(!q){let D=c.current.children[z],A=document.createElement("div");A.className="tool-call-container",A.id=`tool-call-${$}`,D?c.current.insertBefore(A,D):c.current.appendChild(A),q=A}let Y=DYr(p.current,m.current,$,q,"render refresh");!f.current&&!Y.isUnmounting&&LYr(Y,Z.toolCall),z++}else if(Z.type==="error"&&Z.error){let $=Z.error.id,q=document.getElementById(`error-block-${$}`);if(!q){let D=c.current.children[z],A=document.createElement("div");A.className="error-block-container",A.id=`error-block-${$}`,D?c.current.insertBefore(A,D):c.current.appendChild(A),q=A}let Y=$Yr(p.current,h.current,$,q,"error render");!f.current&&!Y.isUnmounting&&FYr(Y,Z.error),z++}});let ee=new Set(B.segments.filter(Z=>Z.type==="toolCall"&&Z.toolCall).map(Z=>Z.toolCall.id));U.forEach(Z=>{if(!ee.has(Z)){let $=document.getElementById(`tool-call-${Z}`);$&&(kYr(p.current,m.current,Z,"tool call removal"),$.remove())}});let ie=new Set(B.segments.filter(Z=>Z.type==="error"&&Z.error).map(Z=>Z.error.id));J.forEach(Z=>{if(!ie.has(Z)){let $=document.getElementById(`error-block-${Z}`);$&&(qYr(p.current,h.current,Z,"error block removal"),$.remove())}})}}return()=>{f.current=!0}},[t,e,d,r,w]),(0,Cr.useEffect)(()=>{let j=d,F=p.current,B=m.current,U=h.current;return(()=>{zYr(),HYr()})(),()=>{f.current=!0,setTimeout(()=>{j.current&&(j.current.unload(),j.current=null),F.startsWith("temp-")&&(VYr(F,B,"component cleanup"),JYr(F,U,"component cleanup"))},0)}},[]);let x=()=>{l(!0)},O=()=>{l(!1)},E=j=>{l(!1),o&&o(j)},T=()=>{t.sources&&t.sources.length>0&&new q$e(e,t.sources).open()},R=()=>{let j=e.workspace.getMostRecentLeaf();if((!j||!(j.view instanceof x3.MarkdownView))&&(j=e.workspace.getLeaf(!1),!j||!(j.view instanceof x3.MarkdownView)))return;let B=j.view.editor.getSelection().length>0,U=Dhe(t.message);Fz(U,B)},I=()=>t.content?Cr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-3"},t.content.map((j,F)=>j.type==="text"?Cr.default.createElement("div",{key:F},t.sender===Zs?Cr.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-break-words tw-text-[calc(var(--font-text-size)_-_2px)] tw-font-normal"},t.message):Cr.default.createElement("div",{ref:c,className:t.isErrorMessage?"tw-text-error":""})):j.type==="image_url"?Cr.defau
`).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"})),sn.default.createElement(ii,{label:"YouTube URLs"},sn.default.createElement(xx,{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"})))),sn.default.createElement("div",{className:"tw-mt-4 tw-flex tw-items-center tw-justify-end tw-gap-2"},sn.default.createElement(we,{variant:"ghost",onClick:r,disabled:o},"Cancel"),sn.default.createElement(we,{onClick:m,disabled:o||!f()},o?"Saving...":"Save")))}var zde=class extends Ude.Modal{constructor(r,n,o){super(r);this.onSave=n;this.initialProject=o}onOpen(){let{contentEl:r}=this;this.root=(0,FQr.createRoot)(r);let n=async i=>{await this.onSave(i),this.close()},o=()=>{this.close()};this.root.render(sn.default.createElement(Yci,{initialProject:this.initialProject,onSave:n,onCancel:o}))}onClose(){this.root.unmount()}};Fo();Zn();Bt();jt();In();var qQr=require("obsidian"),Ge=L(X());function Qci(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 kQr(t,e,r={}){return!t||t.length===0?[]:e.trim()?t.filter(n=>Qci(n,e,r)):t}function edi({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(ch,{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(Tn,null,Ge.default.createElement(En,{asChild:!0},Ge.default.createElement(we,{variant:"ghost2",size:"icon",onClick:o=>{o.stopPropagation(),r(t)}},Ge.default.createElement(cb,{className:"tw-size-4"}))),Ge.default.createElement(bn,{side:"bottom"},"Edit Project")),Ge.default.createElement(Tn,null,Ge.default.createElement(En,{asChild:!0},Ge.default.createElement(we,{variant:"ghost2",size:"icon",onClick:o=>{o.stopPropagation(),e(t)}},Ge.default.createElement($5,{className:"tw-size-4"}))),Ge.default.createElement(bn,{side:"bottom"},"Start Chat")),Ge.default.createElement(Tn,null,Ge.default.createElement(En,{asChild:!0},Ge.default.createElement(we,{variant:"ghost2",size:"icon",onClick:o=>{o.stopPropagation(),new sm(app,()=>n(t),`Are you sure you want to delete project "${t.name}"?`,"Delete Project").open()}},Ge.default.createElement(fy,{className:"tw-size-4"}))),Ge.default.createElement(bn,{side:"bottom"},"Delete Project"))))}var P_t=(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=_U();(0,Ge.useEffect)(()=>{a&&d(!1)},[a]);let _=(0,Ge.useMemo)(()=>kQr(e,g),[e,g]),w=()=>{new zde(n,async I=>{o(I)}).open()},x=R=>{new zde(n,async j=>{i(R,j),m&&m.name===R.name&&h(j)},R).open()},O=R=>{let j=(e||[]).filter(F=>F.name!==R.name);m?.name===R.name&&E(!1),ot("projectList",j),new qQr.Notice(`Project "${R.name}" deleted successfully`)},E=(R,I)=>{if(R){if(!I){ue("Must be exist one project.");return}h(I),p(!0),d(!1)}else{h(null),p(!1),d(!0),s(!1),_L(null);return}},T=R=>{h(R),p(!0),d(!1),s(!0),_L(R),setTimeout(()=>{b.focusInput()},0)};return Ge
- a positive number
- less than the value passed to \`max\` (or ${I_t} if no \`max\` prop is set)
- \`null\` or \`undefined\` if the progress is indeterminate.
Defaulting to \`null\`.`}var N_t=KQr,XQr=GQr;Zn();var j_t=Hde.forwardRef(({className:t,value:e,...r},n)=>Hde.createElement(N_t,{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},Hde.createElement(XQr,{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)}%)`}})));j_t.displayName=N_t.displayName;In();Us();Fo();Bt();function $_t({plugin:t,setHiddenCard:e,onEditContext:r}){let[n]=mee(),o=n.total,i=n.success,a=n.failed,s=n.processingFiles,[u,l]=(0,D_t.useState)(!1),[c,d]=(0,D_t.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 cn.createElement(O3,{className:"tw-w-full tw-border tw-border-solid tw-border-border tw-bg-transparent tw-shadow-none"},cn.createElement(T3,null,cn.createElement(jde,{className:"tw-flex tw-items-center tw-justify-between tw-gap-2"},cn.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},cn.createElement(Ol,{className:"tw-size-5"}),"Context Loading",cn.createElement(we,{size:"sm",variant:"ghost2",className:"tw-size-6 tw-p-0 tw-text-muted",title:"Edit Context",onClick:()=>r?.()},cn.createElement(og,{className:"tw-size-4"}),cn.createElement("span",{className:"tw-sr-only"},"Edit Context"))),cn.createElement("div",{className:"tw-flex tw-items-center tw-gap-2 tw-rounded tw-p-1"},cn.createElement(we,{size:"sm",variant:"ghost2",className:"tw-size-6 tw-p-0 tw-text-muted",title:"Close Progress Bar",onClick:()=>e(!0)},cn.createElement(ci,{className:"tw-size-4"}))))),cn.createElement(E3,{className:"tw-space-y-6"},cn.createElement("div",{className:"tw-space-y-2"},cn.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-text-sm"},cn.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},cn.createElement("span",{className:"tw-text-muted"},"Total progress"),cn.createElement("span",{className:"tw-text-xs tw-text-muted"},"(Success:"," ",cn.createElement("span",{className:"tw-font-medium tw-text-success"},i.length),", Failed: ",cn.createElement("span",{className:"tw-font-medium tw-text-error"},a.length),")")),cn.createElement("span",{className:"tw-font-medium"},f,"/",o.length," (",p,"%)")),cn.createElement(j_t,{value:p,className:"tw-h-2"})),s.length>0&&cn.createElement("div",{className:"tw-space-y-3"},cn.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)},cn.createElement(Jc,{className:"tw-size-4 tw-animate-spin tw-text-accent"}),cn.createElement("span",{className:"tw-text-sm tw-font-medium"},"Processing"),u?cn.createElement(Ys,{className:"tw-ml-auto tw-size-4"}):cn.createElement(og,{className:"tw-ml-auto tw-size-4"})),u&&cn.createElement("div",{className:"tw-max-h-32 tw-space-y-2 tw-overflow-y-auto"},s.map((g,y)=>cn.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"},cn.createElement("div",{className:"tw-size-2 tw-animate-pulse tw-rounded-full tw-bg-interactive-accent"}),cn.createElement(id,{className:"tw-flex-1",title:g},g))))),a.length>0&&cn.createElement("div",{className:"tw-space-y-3"},cn.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},cn.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)},cn.createElement(LO,{className:"tw-size-4 tw-text-error"}),cn.createElement("span",{className:"tw-text-sm tw-font-medium"},"Failed"),cn.createElement(qb,{variant:"destructive",className:"tw-text-xs"},a.length," files"),c?cn.createElement(Ys,{className:"tw-ml-auto tw-size-4"}):cn.createElement(og,{className:"tw-ml-auto tw-size-4"}))),c&&cn.cr
`).filter(o=>o.trim()),n=[];for(let o of r){let i=ddi(t,o.trim());i&&n.push(i)}return n}function QQr(t){let{app:e,contextNotes:r,setContextNotes:n,selectedImages:o,onAddImage:i,containerRef:a}=t,[s,u]=(0,MLe.useState)(!1);return(0,MLe.useEffect)(()=>{let l=a.current;if(!l)return;let c=p=>{if(p.preventDefault(),p.dataTransfer){p.dataTransfer.dropEffect="copy";let m=Array.from(p.dataTransfer.items).some(g=>g.kind==="string"),h=Array.from(p.dataTransfer.items).some(g=>g.kind==="file");(m||h)&&u(!0)}},d=p=>{let m=l.getBoundingClientRect(),h=p.clientX,g=p.clientY;(h<m.left||h>=m.right||g<m.top||g>=m.bottom)&&u(!1)},f=async p=>{if(!p.dataTransfer)return;p.preventDefault(),u(!1);let m=p.dataTransfer.items,h=[],g=[];for(let y=0;y<m.length;y++){let b=m[y];b.kind==="string"?h.push(b):b.kind==="file"&&g.push(b)}if(h.length>0){p.stopPropagation();let y=h.map(w=>new Promise(x=>{w.getAsString(O=>x(O))})),b=await Promise.all(y),_=new Map;for(let w of b){let x=fdi(e,w);for(let O of x)_.set(O.path,O)}for(let w of _.values())if(["png","gif","jpeg","jpg","webp"].includes(w.extension)){if(o.some(I=>I.name===w.name)){new I3.Notice("This image is already in the context");continue}let E=await e.vault.readBinary(w),T=new Blob([E]),R=new File([T],w.name,{type:`image/${w.extension}`});i([R])}else if(xO(w)){if(r.some(E=>E.path===w.path)){new I3.Notice("This note is already in the context");continue}n(E=>[...E,w])}else new I3.Notice(`Unsupported file type: ${w.extension}. Supported types: md, pdf, canvas, and images.`)}else if(g.length>0){let y=[];for(let b of g){let _=b.getAsFile();_&&_.type.startsWith("image/")&&y.push(_)}y.length>0&&i(y)}};return l.addEventListener("dragover",c),l.addEventListener("dragleave",d),l.addEventListener("drop",f),()=>{l.removeEventListener("dragover",c),l.removeEventListener("dragleave",d),l.removeEventListener("drop",f)}},[e,r,o,i,n,a]),{isDragActive:s}}Zr();yr();Bt();kU();xOe();var L_t=async(t,e,r,n,o,i={})=>{let a=new AbortController;o(a);try{await e.runChain(t,a,n,r,i)}catch(s){ue("Model request failed:",s);let u=rG("Model request failed: "+Mo(s));r({id:gv(),sender:TO,isErrorMessage:!0,message:u,isVisible:!0,timestamp:eg(new Date)})}};W1();$z();Lv();jt();yr();pOe();var gl=require("obsidian");var lr=L(X()),pdi=({chainManager:t,onSaveChat:e,updateUserMessageHistory:r,fileParserManager:n,plugin:o,chatUIState:i,chatInput:a})=>{let s=Wn(),u=(0,lr.useContext)(AX),{messages:l,addMessage:c}=YQr(i),[d]=Z0(),[f]=l_(),[p,m]=(0,lr.useState)(""),[h,g]=(0,lr.useState)(""),[y,b]=(0,lr.useState)(null),_=(0,lr.useRef)(null),w=(0,lr.useCallback)(Ue=>{c(Ue),Ue.sender===TO&&Ue.responseMetadata?.tokenUsage?.totalTokens&&b(Ue.responseMetadata.tokenUsage.totalTokens)},[c]),x=(0,lr.useCallback)(Ue=>{_.current=Ue},[]),[O,E]=(0,lr.useState)(!1),[T,R]=(0,lr.useState)(EO.DEFAULT),[I,j]=(0,lr.useState)([]),[F,B]=(0,lr.useState)(!1),[U,J]=(0,lr.useState)([]),[G,oe]=(0,lr.useState)(!1),[ne,z]=(0,lr.useState)([]),[ee,ie]=(0,lr.useState)(null),Z=(0,lr.useRef)(!1),$=(0,lr.useRef)(null),q=(0,lr.useMemo)(()=>({setCurrentAiMessage:Ue=>Z.current&&m(Ue),setLoadingMessage:Ue=>Z.current&&R(Ue),setLoading:Ue=>Z.current&&E(Ue)}),[]),[Y]=iHe(),D=Y.length>0,A=F&&!D,V=tje(),K=()=>xe!=="project"?!1:ee!==null?ee:V==="loading"||V==="error";(0,lr.useEffect)(()=>{ie(null)},[V]),(0,lr.useEffect)(()=>{l.length===0&&b(null)},[l]);let[se,be]=(0,lr.useState)(null),[xe,Pe]=l_(),pt=Z8(),Ht=(0,lr.useContext)(dLe),Ze=o.app||Ht,{isDragActive:Yr}=QQr({app:Ze,contextNotes:I,setContextNotes:j,selectedImages:U,onAddImage:Ue=>J(Rn=>[...Rn,...Ue]),containerRef:$}),Vt=async({toolCalls:Ue,urls:Rn,contextNotes:ui,contextTags:Xm,contextFolders:We}={})=>{if(!h&&U.length===0)return;Rn&&Rn.length>0&&!ib(f)&&new gl.Notice(G6.URL_PROCESSING_RESTRICTED);try{let Sr=[];h&&Sr.push({type:"text",text:h});for(let Iu of U){let Ym=await Iu.arrayBuffer(),pm=Ek(Ym);Sr.push({type:"image_url",image_url:{url:`data:${Iu.type};base64,${pm}`}})}let xi=[...ui||[],...I].filter((Iu,Ym,pm)=>pm.findIndex(pi=>pi.path===Iu.path)===Ym),ks=h;Ue&&(ks+=" "+Ue.join(`
`));let Gu={notes:xi,urls:ib(f)?Rn||[]:[],tags:Xm||[],folders:We||[],selectedTextContexts:Y};g(""),J([]),q.setLoading(!0),q.setLoadingMessage(EO.DEFAULT);let Jh=await i.sendMessage(ks,Gu,f,A,Sr.length>0?Sr:void 0);h&&r(h),s.autosaveChat&&gt();let fm=i.getLLMMessage(Jh);fm&&await L_t(fm,t,w,q.setCurrentAiMessage,x,{debug:s.debug,updateLoadingMessage:q.setLoadingMessage}),s.autosaveChat&&gt()}catch(Sr){ue("Error sending message:",Sr),new gl.Notice("Failed to send message. Please try again.")}finally{q.setLoading(!1),q.setLoadingMessage(EO.DEFAULT)}},gt=(0,lr.useCallback)(async()=>{if(!Ze){ue("App instance is not available.");return}try{await i.saveChat(d)}catch(Ue){ue("Error saving chat as note:",Mo(Ue)),new gl.Notice("Failed to save chat as note. Check console for details.")}},[Ze,i,d]),Ie=(0,lr.useCallback)(Ue=>{_.current&&(H(`stopping generation..., reason: ${Ue}`),_.current.abort(Ue),q.setLoading(!1),q.setLoadingMessage(EO.DEFAULT))},[q]);(0,lr.useEffect)(()=>(Z.current=!0,()=>{Z.current=!1,_.current&&_.current.abort("component-unmount")}),[]);let _n=(0,lr.useCallback)(async Ue=>{if(Ue<=0){new gl.Notice("Cannot regenerate the first message.");return}let Rn=l[Ue];if(!Rn){new gl.Notice("Message not found.");return}q.setCurrentAiMessage(""),q.setLoading(!0);try{await i.regenerateMessage(Rn.id,q.setCurrentAiMessage,w)?s.debug&&console.log("Message regenerated successfully"):new gl.Notice("Failed to regenerate message. Please try again."),s.autosaveChat&&gt()}catch(ui){ue("Error regenerating message:",ui),new gl.Notice("Failed to regenerate message. Please try again.")}finally{q.setLoading(!1)}},[l,i,s.debug,s.autosaveChat,gt,w,q]),Ct=(0,lr.useCallback)(async(Ue,Rn)=>{let ui=l[Ue];if(!(!ui||ui.message===Rn))try{if(!await i.editMessage(ui.id,Rn,f,A)){new gl.Notice("Failed to edit message. Please try again.");return}if(ui.sender===Zs){let We=Ue<l.length-1;if(await i.truncateAfterMessageId(ui.id),We){q.setLoading(!0);try{let It=i.getLLMMessage(ui.id);It&&await L_t(It,t,w,q.setCurrentAiMessage,x,{debug:s.debug,updateLoadingMessage:q.setLoadingMessage})}catch(It){ue("Error regenerating AI response:",It),new gl.Notice("Failed to regenerate AI response. Please try again.")}finally{q.setLoading(!1)}}}s.autosaveChat&&gt()}catch(Xm){ue("Error editing message:",Xm),new gl.Notice("Failed to edit message. Please try again.")}},[l,i,f,A,w,t,s.debug,s.autosaveChat,gt,q,x]);(0,lr.useEffect)(()=>{e&&e(gt)},[e,gt]);let Fe=(0,lr.useCallback)(Ue=>{let Rn=s.projectList||[];if(Rn.findIndex(It=>It.name===Ue.name)>=0)throw new Error(`Project "${Ue.name}" already exists, please use a different name`);let Xm=[...Rn,Ue];return ot("projectList",Xm),tl()?.id===Ue.id?sDe().then(()=>{new gl.Notice(`${Ue.name} added and context loaded`)}).catch(It=>{ue("Error loading project context:",It),new gl.Notice(`${Ue.name} added but context loading failed`)}):new gl.Notice(`${Ue.name} added successfully`),!0},[s.projectList]),At=(0,lr.useCallback)((Ue,Rn)=>{let ui=s.projectList||[];if(!ui.find(Sr=>Sr.name===Ue.name))throw new Error(`Project "${Ue.name}" does not exist`);let We=ui.map(Sr=>Sr.name===Ue.name?Rn:Sr);return ot("projectList",We),tl()?.id===Ue.id?(_L(Rn),sDe().then(()=>{new gl.Notice(`${Ue.name} updated and context reloaded`)}).catch(Sr=>{ue("Error reloading project context:",Sr),new gl.Notice(`${Ue.name} updated but context reload failed`)})):new gl.Notice(`${Ue.name} updated successfully`),!0},[s.projectList]),ke=(0,lr.useCallback)(Ue=>{nHe(Ue)},[]);(0,lr.useEffect)(()=>{let Ue=()=>{a.focusInput()};return u?.addEventListener(eS.CHAT_IS_VISIBLE,Ue),()=>{u?.removeEventListener(eS.CHAT_IS_VISIBLE,Ue)}},[u,a]);let ze=(0,lr.useCallback)(async Ue=>{let Rn=l[Ue];if(!Rn){new gl.Notice("Message not found.");return}try{await i.deleteMessage(Rn.id)||new gl.Notice("Failed to delete message. Please try again.")}catch(ui){ue("Error deleting message:",ui),new gl.Notice("Failed to delete message. Please try again.")}},[l,i]),$e=(0,lr.useCallback)(async()=>{if(tG(),await bm.clear(),Ie("new-chat"),s.enableRecentConversations)try{let Ue=t.chatModelManager.getChatModel()
Original name: ${a.title}
${a.content}`}):e.push(a)}await Lg.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 ${PB()}.`;r.length>0&&(await gdi(r),i+=`
We found ${r.length} unsupported commands. They are saved in ${PB()}/unsupported. To fix them, please resolve the errors and move the note file out of the unsupported folder.`),ot("inlineEditCommands",[]),new sm(app,()=>{},i,"\u{1F680} New Copilot Custom Commands","OK","").open()}async function q_t(){let t=K_(),e=w2r.filter(n=>!t.some(o=>o.title===n.title)),r=[...t,...e];Lg.getInstance().updateCommands(r)}async function uen(){if(ce().suggestedDefaultCommands)return;K_().length===0&&(new sm(app,()=>{q_t()},"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(),ot("suggestedDefaultCommands",!0))}var kc=L(X()),Jde=require("obsidian"),len=L(Sm());Fo();Us();jt();function ydi({plugin:t,onRemove:e}){let[r,n]=(0,kc.useState)(""),o=Wn(),[i,a]=(0,kc.useState)(""),[s]=Z0(),u=(0,kc.useRef)(null),l=o.quickCommandModelKey??s,c=o.quickCommandIncludeNoteContext;(0,kc.useEffect)(()=>{let g=t.app.workspace.getActiveViewOfType(Jde.MarkdownView);if(g&&g.editor){let y=g.editor.getSelection();a(y)}},[t.app]),(0,kc.useEffect)(()=>{u.current&&u.current.focus()},[]);let d=async()=>{if(!r.trim()){new Jde.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 RB(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=>{ot("quickCommandModelKey",g)},h=g=>{ot("quickCommandIncludeNoteContext",g)};return kc.default.createElement("div",{className:"tw-rounded-lg tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-4",onKeyDown:p},kc.default.createElement("div",{className:"tw-space-y-4"},kc.default.createElement(xx,{ref:u,value:r,onChange:g=>n(g.target.value),placeholder:"Ask me anything...",className:"tw-min-h-24 tw-resize-none",rows:3}),kc.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-gap-4"},kc.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-4"},kc.default.createElement(lDe,{size:"sm",variant:"ghost",value:l,onChange:m}),kc.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},kc.default.createElement(od,{id:"includeActiveNote",checked:c,onCheckedChange:g=>h(!!g)}),kc.default.createElement("label",{htmlFor:"includeActiveNote",className:"tw-cursor-pointer tw-text-sm tw-text-muted"},"Include note context"))),kc.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},kc.default.createElement(we,{variant:"secondary",onClick:f,size:"sm"},"Cancel"),kc.default.createElement(we,{onClick:d,size:"sm"},"Submit")))))}function cen({plugin:t,element:e}){let r=document.createElement("div");e.appendChild(r);let n=(0,len.createRoot)(r),o=()=>{let i=t.app.workspace.getActiveViewOfType(Jde.MarkdownView);i&&i.editor&&X1e(i.editor),n.unmount(),r.remove()};return n.render(kc.default.createElement(ydi,{plugin:t,onRemove:o})),{root:n,container:r}}Zr();jt();Hc();Us();Bt();Ik();Zr();async function den(t,e){await e.clearChatMemory();for(let r=0;r<t.length-1;r++){let n=t[r];if(n.sender===Zs){let o=t[r+1];o?.sender===TO&&await e.getMemory().saveContext({input:n.message},{output:o.message})}}}Us();Hc();var men=L(wH());Bt();var fen=["L1_SYSTEM","L2_PREVIOUS","L3_TURN","L4_STRIP","L5_USER"],pen={L1_SYSTEM:"System Instructions",L2_PREVIOUS:"Previous Turn Context",L3_TURN:"Current Turn Context",L4_STRIP:"Conversation Strip",L5_USER:"User Message"};var RU=class RU{constructor(){}static getInstance(){return RU.instance||(RU.instance=new RU),RU.instance}buildEnvelope(e){let r=fen.map(s=>this.buildLayer(s,e.layerSegments[s]??[])),n=this.serializeLayers(r),o=this.collectLayerHashes(r),i=this.hash(n),a=typeof e.metadata?.debugLabel=="string"?e.metadata.debugLabel:void 0;return a&&H(`[PromptContextEngine] Built envelope for ${a}`,o),{version:RU.ENVELOPE_VERSION,conversationId:e.conversationId,messageId:e.messageId,layers:r,serializedText:n,layerHashes:o,combinedHash:i,debug:{warnings:this.collectWarnings(r)}}}buildLayer(e,r){let n=r.map((i,a)=>({...i,id:i.id||`${e}-segment-${a}`,content:this.normalizeWhitespace(i.content),stable:i.stable??!0})),o=this.normalizeWhitespace(n.map(i=>i.content).filter(Boolean).join(`
`));return{id:e,label:pen[e],text:o,segments:n,stable:n.every(i=>i.stable),metadata:n.length===1?n[0].metadata:void 0,hash:this.hash(o)}}serializeLayers(e){return e.map(r=>r.text).filter(r=>r.length>0).join(`
`)}collectLayerHashes(e){return e.reduce((r,n)=>(r[n.id]=n.hash,r),{})}hash(e){return(0,men.SHA256)(e||"").toString()}normalizeWhitespace(e){return e.replace(/\s+$/g,"").trim()}collectWarnings(e){let r=[];return e.forEach(n=>{if(!n.text)return;n.text.includes("\0")&&r.push(`Layer ${n.id} contains control characters and was normalized`)}),r}};RU.ENVELOPE_VERSION=1;var ILe=RU;Us();Zr();Bt();yr();var Kde=require("obsidian");Zr();var NLe=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 Kde.TFile)try{let l=await n.parseFile(u,r);e=e.replace(a[0],`
<${see}>
<name>${s}</name>
<content>
${l}
</content>
</${see}>
`)}catch(l){ue(`Error processing embedded PDF ${s}:`,l),e=e.replace(a[0],`
<${see}>
<name>${s}</name>
<error>Could not process PDF</error>
</${see}>
`)}}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=`
<${uee}>
<query_type>${l}</query_type>
<original_query>
${c}
</original_query>
<executed_result>
${p}
</executed_result>
</${uee}>
`;e=e.slice(0,d)+m+e.slice(f)}catch(p){ue("Error executing Dataview query:",p);let m=`
<${uee}>
<query_type>${l}</query_type>
<original_query>
${c}
</original_query>
<error>${p instanceof Error?p.message:"Query execution failed"}</error>
</${uee}>
`;e=e.slice(0,d)+m+e.slice(f)}}return e}async executeDataviewQuery(e,r,n,o){if(n==="dataviewjs")return"[DataviewJS execution not yet supported - showing original query]";let i=await e.query(r,o);if(!i.successful)throw new Error(i.error||"Query failed");return this.formatDataviewResult(i.value)}formatDataviewResult(e){return e?e.type==="list"?this.formatDataviewList(e.values):e.type==="table"?this.formatDataviewTable(e.headers,e.values):e.type==="task"?this.formatDataviewTasks(e.values):Array.isArray(e)?e.map(r=>this.formatDataviewValue(r)).join(`
`):String(e):"No results"}formatDataviewList(e){return!e||e.length===0?"No results":e.map(r=>`- ${this.formatDataviewValue(r)}`).join(`
`)}formatDataviewTable(e,r){if(!r||r.length===0)return"No results";let n=`| ${e.join(" | ")} |
`;n+=`| ${e.map(()=>"---").join(" | ")} |
`;for(let o of r)n+=`| ${o.map(i=>this.formatDataviewValue(i)).join(" | ")} |
`;return n}formatDataviewTasks(e){return!e||e.length===0?"No results":e.map(r=>`- ${r.completed?"[x]":"[ ]"} ${this.formatDataviewValue(r.text||r)}`).join(`
`)}formatDataviewValue(e){return e==null?"":e&&typeof e=="object"&&e.path?`[[${e.path}]]`:Array.isArray(e)?e.map(r=>this.formatDataviewValue(r)).join(", "):String(e)}async buildMarkdownContextContent(e,r,n,o){let i=await n.parseFile(e,r);return i=await this.processEmbeddedNotes(i,e,r,n,o),ib(o)&&(i=await this.processEmbeddedPDFs(i,r,n)),await this.processDataviewBlocks(i,e.path)}async processEmbeddedNotes(e,r,n,o,i){let a=/!\[\[([^\]]+)\]\]/g,s,u=0,l="";for(;(s=a.exec(e))!==null;){l+=e.slice(u,s.index);let c=s[1].trim(),d=await this.buildEmbeddedNoteBlock(c,s[0],r,n,o,i);l+=d,u=s.index+s[0].length}return l+=e.slice(u),l}async buildEmbeddedNoteBlock(e,r,n,o,i,a){let s=this.parseEmbeddedLinkTarget(e);if(!s)return r;let u=s.path===null?n:app.metadataCache.getFirstLinkpathDest(s.path,n.path);if(!(u instanceof Kde.TFile))return this.formatEmbeddedNoteBlock({title:s.path??n.basename,path:s.path??n.path,heading:s.heading,blockId:s.blockId,error:"Embedded note not found"});if(u.extension!=="md")return r;try{let l=await i.parseFile(u,o);if(s.heading||s.blockId){let c=this.extractMarkdownSegment(u,l,s);if(!c.found){let d=s.blockId?`block reference "${s.blockId}"`:`heading "${s.heading??""}"`;throw new Error(`Embedded note ${d} not found in ${u.path}`)}l=c.content}return ib(a)&&(l=await this.processEmbeddedPDFs(l,o,i)),l=await this.processDataviewBlocks(l,u.path),this.formatEmbeddedNoteBlock({title:u.basename,path:u.path,heading:s.heading,blockId:s.blockId,content:l})}catch(l){it("Failed to process embedded note",l);let c=l instanceof Error?l.message:"Could not process embedded note";return this.formatEmbeddedNoteBlock({title:u.basename,path:u.path,heading:s.heading,blockId:s.blockId,error:c})}}parseEmbeddedLinkTarget(e){if(!e)return null;let r=e.indexOf("|"),o=(r>=0?e.slice(0,r):e).trim();if(!o)return{path:null};let i,a,s=o.indexOf("#^");s!==-1&&(i=o.slice(s+2).trim(),o=o.slice(0,s));let u=o.indexOf("#");return u!==-1&&(a=o.slice(u+1).trim(),o=o.slice(0,u)),{path:o.length>0?o:null,heading:a&&a.length>0?a:void 0,blockId:i&&i.length>0?i:void 0}}extractMarkdownSegment(e,r,n){let o=app.metadataCache.getFileCache(e);if(n.blockId){let i=o?.blocks?.[n.blockId],a=i?.position?.start?.offset,s=i?.position?.end?.offset;return a===void 0||s===void 0?{content:"",found:!1}:{content:r.slice(a,s),found:!0}}if(n.heading){let i=o?.headings??[],a=this.normalizeHeadingForMatch(n.heading),s=i.findIndex(d=>this.normalizeHeadingForMatch(d.heading)===a);if(s===-1)return{content:"",found:!1};let u=i[s],l=u.position?.start?.offset??0,c=r.length;for(let d=s+1;d<i.length;d++)if(i[d].level<=u.level){c=i[d].position?.start?.offset??c;break}return{content:r.slice(l,c),found:!0}}return{content:r,found:!0}}normalizeHeadingForMatch(e){return e.trim().toLowerCase().replace(/\s+/g," ")}formatEmbeddedNoteBlock(e){let{title:r,path:n,heading:o,blockId:i,content:a,error:s}=e,u=`
<${I2e}>
<title>${r}</title>
<path>${n}</path>`;return o&&(u+=`
<heading>${o}</heading>`),i&&(u+=`
<block_id>${i}</block_id>`),s?u+=`
<error>${s}</error>`:u+=`
<content>
${a??""}
</content>`,u+=`
</${I2e}>
`,u}async processContextNotes(e,r,n,o,i,a,s){let u="",l=async(d,f=iee)=>{try{if(e.has(d.path)){H(`Skipping note ${d.path} as it was included via custom prompt.`);return}if(H(`Processing note: ${d.path}, extension: ${d.extension}, chain: ${s}`),!r.supportsExtension(d.extension)){it(`Unsupported file type: ${d.extension}`);return}if(!ib(s)&&d.extension!=="md"&&d.extension!=="canvas"){it(`File type ${d.extension} requires Copilot Plus mode for context processing.`),new Kde.Notice(G6.NON_MARKDOWN_FILES_RESTRICTED);return}let p=d.extension==="md"?await this.buildMarkdownContextContent(d,n,r,s):await r.parseFile(d,n),m=await n.adapter.stat(d.path),h=m?new Date(m.ctime).toISOString():"Unknown",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){ue(`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=vL();if(!e||e.length===0)return"";let r="";for(let n of e)r+=`
<${s_}>
<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>
</${s_}>`;return r}};Bt();Jnt();yr();var jLe=class t{constructor(){this.contextProcessor=NLe.getInstance(),this.mention=Y8.getInstance(),this.promptContextEngine=ILe.getInstance()}static getInstance(){return t.instance||(t.instance=new t),t.instance}async processMessageContext(e,r,n,o,i,a,s,u){try{H(`[ContextManager] Processing context for message ${e.id}`);let l=e.originalMessage||e.message,{processedPrompt:c,includedFiles:d}=await kpt(l,"",n,a),f=await this.buildL2ContextFromPreviousTurns(e.id,s,r,n,o),p=e.context?.urls||[],m=o==="copilot_plus"?await this.mention.processUrlList(p):{urlContext:"",imageUrls:[]},h=new Set(d.map(I=>I.path)),y=[...e.context?.notes||[]];i&&o!=="project"&&a&&!h.has(a.path)&&!y.some(I=>I.path===a.path)&&y.push(a);let b=await this.contextProcessor.processContextNotes(h,r,n,y,i,a,o);y.forEach(I=>h.add(I.path));let _=e.context?.tags||[],w="";if(_.length>0){let j=Nhe(n,_).filter(F=>!h.has(F.path));j.length>0&&(w=await this.contextProcessor.processContextNotes(new Set,r,n,j,!1,null,o),j.forEach(F=>h.add(F.path)))}let x=e.context?.folders||[],O="";if(x.length>0){let j=x.flatMap(F=>QQ(n,F)).filter(F=>!h.has(F.path));j.length>0&&(O=await this.contextProcessor.processContextNotes(new Set,r,n,j,!1,null,o),j.forEach(F=>h.add(F.path)))}let E=this.contextProcessor.processSelectedTextContexts(),T=c+f+b+w+O+m.urlContext+E;H(`[ContextManager] Successfully processed context for message ${e.id}`);let R=this.buildPromptContextEnvelope({chainType:o,message:e,systemPrompt:u||"",processedUserMessage:c,l2PreviousContext:f,noteContextAddition:b,tagContextAddition:w,folderContextAddition:O,urlContext:m.urlContext,selectedText:E});return{processedContent:T,contextEnvelope:R}}catch(l){return H(`[ContextManager] Error processing context for message ${e.id}:`,l),{processedContent:e.originalMessage||e.message,contextEnvelope:void 0}}}async reprocessMessageContext(e,r,n,o,i,a,s,u){let l=r.getMessage(e);if(!l||l.sender!=="user"||!l.id)return;H(`[ContextManager] Reprocessing context for message ${e}`);let{processedContent:c,contextEnvelope:d}=await this.processMessageContext(l,n,o,i,a,s,r,u);r.updateProcessedText(l.id,c,d),H(`[ContextManager] Completed context reprocessing for message ${e}`)}async buildL2ContextFromPreviousTurns(e,r,n,o,i){let a=r.getDisplayMessages(),s=a.findIndex(p=>p.id===e);if(s===-1||s===0)return"";let u=a.slice(0,s).filter(p=>p.sender==="user"),l=new Map,c=new Map;for(let p of u)if(p.context){if(p.context.notes)for(let m of p.context.notes)l.has(m.path)||l.set(m.path,{file:m,firstSeen:p.timestamp?.epoch||Date.now()});if(p.context.urls)for(let m of p.context.urls)c.has(m)||c.set(m,{url:m,firstSeen:p.timestamp?.epoch||Date.now()})}let d=Array.from(l.values()).sort((p,m)=>p.firstSeen-m.firstSeen),f="";if(d.length>0){let p=d.map(h=>h.file),m=await this.contextProcessor.processContextNotes(new Set,n,o,p,!1,null,i);f+=m}return f}buildPromptContextEnvelope(e){let r=e.message.id;if(!r)return;let n={};if(e.systemPrompt&&(n.L1_SYSTEM=[{id:"system",content:e.systemPrompt,stable:!0,metadata:{source:"system_prompt"}}]),e.l2PreviousContext){let i=this.parseContextIntoSegments(e.l2PreviousContext,!0);i.length>0&&(n.L2_PREVIOUS=i)}let o=[];if(e.noteContextAddition){let i=this.parseContextIntoSegments(e.noteContextAddition,!1);o.push(...i)}return this.appendTurnContextSegment(o,"tags",e.tagContextAddition,{source:"tags"}),this.appendTurnContextSegment(o,"folders",e.folderContextAddition,{source:"folders"}),this.appendTurnContextSegment(o,"urls",e.urlContext,{source:"urls"}),this.appendTurnContextSegment(o,"selected_text",e.selectedText,{source:"selected_text"}),o.length>0&&(n.L3_TURN=o),n.L5_USER=[{id:`${r}-user`,content:e.processedUserMessage,stable:!1,metadata:{source:"user_input"}}],this.promptContextEngine.buildEnvelope({conversationId:null,messageId:r,layerSegments:n,metadata:{debugLabel:`message:${r}`,chainType:e.chainType}})}parseContextIntoSegments(e,r){if(!e.trim())return[];let n=[],o=/<(?:note_context|active_note)>[\s\S]*?<\/(?:note_context|active_note)>/g,i;for(;(i=o.exec(e))!==null;){let a=i[0],s=/<path>([^
[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"?Zs: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=>{let u=s.trim(),l=this.app.vault.getAbstractFileByPath(u);if(l instanceof mv.TFile)return l;let c=u.includes("/")?u.split("/").pop():u,d=this.app.vault.getMarkdownFiles().filter(f=>f.basename===c);return d.length===1?(H(`[ChatPersistenceManager] Resolved legacy basename "${c}" to ${d[0].path}`),d[0]):(d.length>1?it(`[ChatPersistenceManager] Ambiguous basename "${c}", skipping. Matches: ${d.map(f=>f.path).join(", ")}`):it(`[ChatPersistenceManager] Note not found: ${u}`),null)}).filter(s=>s!==null))}else if(i.startsWith("URLs: ")){let a=i.substring(6);a&&(r.urls=a.split(", ").map(s=>s.trim()))}else if(i.startsWith("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 Fhe(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=eg(new Date(r)).fileName,s;if(n)s=n;else{let w=e.find(x=>x.sender===Zs);s=w&&w.message.replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/[{}[\]]/g,"").split(/\s+/).slice(0,10).join(" ").replace(/[\\/:*?"<>|\x00-\x1F]/g,"").trim()||"Untitled Chat"}let u=o.defaultConversationNoteName||"{$date}_{$time}__{$topic}",l=tl(),c=l?`${l.id}__`:"",d=ree(".md"),f=ree(c),p=u.replace("{$topic}","").replace("{$date}",a.split("_")[0]).replace("{$time}",a.split("_")[1]),m=ree(p),h=Math.max(20,B_t-d-f-m),g=s.replace(/\s+/g,"_"),y=M2e(g,h);u=u.replace("{$topic}",y).replace("{$date}",a.split("_")[0]).replace("{$time}",a.split("_")[1]);let b=u.replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/[{}[\]]/g,"_").replace(/[\\/:*?"<>|\x00-\x1F]/g,"_"),_=`${c}${b}.md`;if(ree(_)>B_t){let w=B_t-d-f,x=M2e(b,w);return`${o.defaultSaveFolder}/${c}${x}.md`}return`${o.defaultSaveFolder}/${_}`}generateNoteContent(e,r,n,o){let i=ce(),a=tl();return`---
epoch: ${r}
modelKey: "${bdi(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)}),H(`[ChatPersistenceManager] Applied AI topic to chat file: ${e.path}`)}catch(n){ue("[ChatPersistenceManager] Error applying AI topic to file:",n)}}isNameTooLongError(e){if(!e)return!1;let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("enametoolong")||n.includes("name too long")}isFileAlreadyExistsError(e){return e?(e instanceof Error?e.message:String(e)).toLowerCase().includes("already exists"):!1}};Zr();var DLe=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=jLe.getInstance(),this.projectMessageRepos.set(this.defaultProjectKey,e),this.persistenceManager=new Wde(o.app,e,r)}getCurrentMessageRepo(){let e=this.plugin.projectManager.getCurrentProjectId(),r=e??this.defaultProjectKey;if(this.lastKnownProjectId!==e&&(H(`[ChatManager] Project changed from ${this.lastKnownProjectId} to ${e}`),this.lastKnownProjectId=e),!this.projectMessageRepos.has(r)){H(`[ChatManager] Creating new message repository for project: ${r}`);let o=new UX;this.projectMessageRepos.set(r,o)}let n=this.projectMessageRepos.get(r);return this.persistenceManager=new Wde(this.plugin.app,n,this.chainManager),n}setOnMessageCreatedCallback(e){this.onMessageCreatedCallback=e}async getSystemPromptForMessage(e){let r=await ON(this.chainManager.userMemoryManager);if(e==="project"){let n=tl();if(n){let o=await xg.instance.getProjectContext(n.id),i=`${r}
<project_system_prompt>
${n.systemPrompt}
</project_system_prompt>`;return o&&(i+=`
<project_context>
${o}
</project_context>`),i}}return r}async sendMessage(e,r,n,o=!1,i){try{H(`[ChatManager] Sending message: "${e}"`);let a=this.plugin.app.workspace.getActiveFile(),s={...r};if(o&&a){let m=r.notes||[],h=m.some(g=>g.path===a.path);s.notes=h?m:[...m,a]}let u=this.getCurrentMessageRepo(),l=u.addMessage(e,e,Zs,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.getSystemPromptForMessage(n),{processedContent:f,contextEnvelope:p}=await this.contextManager.processMessageContext(c,this.fileParserManager,this.plugin.app.vault,n,o,a,u,d);return u.updateProcessedText(l,f,p),H(`[ChatManager] Successfully sent message ${l}`),l}catch(a){throw H("[ChatManager] Error sending message:",a),a}}async editMessage(e,r,n,o=!1){try{H(`[ChatManager] Editing message ${e}: "${r}"`);let i=this.getCurrentMessageRepo();if(!i.editMessage(e,r))return!1;let s=this.plugin.app.workspace.getActiveFile(),u=await this.getSystemPromptForMessage(n);return await this.contextManager.reprocessMessageContext(e,i,this.fileParserManager,this.plugin.app.vault,n,o,s,u),await this.updateChainMemory(),H(`[ChatManager] Successfully edited message ${e}`),!0}catch(i){return H(`[ChatManager] Error editing message ${e}:`,i),!1}}async regenerateMessage(e,r,n,o){try{H(`[ChatManager] Regenerating message ${e}`);let i=this.getCurrentMessageRepo();if(!i.getMessage(e))return H(`[ChatManager] Message not found: ${e}`),!1;let s=i.getDisplayMessages(),u=s.findIndex(f=>f.id===e);if(u<=0)return H("[ChatManager] Cannot regenerate first message or no user message found"),!1;let l=s[u-1];if(l.sender!==Zs)return H("[ChatManager] Previous message is not from user"),!1;if(i.truncateAfter(u-1),o&&o(),await this.updateChainMemory(),!l.id)return H("[ChatManager] User message has no ID for regeneration"),!1;let c=i.getLLMMessage(l.id);if(!c)return H("[ChatManager] LLM message not found for regeneration"),!1;let d=new AbortController;return await this.chainManager.runChain(c,d,r,n,{debug:ce().debug}),H(`[ChatManager] Successfully regenerated message ${e}`),!0}catch(i){return H(`[ChatManager] Error regenerating message ${e}:`,i),!1}}async deleteMessage(e){try{return H(`[ChatManager] Deleting message ${e}`),this.getCurrentMessageRepo().deleteMessage(e)?(await this.updateChainMemory(),H(`[ChatManager] Successfully deleted message ${e}`),!0):!1}catch(r){return H(`[ChatManager] Error deleting message ${e}:`,r),!1}}addMessage(e){return this.getCurrentMessageRepo().addMessage(e)}clearMessages(){this.getCurrentMessageRepo().clear(),this.chainManager.memoryManager.clearChatMemory(),H("[ChatManager] Cleared all messages")}async truncateAfterMessageId(e){this.getCurrentMessageRepo().truncateAfterMessageId(e),await this.updateChainMemory(),H(`[ChatManager] Truncated messages after ${e}`)}getDisplayMessages(){return this.getCurrentMessageRepo().getDisplayMessages()}getLLMMessages(){return this.getCurrentMessageRepo().getLLMMessages()}getMessage(e){return this.getCurrentMessageRepo().getMessage(e)}getLLMMessage(e){return this.getCurrentMessageRepo().getLLMMessage(e)}async updateChainMemory(){try{let r=this.getCurrentMessageRepo().getLLMMessages();await den(r,this.chainManager.memoryManager),H(`[ChatManager] Updated chain memory with ${r.length} messages`)}catch(e){H("[ChatManager] Error updating chain memory:",e)}}async loadMessages(e){let r=this.getCurrentMessageRepo();r.clear(),e.forEach(n=>{r.addMessage(n)}),await this.updateChainMemory(),H(`[ChatManager] Loaded ${e.length} messages`)}async saveChat(e){await this.persistenceManager.saveChat(e)}getDebugInfo(){return{...this.getCurrentMessageRepo().getDebugInfo(),currentProject:this.plugin.projectManager.getCurrentProjectId(),totalProjects:this.projectMessageRepos.size}}async handleProjectSwitch(){let e=this.plugin.projectManager.getCurrentProjectId();H(`[ChatManager] Handling project switch to: ${e}`),this.lastKnownProjectId=null;let r=this.getCurrentMessageRepo();await this.updateChainMemory(),H(`[ChatManager] Project switch complete. Messages: ${r.g
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.
`},Odi={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 Tdi(t){let{announcements:e=Odi,container:r,hiddenTextDescribedById:n,screenReaderInstructions:o=xdi}=t,{announce:i,announcement:a}=Ten(),s=D3("DndLiveRegion"),[u,l]=(0,Be.useState)(!1);if((0,Be.useEffect)(()=>{l(!0)},[]),Sdi((0,Be.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=Be.default.createElement(Be.default.Fragment,null,Be.default.createElement(xen,{id:n,value:o.draggable}),Be.default.createElement(Oen,{id:s,announcement:a}));return r?(0,k3.createPortal)(c,r):c}var Gm;(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"})(Gm||(Gm={}));function zLe(){}function KX(t,e){return(0,Be.useMemo)(()=>({sensor:t,options:e??{}}),[t,e])}function VLe(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return(0,Be.useMemo)(()=>[...e].filter(n=>n!=null),[...e])}var Qx=Object.freeze({x:0,y:0});function qen(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}function Ben(t,e){let{data:{value:r}}=t,{data:{value:n}}=e;return r-n}function Edi(t,e){let{data:{value:r}}=t,{data:{value:n}}=e;return n-r}function Een(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 Y_t(t,e){if(!t||t.length===0)return null;let[r]=t;return e?r[e]:r}function Pen(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 WX=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=Pen(e,e.left,e.top),i=[];for(let a of n){let{id:s}=a,u=r.get(s);if(u){let l=qen(Pen(u),o);i.push({id:s,data:{droppableContainer:a,value:l}})}}return i.sort(Ben)},Uen=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=Een(e),i=[];for(let a of n){let{id:s}=a,u=r.get(s);if(u){let l=Een(u),c=o.reduce((f,p,m)=>f+qen(l[m],p),0),d=Number((c/4).toFixed(4));i.push({id:s,data:{droppableContainer:a,value:d}})}}return i.sort(Ben)};function Pdi(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 Mdi=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=Pdi(s,e);u>0&&o.push({id:a,data:{droppableContainer:i,value:u}})}}return o.sort(Edi)};function Rdi(t,e,r){return{...t,scaleX:e&&r?e.width/r.width:1,scaleY:e&&r?e.height/r.height:1}}function zen(t,e){return t&&e?{x:t.left-e.left,y:t.top-e.top}:Qx}function Adi(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 Idi=Adi(1);function Ndi(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 Wu.useEffect(()=>{t&&(document.getElementById(t)||console.error(r))},[r,t]),null},hpi="DialogDescriptionWarning",gpi=({contentRef:t,descriptionId:e})=>{let n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Utn(hpi).contentName}}.`;return Wu.useEffect(()=>{let o=t.current?.getAttribute("aria-describedby");e&&o&&(document.getElementById(e)||console.warn(n))},[n,t,e]),null},ztn=Ptn,Htn=Rtn,Vtn=Itn,fvt=Ntn,pvt=jtn,mvt=$tn,hvt=Ftn,Jtn=qtn;In();Zn();var rFe=ztn,Ktn=Htn,bpi=Vtn;var Wtn=Vg.forwardRef(({className:t,...e},r)=>Vg.createElement(fvt,{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}));Wtn.displayName=fvt.displayName;var ufe=Vg.forwardRef(({className:t,children:e,container:r,...n},o)=>Vg.createElement(bpi,{container:r},Vg.createElement(Wtn,null),Vg.createElement(pvt,{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,Vg.createElement(Jtn,{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"},Vg.createElement(ci,{className:"tw-size-4"}),Vg.createElement("span",{className:"tw-sr-only"},"Close")))));ufe.displayName=pvt.displayName;var lfe=({className:t,...e})=>Vg.createElement("div",{className:Oe("tw-flex tw-flex-col tw-space-y-0.5 tw-text-center sm:tw-text-left",t),...e});lfe.displayName="DialogHeader";var _pi=({className:t,...e})=>Vg.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});_pi.displayName="DialogFooter";var cfe=Vg.forwardRef(({className:t,...e},r)=>Vg.createElement(mvt,{ref:r,className:Oe("tw-mt-0 tw-text-lg tw-font-semibold tw-leading-none tw-tracking-tight",t),...e}));cfe.displayName=mvt.displayName;var dfe=Vg.forwardRef(({className:t,...e},r)=>Vg.createElement(hvt,{ref:r,className:Oe("tw-text-sm tw-text-muted",t),...e}));dfe.displayName=hvt.displayName;yr();function mn(t){let{title:e,description:r,className:n,disabled:o}=t,{modalContainer:i}=zX(),a="onChange"in t?t.onChange:void 0,s=(0,yl.useMemo)(()=>{if(a)return $he(l=>{a(l)},1e3)},[a]),u=()=>{switch(t.type){case"text":case"number":return yl.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 yl.default.createElement(UI,{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 yl.default.createElement(xx,{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 yl.default.createElement(wZ,{checked:t.checked,onCheckedChange:t.onCheckedChange,disabled:o});case"select":return yl.default.createElement("div",{className:"tw-group tw-relative tw-w-full sm:tw-w-[200px]"},yl.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: `+J)}return U}finally{clearTimeout(B)}},T;try{T=await E(!1)}catch(j){console.log("First fetch attempt failed, trying with safeFetch...");try{T=await E(!0)}catch(F){let B=`
without CORS Error: `+Mo(j)+`
with CORS Error: `+Mo(F);throw new Error(B)}}let R=await T.json(),I=ern(_,R);i(j=>({...j,[_]:I})),s(null)}catch(x){ue(`Error fetching models for ${_}:`,x),l(_),s(null),new JI.Notice(`Failed to load models for ${ab(_)}: ${Mo(x)}`,5e3)}},b=async()=>{if(!c){new JI.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 xg.instance.getCurrentChainManager().chatModelManager.ping(O)}catch(T){_=!0,w=Mo(T),ue("Model verification failed:",T)}if(e.activeModels.find(T=>T.name===c.name&&T.provider===c.provider))_?new JI.Notice(`Model ${c.name} already exists in your models list (verification failed: ${w})`,1e4):new JI.Notice(`Model ${c.name} verified successfully! It already exists in your models list.`);else{let T=[...e.activeModels,{...O,apiKey:void 0}];ot("activeModels",T),_?new JI.Notice(`Model ${c.name} added to your models list (verification failed: ${w})`,1e4):new JI.Notice(`Model ${c.name} verified successfully and added to your models list!`)}}catch(x){ue("Error adding model:",x),new JI.Notice(`Failed to add model: ${Mo(x)}`,1e4)}finally{p(!1)}};return Mn.default.createElement("div",{className:"tw-max-h-[600px] tw-overflow-y-auto tw-p-4 sm:tw-max-w-[500px]"},Mn.default.createElement("div",{className:"tw-mb-4"},Mn.default.createElement("h2",{className:"tw-text-xl tw-font-bold"},"AI Provider Settings"),Mn.default.createElement("p",{className:"tw-text-sm tw-text-muted"},"Configure your AI providers by adding their API keys.")),Mn.default.createElement("div",{className:"tw-space-y-6 tw-py-4"},Mn.default.createElement("div",{className:"tw-space-y-4"},h.map(_=>{let w=hL(_.provider),x=!!w.listModelURL;return Mn.default.createElement(Mn.default.Fragment,{key:_.provider},Mn.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Mn.default.createElement("div",{className:"tw-flex tw-items-end tw-gap-2 tw-font-medium"},Mn.default.createElement("div",{className:"tw-truncate"},ab(_.provider))),Mn.default.createElement("div",{className:"tw-flex tw-flex-row tw-items-center tw-gap-2"},Mn.default.createElement("div",{className:"tw-flex-1"},Mn.default.createElement(UI,{className:"tw-max-w-full",value:_.apiKey,onChange:O=>g(_.provider,O)})),x&&Mn.default.createElement("div",null,Mn.default.createElement(we,{onClick:()=>{let O=r===_.provider?null:_.provider;n(O),O&&_.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?Mn.default.createElement(sC,{className:"tw-ml-1 tw-size-4"}):Mn.default.createElement(Ys,{className:"tw-ml-1 tw-size-4"})))),Mn.default.createElement("div",null,w.keyManagementURL&&Mn.default.createElement("a",{href:w.keyManagementURL,target:"_blank",rel:"noopener noreferrer",className:"tw-text-[10px] tw-text-accent hover:tw-text-accent-hover sm:tw-text-xs"},"Get ",ab(_.provider)," Key"))),x&&Mn.default.createElement(Zx,{open:r===_.provider,className:"tw-mt-2"},Mn.default.createElement(Xx,{className:"tw-rounded-md tw-p-3"},Mn.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Mn.default.createElement(ii,{label:"Model",description:"Add the currently selected model to model List. After adding, please check the Model Tab."},Mn.default.createElement("div",null,Mn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Mn.default.createElement("div",{className:"tw-flex-1"},Mn.default.createElement(TLe,{options:o[_.provider]?.sort((O,E)=>O.name.localeCompare(E.name)).map(O=>({label:O.name,value:O.id}))||[],onChange:O=>{let E=O.target.value,T=o[_.provider]?.find(R=>R.id===E);T&&d({id:T.id,name:T.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})),Mn.default.cr
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")}};Fo();Zr();jt();var frn=require("obsidian"),Wr=L(X()),prn=()=>{let t=Wn(),e=async r=>{if(r!==t.embeddingModelKey){if(t.enableSemanticSearchV3){new fFe(app,async()=>{ot("embeddingModelKey",r),await(await Promise.resolve().then(()=>($m(),Cg))).default.getInstance().indexVaultToVectorStore(!1)}).open();return}ot("embeddingModelKey",r),new frn.Notice("Embedding model saved. Enable Semantic Search to build the index.")}};return Wr.default.createElement("div",{className:"tw-space-y-4"},Wr.default.createElement("section",null,Wr.default.createElement("div",{className:"tw-space-y-4"},Wr.default.createElement(mn,{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 pFe(app,async()=>{ot("enableSemanticSearchV3",r),r&&await(await Promise.resolve().then(()=>($m(),Cg))).default.getInstance().indexVaultToVectorStore(!1)},r).open()}}),Wr.default.createElement(mn,{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=>ot("enableInlineCitations",r)}),Wr.default.createElement(mn,{type:"select",title:"Embedding Model",description:Wr.default.createElement("div",{className:"tw-space-y-2"},Wr.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},Wr.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."),Wr.default.createElement(Ni,{content:Wr.default.createElement("div",{className:"tw-flex tw-max-w-96 tw-flex-col tw-gap-2"},Wr.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:"),Wr.default.createElement("ul",{className:"tw-pl-4 tw-text-sm tw-text-muted"},Wr.default.createElement("li",null,"Require rebuilding your vault's vector index"),Wr.default.createElement("li",null,"Affect semantic search quality"),Wr.default.createElement("li",null,"Impact Question Answering feature performance")))}))),value:t.embeddingModelKey,onChange:e,options:t.activeEmbeddingModels.map(r=>({label:rZ(r),value:Qn(r)})),placeholder:"Model"}),Wr.default.createElement(mn,{type:"select",title:"Auto-Index Strategy",description:Wr.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},Wr.default.createElement("span",{className:"tw-leading-none"},"Decide when you want the vault to be indexed."),Wr.default.createElement(Ni,{content:Wr.default.createElement("div",{className:"tw-space-y-2 tw-py-2"},Wr.default.createElement("div",{className:"tw-space-y-1"},Wr.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Choose when to index your vault:"),Wr.default.createElement("ul",{className:"tw-list-disc tw-space-y-1 tw-pl-2 tw-text-sm"},Wr.default.createElement("li",null,Wr.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Wr.default.createElement("strong",{className:"tw-inline-block tw-whitespace-nowrap"},"NEVER:"),Wr.default.createElement("span",null,"Manual indexing via command or refresh only"))),Wr.default.createElement("li",null,Wr.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Wr.default.createElement("strong",{className:"tw-inline-block tw-whitespace-nowrap"},"ON STARTUP:"),Wr.default.createElement("span",null,"Index updates when plugin loads or reloads"))),Wr.default.createElement("li",null,Wr.default.c
/*! Bundled license information:
@langchain/core/dist/utils/fast-json-patch/src/helpers.js:
(*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2017-2022 Joachim Wester
* MIT licensed
*)
@langchain/core/dist/utils/sax-js/sax.js:
(*! http://mths.be/fromcodepoint v0.1.0 by @mathias *)
mustache/mustache.mjs:
(*!
* mustache.js - Logic-less {{mustache}} templates with JavaScript
* http://github.com/janl/mustache.js
*)
react/cjs/react.production.min.js:
(**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
moment/moment.js:
(*! moment.js *)
(*! version : 2.29.4 *)
(*! authors : Tim Wood, Iskren Chernev, Moment.js contributors *)
(*! license : MIT *)
(*! momentjs.com *)
ieee754/index.js:
(*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)
buffer/index.js:
(*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*)
scheduler/cjs/scheduler.production.min.js:
(**
* @license React
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
react-dom/cjs/react-dom.production.min.js:
(**
* @license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
react/cjs/react-jsx-runtime.production.min.js:
(**
* @license React
* react-jsx-runtime.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/shared/src/utils.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/defaultAttributes.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/Icon.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/createLucideIcon.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/arrow-big-up.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/arrow-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/arrow-up-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/bot.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/brain.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/check.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/chevron-down.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/chevron-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/chevron-up.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-alert.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-check-big.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-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 */