vault backup: 2025-07-12 10:26:56

This commit is contained in:
CrazyJasonwell committed 2025-07-12 10:26:56 +08:00
1 parent 7b8f306807
commit c4db5e33fb
7 files changed
+245 -246

No files matched your search

+1 -1
View File
@@ -338,7 +338,7 @@
"autocompleteAcceptKey": "Tab",
"allowAdditionalContext": true,
"enableWordCompletion": false,
"lastDismissedVersion": null,
"lastDismissedVersion": "2.9.4",
"passMarkdownImages": true,
"enableCustomPromptTemplating": true,
"suggestedDefaultCommands": true
+224 -224
View File
@@ -3,10 +3,10 @@ THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var Oer=Object.create;var u2=Object.defineProperty;var Per=Object.getOwnPropertyDescriptor;var Eer=Object.getOwnPropertyNames;var Ter=Object.getPrototypeOf,Aer=Object.prototype.hasOwnProperty;var dUe=t=>{throw TypeError(t)};var Ier=(t,e,r)=>e in t?u2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var w=(t,e)=>()=>(t&&(e=t(t=0)),e);var v=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Cf=(t,e)=>{for(var r in e)u2(t,r,{get:e[r],enumerable:!0})},fUe=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Eer(e))!Aer.call(t,o)&&o!==r&&u2(t,o,{get:()=>e[o],enumerable:!(n=Per(e,o))||n.enumerable});return t};var F=(t,e,r)=>(r=t!=null?Oer(Ter(t)):{},fUe(e||!t||!t.__esModule?u2(r,"default",{value:t,enumerable:!0}):r,t)),zl=t=>fUe(u2({},"__esModule",{value:!0}),t);var Cc=(t,e,r)=>Ier(t,typeof e!="symbol"?e+"":e,r),Mer=(t,e,r)=>e.has(t)||dUe("Cannot "+r);var pUe=(t,e,r)=>e.has(t)?dUe("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r);var mUe=(t,e,r)=>(Mer(t,e,"access private method"),r);function epe(){if(!yK&&(yK=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!yK))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return yK(Rer)}var yK,Rer,hUe=w(()=>{Rer=new Uint8Array(16)});function gUe(t,e=0){return Oc[t[e+0]]+Oc[t[e+1]]+Oc[t[e+2]]+Oc[t[e+3]]+"-"+Oc[t[e+4]]+Oc[t[e+5]]+"-"+Oc[t[e+6]]+Oc[t[e+7]]+"-"+Oc[t[e+8]]+Oc[t[e+9]]+"-"+Oc[t[e+10]]+Oc[t[e+11]]+Oc[t[e+12]]+Oc[t[e+13]]+Oc[t[e+14]]+Oc[t[e+15]]}var Oc,yUe=w(()=>{Oc=[];for(let t=0;t<256;++t)Oc.push((t+256).toString(16).slice(1))});var jer,tpe,bUe=w(()=>{jer=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),tpe={randomUUID:jer}});function Ner(t,e,r){if(tpe.randomUUID&&!e&&!t)return tpe.randomUUID();t=t||{};let n=t.random||(t.rng||epe)();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 gUe(n)}var yC,_Ue=w(()=>{bUe();hUe();yUe();yC=Ner});var l2=w(()=>{_Ue()});function Ler(t){xUe=t}function bK(){return xUe}function ut(t,e){let r=bK(),n=_K({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===DL?void 0:DL].filter(o=>!!o)});t.common.issues.push(n)}function vK(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)}function CUe(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 Hr(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(a,s)=>{var u,l;let{message:c}=t;return a.code==="invalid_enum_value"?{message:c??s.defaultError}:typeof s.data>"u"?{message:(u=c??n)!==null&&u!==void 0?u:s.defaultError}:a.code!=="invalid_type"?{message:s.defaultError}:{message:(l=c??r)!==null&&l!==void 0?l:s.defaultError}},description:o}}function PUe(t){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),e}function etr(t){return new RegExp(`^${PUe(t)}$`)}function EUe(t){let e=`${OUe}T${PUe(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function ttr(t,e){return!!((e==="v4"||!e)&&Ker.test(t)||(e==="v6"||!e)&&Jer.test(t))}function rtr(t,e){if(!zer.test(t))return!1;try{let[r]=t.split("."),n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||!o.typ||!o.alg||e&&o.alg!==e)}catch{return!1}}function ntr(t,e){return!!((e==="v4"||!e)&&Ger.test(t)||(e==="v6"||!e)&&Yer.test(t))}function otr(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,i=parseInt(t.toFixed(o).replace(".","")),a=parseInt(e.toFixed(o).replace(".",""));return i%a/Math.pow(10,o)}function jL(t){if(t instanceof fp){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=dp.create(jL(n))}return new fp({...t._def,shape:()=>e})}else return t instanceof wC?new wC({...t._def,type:jL(t.element)}):t instanceof dp?dp.create(jL(t.unwrap())):t instanceof qb?qb.create(jL(t.unwrap())):t instanceof Bb?Bb.create(t.items.map(e=>jL(e))):t}function ape(t,e){let r=_C(t),n=_C(e);if(t===e)return{valid:!0,data:t};if(r===bt.object&&n===bt.object){letLine truncated
var Ier=Object.create;var l2=Object.defineProperty;var Mer=Object.getOwnPropertyDescriptor;var Rer=Object.getOwnPropertyNames;var jer=Object.getPrototypeOf,Ner=Object.prototype.hasOwnProperty;var pUe=t=>{throw TypeError(t)};var Der=(t,e,r)=>e in t?l2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var w=(t,e)=>()=>(t&&(e=t(t=0)),e);var v=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Cf=(t,e)=>{for(var r in e)l2(t,r,{get:e[r],enumerable:!0})},mUe=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Rer(e))!Ner.call(t,o)&&o!==r&&l2(t,o,{get:()=>e[o],enumerable:!(n=Mer(e,o))||n.enumerable});return t};var F=(t,e,r)=>(r=t!=null?Ier(jer(t)):{},mUe(e||!t||!t.__esModule?l2(r,"default",{value:t,enumerable:!0}):r,t)),zl=t=>mUe(l2({},"__esModule",{value:!0}),t);var Cc=(t,e,r)=>Der(t,typeof e!="symbol"?e+"":e,r),Ler=(t,e,r)=>e.has(t)||pUe("Cannot "+r);var hUe=(t,e,r)=>e.has(t)?pUe("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r);var gUe=(t,e,r)=>(Ler(t,e,"access private method"),r);function npe(){if(!bK&&(bK=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!bK))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return bK(Fer)}var bK,Fer,yUe=w(()=>{Fer=new Uint8Array(16)});function bUe(t,e=0){return Oc[t[e+0]]+Oc[t[e+1]]+Oc[t[e+2]]+Oc[t[e+3]]+"-"+Oc[t[e+4]]+Oc[t[e+5]]+"-"+Oc[t[e+6]]+Oc[t[e+7]]+"-"+Oc[t[e+8]]+Oc[t[e+9]]+"-"+Oc[t[e+10]]+Oc[t[e+11]]+Oc[t[e+12]]+Oc[t[e+13]]+Oc[t[e+14]]+Oc[t[e+15]]}var Oc,_Ue=w(()=>{Oc=[];for(let t=0;t<256;++t)Oc.push((t+256).toString(16).slice(1))});var ker,ope,vUe=w(()=>{ker=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ope={randomUUID:ker}});function $er(t,e,r){if(ope.randomUUID&&!e&&!t)return ope.randomUUID();t=t||{};let n=t.random||(t.rng||npe)();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 bUe(n)}var bC,wUe=w(()=>{vUe();yUe();_Ue();bC=$er});var c2=w(()=>{wUe()});function qer(t){OUe=t}function _K(){return OUe}function ut(t,e){let r=_K(),n=vK({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===LL?void 0:LL].filter(o=>!!o)});t.common.issues.push(n)}function wK(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)}function PUe(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 Hr(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(a,s)=>{var u,l;let{message:c}=t;return a.code==="invalid_enum_value"?{message:c??s.defaultError}:typeof s.data>"u"?{message:(u=c??n)!==null&&u!==void 0?u:s.defaultError}:a.code!=="invalid_type"?{message:s.defaultError}:{message:(l=c??r)!==null&&l!==void 0?l:s.defaultError}},description:o}}function TUe(t){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),e}function itr(t){return new RegExp(`^${TUe(t)}$`)}function AUe(t){let e=`${EUe}T${TUe(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function atr(t,e){return!!((e==="v4"||!e)&&Xer.test(t)||(e==="v6"||!e)&&etr.test(t))}function str(t,e){if(!Ger.test(t))return!1;try{let[r]=t.split("."),n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||!o.typ||!o.alg||e&&o.alg!==e)}catch{return!1}}function utr(t,e){return!!((e==="v4"||!e)&&Qer.test(t)||(e==="v6"||!e)&&ttr.test(t))}function ltr(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,i=parseInt(t.toFixed(o).replace(".","")),a=parseInt(e.toFixed(o).replace(".",""));return i%a/Math.pow(10,o)}function NL(t){if(t instanceof fp){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=dp.create(NL(n))}return new fp({...t._def,shape:()=>e})}else return t instanceof SC?new SC({...t._def,type:NL(t.element)}):t instanceof dp?dp.create(NL(t.unwrap())):t instanceof qb?qb.create(NL(t.unwrap())):t instanceof Bb?Bb.create(t.items.map(e=>NL(e))):t}function lpe(t,e){let r=vC(t),n=vC(e);if(t===e)return{valid:!0,data:t};if(r===bt.object&&n===bt.object){letLine truncated
=== 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{console.warn("[WARNING]: LangSmith failed to fetch info on supported operations. Falling back to batch operations and default limits.")}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();await this.drainAutoBatchQueue(e)}async createRun(e){if(!this._filterForSampling([e]).length)return;let r={...this.headers,"Content-Type":"application/json"},n=e.project_name;delete e.project_name;let o=await this.prepareRunCreateOrUpdateInputs({session_name:n,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&o.trace_id!==void 0&&o.dotted_order!==void 0){this.processRunOperation({action:"create",item:o}).catch(console.error);return}let i=r4e(o),a=await this.caller.call(Vt(this.debug),`${this.apiUrl}/runs`,{method:"POST",headers:r,body:hp(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(a,"create run",!0)}async batchIngestRuns({runCreates:e,runUpdates:r}){if(e===void 0&&r===void 0)return;let n=await Promise.all(e?.map(s=>this.prepareRunCreateOrUpdateInputs(s))??[]),o=await Promise.all(r?.map(s=>this.prepareRunCreateOrUpdateInputs(s))??[]);if(n.length>0&&o.length>0){let s=n.reduce((l,c)=>(c.id&&(l[c.id]=c),l),{}),u=[];for(let l of o)l.id!==void 0&&s[l.id]?s[l.id]={...s[l.id],...l}:u.push(l);n=Object.values(s),o=u}let i={post:n,patch:o};if(!i.post.length&&!i.patch.length)return;let a={post:[],patch:[]};for(let s of["post","patch"]){let u=s,l=i[u].reverse(),c=l.pop();for(;c!==void 0;)a[u].push(c),c=l.pop()}(a.post.length>0||a.patch.length>0)&&await this._postBatchIngestRuns(hp(a))}async _postBatchIngestRuns(e){let r={...this.headers,"Content-Type":"application/json",Accept:"application/json"},n=await this.batchIngestCaller.call(Vt(this.debug),`${this.apiUrl}/runs/batch`,{method:"POST",headers:r,body:e,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(n,"batch create run",!0)}async multipartIngestRuns({runCreates:e,runUpdates:r}){if(e===void 0&&r===void 0)return;let n={},o=[];for(let c of e??[]){let d=await this.prepareRunCreateOrUpdateInputs(c);d.id!==void 0&&d.attachments!==void 0&&(n[d.id]=d.attachments),delete d.attachments,o.push(d)}let i=[];for(let c of r??[])i.push(await this.prepareRunCreateOrUpdateInputs(c));if(o.find(c=>c.trace_id===void 0||c.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(i.find(c=>c.trace_id===void 0||c.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(o.length>0&&i.length>0){let c=o.reduce((f,p)=>(p.id&&(f[p.id]=p),f),{}),d=[];for(let f of i)f.id!==void 0&&c[f.id]?c[f.id]={...c[f.id],...f}:d.push(f);o=Object.values(c),i=d}if(o.length===0&&i.length===0)return;let u=[],l=[];for(let[c,d]of[["post",o],["patch",i]])for(let f of d){let{inputs:p,outputs:m,events:h,attachments:b,...g}=f,y={inputs:p,outputs:m,events:h},S=hp(g);l.push({name:`${c}.${g.id}`,payload:new Blob([S],{type:`application/json; length=${S.length}`})});for(let[x,O]of Object.entries(y)){if(O===void 0)continue;let P=hp(O);l.push({name:`${c}.${g.id}.${x}`,payload:new Blob([P],{type:`application/json; length=${P.length}`})})}if(g.id!==void 0){let x=n[g.id];if(x){delete n[g.id];for(let[O,P]of Object.entries(x)){let E,A;if(Array.isArray(P)?[E,A]=P:(E=P.mimeType,A=P.data),O.includes(".")){console.warn(`Skipping attachment '${O}' for run ${g.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}l.push({name:`attachment.${g.id}.${O}`,payload:new Blob([A],{type:`${E}; length=${A.byteLength}`})})}}}u.push(`trace=${g.trace_id},id=${g.id}`)}await this._sendMultipartRequest(l,u.join("; "))}async _sendMultipartRequest(e,r){try{let n="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),o=[];for(let u of e)o.push(new Blob([`--${n}\r
`),r}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch{console.warn("[WARNING]: LangSmith failed to fetch info on supported operations. Falling back to batch operations and default limits.")}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();await this.drainAutoBatchQueue(e)}async createRun(e){if(!this._filterForSampling([e]).length)return;let r={...this.headers,"Content-Type":"application/json"},n=e.project_name;delete e.project_name;let o=await this.prepareRunCreateOrUpdateInputs({session_name:n,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&o.trace_id!==void 0&&o.dotted_order!==void 0){this.processRunOperation({action:"create",item:o}).catch(console.error);return}let i=o4e(o),a=await this.caller.call(Vt(this.debug),`${this.apiUrl}/runs`,{method:"POST",headers:r,body:hp(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(a,"create run",!0)}async batchIngestRuns({runCreates:e,runUpdates:r}){if(e===void 0&&r===void 0)return;let n=await Promise.all(e?.map(s=>this.prepareRunCreateOrUpdateInputs(s))??[]),o=await Promise.all(r?.map(s=>this.prepareRunCreateOrUpdateInputs(s))??[]);if(n.length>0&&o.length>0){let s=n.reduce((l,c)=>(c.id&&(l[c.id]=c),l),{}),u=[];for(let l of o)l.id!==void 0&&s[l.id]?s[l.id]={...s[l.id],...l}:u.push(l);n=Object.values(s),o=u}let i={post:n,patch:o};if(!i.post.length&&!i.patch.length)return;let a={post:[],patch:[]};for(let s of["post","patch"]){let u=s,l=i[u].reverse(),c=l.pop();for(;c!==void 0;)a[u].push(c),c=l.pop()}(a.post.length>0||a.patch.length>0)&&await this._postBatchIngestRuns(hp(a))}async _postBatchIngestRuns(e){let r={...this.headers,"Content-Type":"application/json",Accept:"application/json"},n=await this.batchIngestCaller.call(Vt(this.debug),`${this.apiUrl}/runs/batch`,{method:"POST",headers:r,body:e,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(n,"batch create run",!0)}async multipartIngestRuns({runCreates:e,runUpdates:r}){if(e===void 0&&r===void 0)return;let n={},o=[];for(let c of e??[]){let d=await this.prepareRunCreateOrUpdateInputs(c);d.id!==void 0&&d.attachments!==void 0&&(n[d.id]=d.attachments),delete d.attachments,o.push(d)}let i=[];for(let c of r??[])i.push(await this.prepareRunCreateOrUpdateInputs(c));if(o.find(c=>c.trace_id===void 0||c.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(i.find(c=>c.trace_id===void 0||c.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(o.length>0&&i.length>0){let c=o.reduce((f,p)=>(p.id&&(f[p.id]=p),f),{}),d=[];for(let f of i)f.id!==void 0&&c[f.id]?c[f.id]={...c[f.id],...f}:d.push(f);o=Object.values(c),i=d}if(o.length===0&&i.length===0)return;let u=[],l=[];for(let[c,d]of[["post",o],["patch",i]])for(let f of d){let{inputs:p,outputs:m,events:h,attachments:b,...g}=f,y={inputs:p,outputs:m,events:h},S=hp(g);l.push({name:`${c}.${g.id}`,payload:new Blob([S],{type:`application/json; length=${S.length}`})});for(let[x,O]of Object.entries(y)){if(O===void 0)continue;let P=hp(O);l.push({name:`${c}.${g.id}.${x}`,payload:new Blob([P],{type:`application/json; length=${P.length}`})})}if(g.id!==void 0){let x=n[g.id];if(x){delete n[g.id];for(let[O,P]of Object.entries(x)){let E,A;if(Array.isArray(P)?[E,A]=P:(E=P.mimeType,A=P.data),O.includes(".")){console.warn(`Skipping attachment '${O}' for run ${g.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}l.push({name:`attachment.${g.id}.${O}`,payload:new Blob([A],{type:`${E}; length=${A.byteLength}`})})}}}u.push(`trace=${g.trace_id},id=${g.id}`)}await this._sendMultipartRequest(l,u.join("; "))}async _sendMultipartRequest(e,r){try{let n="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),o=[];for(let u of e)o.push(new Blob([`--${n}\r
`])),o.push(new Blob([`Content-Disposition: form-data; name="${u.name}"\r
`,`Content-Type: ${u.payload.type}\r
\r
@@ -14,63 +14,63 @@ var Oer=Object.create;var u2=Object.defineProperty;var Per=Object.getOwnProperty
`]));o.push(new Blob([`--${n}--\r
`]));let a=await new Blob(o).arrayBuffer(),s=await this.batchIngestCaller.call(Vt(this.debug),`${this.apiUrl}/runs/multipart`,{method:"POST",headers:{...this.headers,"Content-Type":`multipart/form-data; boundary=${n}`},body:a,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(s,"ingest multipart runs",!0)}catch(n){console.warn(`${n.message.trim()}
Context: ${r}`)}}async updateRun(e,r){Kr(e),r.inputs&&(r.inputs=await this.processInputs(r.inputs)),r.outputs&&(r.outputs=await this.processOutputs(r.outputs));let n={...r,id:e};if(!this._filterForSampling([n],!0).length)return;if(this.autoBatchTracing&&n.trace_id!==void 0&&n.dotted_order!==void 0){if(r.end_time!==void 0&&n.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:n}).catch(console.error);return}else this.processRunOperation({action:"update",item:n}).catch(console.error);return}let o={...this.headers,"Content-Type":"application/json"},i=await this.caller.call(Vt(this.debug),`${this.apiUrl}/runs/${e}`,{method:"PATCH",headers:o,body:hp(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(i,"update run",!0)}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){Kr(e);let n=await this._get(`/runs/${e}`);return r&&n.child_run_ids&&(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:pp("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 fir(this.listRuns({id:e.child_run_ids})),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.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:b,limit:g,select:y}=e,S=[];if(r&&(S=Array.isArray(r)?r:[r]),n){let E=Array.isArray(n)?n:[n],A=await Promise.all(E.map(I=>this.readProject({projectName:I}).then(R=>R.id)));S.push(...A)}let x=["app_path","child_run_ids","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:S.length?S:null,run_type:c,reference_example:a,query:p,filter:m,trace_filter:h,tree_filter:b,execution_order:u,parent_run:o,start_time:s?s.toISOString():null,error:d,id:f,limit:g,trace:i,select:y||x,is_root:l},P=0;for await(let E of this._getCursorPaginatedList("/runs/query",O))if(g){if(P>=g)break;if(E.length+P>g){yield*E.slice(0,g-P);break}P+=E.length,yield*E}else yield*E}async getRunStats({id:e,trace:r,parentRun:n,runType:o,projectNames:i,projectIds:a,referenceExampleIds:s,startTime:u,endTime:l,error:c,query:d,filter:f,traceFilter:p,treeFilter:m,isRoot:h,dataSourceType:b}){let g=a||[];i&&(g=[...a||[],...await Promise.all(i.map(P=>this.readProject({projectName:P}).then(E=>E.id)))]);let S=Object.fromEntries(Object.entries({id:e,trace:r,parent_run:n,run_type:o,session:g,reference_example:s,start_time:u,end_time:l,error:c,query:d,filter:f,trace_filter:p,tree_filter:m,is_root:h,data_source_type:b}).filter(([P,E])=>E!==void 0));return await(await this.caller.call(Vt(this.debug),`${this.apiUrl}/runs/stats`,{method:"POST",headers:this.headers,body:JSON.stringify(S),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json()}async shareRun(e,{shareId:r}={}){let n={run_id:e,share_token:r||as()};Kr(e);let i=await(await this.caller.call(Vt(this.debug),`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(n),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json();if(i===null||!("share_token"in i))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${i.share_token}/r`}async unshareRun(e){Kr(e);let r=await this.caller.call(Vt(this.debug),`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(r,"unshare run",!0)}async readRunSharedLink(e){Kr(e);let n=await(await this.caller.call(Vt(this.debug),`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json();if(!(n===null||!("share_token"in n)))return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(e,{runIds:r}={}){let n=new URLSearchParams({share_token:e});if(r!==void Line truncated
Context: ${r}`)}}async updateRun(e,r){Kr(e),r.inputs&&(r.inputs=await this.processInputs(r.inputs)),r.outputs&&(r.outputs=await this.processOutputs(r.outputs));let n={...r,id:e};if(!this._filterForSampling([n],!0).length)return;if(this.autoBatchTracing&&n.trace_id!==void 0&&n.dotted_order!==void 0){if(r.end_time!==void 0&&n.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:n}).catch(console.error);return}else this.processRunOperation({action:"update",item:n}).catch(console.error);return}let o={...this.headers,"Content-Type":"application/json"},i=await this.caller.call(Vt(this.debug),`${this.apiUrl}/runs/${e}`,{method:"PATCH",headers:o,body:hp(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(i,"update run",!0)}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){Kr(e);let n=await this._get(`/runs/${e}`);return r&&n.child_run_ids&&(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:pp("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 yir(this.listRuns({id:e.child_run_ids})),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.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:b,limit:g,select:y}=e,S=[];if(r&&(S=Array.isArray(r)?r:[r]),n){let E=Array.isArray(n)?n:[n],A=await Promise.all(E.map(I=>this.readProject({projectName:I}).then(R=>R.id)));S.push(...A)}let x=["app_path","child_run_ids","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:S.length?S:null,run_type:c,reference_example:a,query:p,filter:m,trace_filter:h,tree_filter:b,execution_order:u,parent_run:o,start_time:s?s.toISOString():null,error:d,id:f,limit:g,trace:i,select:y||x,is_root:l},P=0;for await(let E of this._getCursorPaginatedList("/runs/query",O))if(g){if(P>=g)break;if(E.length+P>g){yield*E.slice(0,g-P);break}P+=E.length,yield*E}else yield*E}async getRunStats({id:e,trace:r,parentRun:n,runType:o,projectNames:i,projectIds:a,referenceExampleIds:s,startTime:u,endTime:l,error:c,query:d,filter:f,traceFilter:p,treeFilter:m,isRoot:h,dataSourceType:b}){let g=a||[];i&&(g=[...a||[],...await Promise.all(i.map(P=>this.readProject({projectName:P}).then(E=>E.id)))]);let S=Object.fromEntries(Object.entries({id:e,trace:r,parent_run:n,run_type:o,session:g,reference_example:s,start_time:u,end_time:l,error:c,query:d,filter:f,trace_filter:p,tree_filter:m,is_root:h,data_source_type:b}).filter(([P,E])=>E!==void 0));return await(await this.caller.call(Vt(this.debug),`${this.apiUrl}/runs/stats`,{method:"POST",headers:this.headers,body:JSON.stringify(S),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json()}async shareRun(e,{shareId:r}={}){let n={run_id:e,share_token:r||as()};Kr(e);let i=await(await this.caller.call(Vt(this.debug),`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(n),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json();if(i===null||!("share_token"in i))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${i.share_token}/r`}async unshareRun(e){Kr(e);let r=await this.caller.call(Vt(this.debug),`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(r,"unshare run",!0)}async readRunSharedLink(e){Kr(e);let n=await(await this.caller.call(Vt(this.debug),`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json();if(!(n===null||!("share_token"in n)))return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(e,{runIds:r}={}){let n=new URLSearchParams({share_token:e});if(r!==void Line truncated
Status: ${i.status}
Message: ${a.detail.join(`
`)}`):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=await this.caller.call(Vt(this.debug),u,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(c),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await sn(d,"create project"),await d.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={name:r,extra:u,description:n,end_time:a?new Date(a).toISOString():null},c=await this.caller.call(Vt(this.debug),s,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await sn(c,"update project"),await c.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)Kr(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(Vt(this.debug),`${this.apiUrl}${n}?${o}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});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)Kr(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,referenceFree:a,metadata:s}={}){let u=new URLSearchParams;if(e!==void 0)for(let l of e)u.append("id",l);if(r!==void 0&&u.append("name",r),n!==void 0&&u.append("name_contains",n),o!==void 0)u.append("reference_dataset",o);else if(i!==void 0){let l=await this.readDataset({datasetName:i});u.append("reference_dataset",l.id)}a!==void 0&&u.append("reference_free",a.toString()),s!==void 0&&u.append("metadata",JSON.stringify(s));for await(let l of this._getPaginated("/sessions",u))yield*l}async deleteProject({projectId:e,projectName:r}){let n;if(e===void 0&&r===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?n=(await this.readProject({projectName:r})).id:n=e,Kr(n);let o=await this.caller.call(Vt(this.debug),`${this.apiUrl}/sessions/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(o,`delete session ${n} (${r})`,!0)}async uploadCsv({csvFile:e,fileName:r,inputKeys:n,outputKeys:o,description:i,dataType:a,name:s}){let u=`${this.apiUrl}/datasets/upload`,l=new FormData;l.append("file",e,r),n.forEach(f=>{l.append("input_keys",f)}),o.forEach(f=>{l.append("output_keys",f)}),i&&l.append("description",i),a&&l.append("data_type",a),s&&l.append("name",s);let c=await this.caller.call(Vt(this.debug),u,{method:"POST",headers:this.headers,body:l,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await sn(c,"upload CSV"),await c.json()}async createDataset(e,{description:r,dataType:n,inputsSchema:o,outputsSchema:i,metadata:a}={}){let s={name:e,description:r,extra:a?{metadata:a}:void 0};n&&(s.data_type=n),o&&(s.inputs_schema_definition=o),i&&(s.outputLine truncated
`).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;Kr(i);let a=await this.caller.call(Vt(this.debug),`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await sn(a,"update dataset"),await a.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;Kr(a);let s=await this.caller.call(Vt(this.debug),`${this.apiUrl}/datasets/${a}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({as_of:typeof o=="string"?o:o.toISOString(),tag:i}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(s,"update dataset tags")}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)Kr(o),n+=`/${o}`;else throw new Error("Must provide datasetName or datasetId");let i=await this.caller.call(Vt(this.debug),this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(i,`delete ${n}`),await i.json()}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),Kr(o);let i={tag:n},a=await this.caller.call(Vt(this.debug),`${this.apiUrl}/datasets/${o}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(a,"index dataset"),await a.json()}async similarExamples(e,r,n,{filter:o}={}){let i={limit:n,inputs:e};o!==void 0&&(i.filter=o),Kr(r);let a=await this.caller.call(Vt(this.debug),`${this.apiUrl}/datasets/${r}/search`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await sn(a,"fetch similar examples"),(await a.json()).examples}async createExample(e,r,n){if(o4e(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;o4e(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]??as())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let y=e,S=y[0].dataset_id,x=y[0].dataset_name;if(S===void 0&&x===void 0)throw new Error("Must provide either datasetName or datasetId");if(S!==void 0&&x!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");S===void 0&&(S=(await this.readDataset({datasetName:x})).id);let O=await this._uploadExamplesMultipart(S,y);return await Promise.all(O.example_ids.map(E=>this.readExample(E)))}let{inputs:r,outputs:n,metadata:o,splits:i,sourceRunIds:a,useSourceRunIOs:s,useSourceRunAttachments:u,attachments:l,exampleIds:c,datasetId:d,datasetName:f}=e;if(r===void 0)throw new Error("Must provide inputs when using legacy parameters");let p=d,m=f;if(p===void 0&&m===void 0)throw new Error("Must provide either datasetName or datasetId");if(p!==void 0&&m!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");p===void 0&&(p=(await this.readDataset({datasetName:m})).id);let h=r.map((y,S)=>({dataset_id:p,inputs:y,outputs:n?.[S],metadata:o?.[S],split:i?.[S],id:c?.[S],attachments:l?.[S],source_run_id:a?.[S],use_source_run_io:s?.[S Line truncated
`).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;Kr(i);let a=await this.caller.call(Vt(this.debug),`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await sn(a,"update dataset"),await a.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;Kr(a);let s=await this.caller.call(Vt(this.debug),`${this.apiUrl}/datasets/${a}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({as_of:typeof o=="string"?o:o.toISOString(),tag:i}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(s,"update dataset tags")}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)Kr(o),n+=`/${o}`;else throw new Error("Must provide datasetName or datasetId");let i=await this.caller.call(Vt(this.debug),this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(i,`delete ${n}`),await i.json()}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),Kr(o);let i={tag:n},a=await this.caller.call(Vt(this.debug),`${this.apiUrl}/datasets/${o}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(a,"index dataset"),await a.json()}async similarExamples(e,r,n,{filter:o}={}){let i={limit:n,inputs:e};o!==void 0&&(i.filter=o),Kr(r);let a=await this.caller.call(Vt(this.debug),`${this.apiUrl}/datasets/${r}/search`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await sn(a,"fetch similar examples"),(await a.json()).examples}async createExample(e,r,n){if(a4e(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;a4e(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]??as())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let y=e,S=y[0].dataset_id,x=y[0].dataset_name;if(S===void 0&&x===void 0)throw new Error("Must provide either datasetName or datasetId");if(S!==void 0&&x!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");S===void 0&&(S=(await this.readDataset({datasetName:x})).id);let O=await this._uploadExamplesMultipart(S,y);return await Promise.all(O.example_ids.map(E=>this.readExample(E)))}let{inputs:r,outputs:n,metadata:o,splits:i,sourceRunIds:a,useSourceRunIOs:s,useSourceRunAttachments:u,attachments:l,exampleIds:c,datasetId:d,datasetName:f}=e;if(r===void 0)throw new Error("Must provide inputs when using legacy parameters");let p=d,m=f;if(p===void 0&&m===void 0)throw new Error("Must provide either datasetName or datasetId");if(p!==void 0&&m!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");p===void 0&&(p=(await this.readDataset({datasetName:m})).id);let h=r.map((y,S)=>({dataset_id:p,inputs:y,outputs:n?.[S],metadata:o?.[S],split:i?.[S],id:c?.[S],attachments:l?.[S],source_run_id:a?.[S],use_source_run_io:s?.[S Line truncated
Current tenant: ${n.tenant_handle}
Requested tenant: ${r}`)}async _getLatestCommitHash(e){let r=await this.caller.call(Vt(this.debug),`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),n=await r.json();if(!r.ok){let o=typeof n.detail=="string"?n.detail:JSON.stringify(n.detail),i=new Error(`Error ${r.status}: ${r.statusText}
${o}`);throw i.statusCode=r.status,i}if(n.commits.length!==0)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(e,r){let[n,o,i]=xC(e),a=await this.caller.call(Vt(this.debug),`${this.apiUrl}/likes/${n}/${o}`,{method:"POST",body:JSON.stringify({like:r}),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await sn(a,`${r?"like":"unlike"} prompt`),await a.json()}async _getPromptUrl(e){let[r,n,o]=xC(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]=xC(e),i=await this.caller.call(Vt(this.debug),`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(i.status===404)return null;await sn(i,"get prompt");let a=await i.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
${o}`);throw i.statusCode=r.status,i}if(n.commits.length!==0)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(e,r){let[n,o,i]=CC(e),a=await this.caller.call(Vt(this.debug),`${this.apiUrl}/likes/${n}/${o}`,{method:"POST",body:JSON.stringify({like:r}),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await sn(a,`${r?"like":"unlike"} prompt`),await a.json()}async _getPromptUrl(e){let[r,n,o]=CC(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]=CC(e),i=await this.caller.call(Vt(this.debug),`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(i.status===404)return null;await sn(i,"get prompt");let a=await i.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]=xC(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=await this.caller.call(Vt(this.debug),`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(u,"create prompt");let{repo:l}=await u.json();return l}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]=xC(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=await this.caller.call(Vt(this.debug),`${this.apiUrl}/commits/${o}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(u),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(l,"create commit");let c=await l.json();return this._getPromptUrl(`${o}/${i}${c.commit_hash?`:${c.commit_hash}`:""}`)}async updateExamplesMultipart(e,r=[]){return this._updateExamplesMultipart(e,r)}async _updateExamplesMultipart(e,r=[]){if(!await this._getMultiPartSupport())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 s of r){let u=s.id,l={...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split}},c=hp(l),d=new Blob([c],{type:"application/json"});if(n.append(u,d),s.inputs){let f=hp(s.inputs),p=new Blob([f],{type:"application/json"});n.append(`${u}.inputs`,p)}if(s.outputs){let f=hp(s.outputs),p=new Blob([f],{type:"application/json"});n.append(`${u}.outputs`,p)}if(s.attachments)for(let[f,p]of Object.entries(s.attachments)){let m,h;Array.isArray(p)?[m,h]=p:(m=p.mimeType,h=p.data);let b=new Blob([h],{type:`${m}; length=${h.byteLength}`});n.append(`${u}.attachment.${f}`,b)}if(s.attachments_operations){let f=hp(s.attachments_operations),p=new Blob([f],{type:"application/json"});n.append(`${u}.attachments_operations`,p)}}let o=e??r[0]?.dataset_id;return await(await this.caller.call(Vt(this.debug),`${this.apiUrl}/v1/platform/datasets/${o}/examples`,{method:"PATCH",headers:this.headers,body:n})).json()}async uploadExamplesMultipart(e,r=[]){return this._uploadExamplesMultipart(e,r)}async _uploadExamplesMultipart(e,r=[]){if(!await this._getMultiPartSupport())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??as()).toString(),u={created_at:a.created_at,...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split},...a.source_run_id&&{source_run_id:a.source_run_id},...a.use_source_run_io&&{use_source_run_io:a.use_source_run_io},...a.use_source_run_attachments&&{use_source_run_attachments:a.use_source_run_attachments}},l=hp(u),c=new Blob([l],{type:"application/json"});if(n.append(s,c),a.inputs){let d=hp(a.inputs),f=new Blob([d],{type:"application/json"});n.append(`${s}.inputs`,f)}if(a.outputs){let d=hp(a.outputs),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)}}let o=await this.caller.call(Vt(this.debug),`${this.apiUrl}/v1/platform/datasets/${e}/examples`,{method:"POST",headers:this.headers,body:n});return await sn(o,"upload examples"),await o.json()}async updatePrompt(e,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[n,o]=xC(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);let i={};if(r?.description!==void 0&&(i.description=r.description),r?.readme!==void 0&&(i.readme=r.readme),r?.tags!==void 0&&(i.tags=r.tags),r?.isPublic!==void 0&&(i.is_public=r.isPublic),r?.isArchived!==void 0&&(i.is_archived=r.isArchived),Object.keys(i).length===0)throw new Error("No valid update options provided");let a=await this.caller.call(Vt(this.debug),`${this.apiUrl}/repos/${n}/${o}`,{method:"PATCH",body:JSON.stringify(i),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await sn(a,"update prompt"),a.json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[r,n,o]=xC(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete a prompt",r);return await(await this.caller.call(Vt(thi Line truncated
`));return t},uNn=Symbol.for("langsmith:traceable:root")});var Kpe=w(()=>{p4e()});function iG(t,e){return Air.call(t,e)}function aG(t){if(Array.isArray(t)){let r=new Array(t.length);for(let n=0;n<r.length;n++)r[n]=""+n;return r}if(Object.keys)return Object.keys(t);let e=[];for(let r in t)iG(t,r)&&e.push(r);return e}function Md(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function sG(t){let e=0,r=t.length,n;for(;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}function zb(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function O2(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function oG(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if(oG(t[r]))return!0}else if(typeof t=="object"){let r=aG(t),n=r.length;for(var e=0;e<n;e++)if(oG(t[r[e]]))return!0}}return!1}function m4e(t,e){let r=[t];for(let n in e){let o=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof o<"u"&&r.push(`${n}: ${o}`)}return r.join(`
`)}var Air,hR,P2=w(()=>{Air=Object.prototype.hasOwnProperty;hR=class extends Error{constructor(e,r,n,o,i){super(m4e(e,{name:r,index:n,operation:o,tree:i})),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:o}),Object.defineProperty(this,"tree",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.setPrototypeOf(this,new.target.prototype),this.message=m4e(e,{name:r,index:n,operation:o,tree:i})}}});var Gpe={};Cf(Gpe,{JsonPatchError:()=>ss,_areEquals:()=>E2,applyOperation:()=>gR,applyPatch:()=>AE,applyReducer:()=>Rir,deepClone:()=>Iir,getValueByPointer:()=>uG,validate:()=>h4e,validator:()=>lG});function uG(t,e){if(e=="")return t;var r={op:"_get",path:e};return gR(t,r),r.value}function gR(t,e,r=!1,n=!0,o=!0,i=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):lG(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=uG(t,e.from),e.op==="move"&&(a.removed=t),a;if(e.op==="test"){if(a.test=E2(t,e.value),a.test===!1)throw new ss("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 ss("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return a}}else{n||(t=Md(t));let s=(e.path||"").split("/"),u=t,l=1,c=s.length,d,f,p;for(typeof r=="function"?p=r:p=lG;;){if(f=s[l],f&&f.indexOf("~")!=-1&&(f=O2(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&&!sG(f))throw new ss("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);sG(f)&&(f=~~f)}if(l>=c){if(r&&e.op==="add"&&f>u.length)throw new ss("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=Mir[e.op].call(e,u,f,t);if(m.test===!1)throw new ss("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return m}}else if(l>=c){let m=HL[e.op].call(e,u,f,t);if(m.test===!1)throw new ss("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return m}if(u=u[f],r&&l<c&&(!u||typeof u!="object"))throw new ss("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function AE(t,e,r,n=!0,o=!0){if(r&&!Array.isArray(e))throw new ss("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=Md(t));let i=new Array(e.length);for(let a=0,s=e.length;a<s;a++)i[a]=gR(t,e[a],r,!0,o,a),t=i[a].newDocument;return i.newDocument=t,i}function Rir(t,e,r){let n=gR(t,e);if(n.test===!1)throw new ss("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function lG(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new ss("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(HL[t.op]){if(typeof t.path!="string")throw new ss("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new ss('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 ss("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 ss("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")&&oG(t.value))throw new ss("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 ss("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,r)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==n)throw new ss("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,r)}else if(t.op==="move"||t.op==="copy"){var a={op:"_get",path:t.from,value:void 0},s=h4e([a],r);if(s&&s.name==="OPERATION_PATH_UNRESOLVABLE")throw new ss(" Line truncated
https://smith.langchain.com/prompts`);let[o,i,a]=CC(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=await this.caller.call(Vt(this.debug),`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(u,"create prompt");let{repo:l}=await u.json();return l}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]=CC(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=await this.caller.call(Vt(this.debug),`${this.apiUrl}/commits/${o}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(u),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(l,"create commit");let c=await l.json();return this._getPromptUrl(`${o}/${i}${c.commit_hash?`:${c.commit_hash}`:""}`)}async updateExamplesMultipart(e,r=[]){return this._updateExamplesMultipart(e,r)}async _updateExamplesMultipart(e,r=[]){if(!await this._getMultiPartSupport())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 s of r){let u=s.id,l={...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split}},c=hp(l),d=new Blob([c],{type:"application/json"});if(n.append(u,d),s.inputs){let f=hp(s.inputs),p=new Blob([f],{type:"application/json"});n.append(`${u}.inputs`,p)}if(s.outputs){let f=hp(s.outputs),p=new Blob([f],{type:"application/json"});n.append(`${u}.outputs`,p)}if(s.attachments)for(let[f,p]of Object.entries(s.attachments)){let m,h;Array.isArray(p)?[m,h]=p:(m=p.mimeType,h=p.data);let b=new Blob([h],{type:`${m}; length=${h.byteLength}`});n.append(`${u}.attachment.${f}`,b)}if(s.attachments_operations){let f=hp(s.attachments_operations),p=new Blob([f],{type:"application/json"});n.append(`${u}.attachments_operations`,p)}}let o=e??r[0]?.dataset_id;return await(await this.caller.call(Vt(this.debug),`${this.apiUrl}/v1/platform/datasets/${o}/examples`,{method:"PATCH",headers:this.headers,body:n})).json()}async uploadExamplesMultipart(e,r=[]){return this._uploadExamplesMultipart(e,r)}async _uploadExamplesMultipart(e,r=[]){if(!await this._getMultiPartSupport())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??as()).toString(),u={created_at:a.created_at,...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split},...a.source_run_id&&{source_run_id:a.source_run_id},...a.use_source_run_io&&{use_source_run_io:a.use_source_run_io},...a.use_source_run_attachments&&{use_source_run_attachments:a.use_source_run_attachments}},l=hp(u),c=new Blob([l],{type:"application/json"});if(n.append(s,c),a.inputs){let d=hp(a.inputs),f=new Blob([d],{type:"application/json"});n.append(`${s}.inputs`,f)}if(a.outputs){let d=hp(a.outputs),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)}}let o=await this.caller.call(Vt(this.debug),`${this.apiUrl}/v1/platform/datasets/${e}/examples`,{method:"POST",headers:this.headers,body:n});return await sn(o,"upload examples"),await o.json()}async updatePrompt(e,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[n,o]=CC(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);let i={};if(r?.description!==void 0&&(i.description=r.description),r?.readme!==void 0&&(i.readme=r.readme),r?.tags!==void 0&&(i.tags=r.tags),r?.isPublic!==void 0&&(i.is_public=r.isPublic),r?.isArchived!==void 0&&(i.is_archived=r.isArchived),Object.keys(i).length===0)throw new Error("No valid update options provided");let a=await this.caller.call(Vt(this.debug),`${this.apiUrl}/repos/${n}/${o}`,{method:"PATCH",body:JSON.stringify(i),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await sn(a,"update prompt"),a.json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[r,n,o]=CC(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete a prompt",r);return await(await this.caller.call(Vt(thi Line truncated
`));return t},pNn=Symbol.for("langsmith:traceable:root")});var Ype=w(()=>{h4e()});function aG(t,e){return Nir.call(t,e)}function sG(t){if(Array.isArray(t)){let r=new Array(t.length);for(let n=0;n<r.length;n++)r[n]=""+n;return r}if(Object.keys)return Object.keys(t);let e=[];for(let r in t)aG(t,r)&&e.push(r);return e}function Md(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function uG(t){let e=0,r=t.length,n;for(;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}function zb(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function P2(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function iG(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if(iG(t[r]))return!0}else if(typeof t=="object"){let r=sG(t),n=r.length;for(var e=0;e<n;e++)if(iG(t[r[e]]))return!0}}return!1}function g4e(t,e){let r=[t];for(let n in e){let o=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof o<"u"&&r.push(`${n}: ${o}`)}return r.join(`
`)}var Nir,hR,E2=w(()=>{Nir=Object.prototype.hasOwnProperty;hR=class extends Error{constructor(e,r,n,o,i){super(g4e(e,{name:r,index:n,operation:o,tree:i})),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:o}),Object.defineProperty(this,"tree",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.setPrototypeOf(this,new.target.prototype),this.message=g4e(e,{name:r,index:n,operation:o,tree:i})}}});var Zpe={};Cf(Zpe,{JsonPatchError:()=>ss,_areEquals:()=>T2,applyOperation:()=>gR,applyPatch:()=>AE,applyReducer:()=>Fir,deepClone:()=>Dir,getValueByPointer:()=>lG,validate:()=>y4e,validator:()=>cG});function lG(t,e){if(e=="")return t;var r={op:"_get",path:e};return gR(t,r),r.value}function gR(t,e,r=!1,n=!0,o=!0,i=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):cG(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=lG(t,e.from),e.op==="move"&&(a.removed=t),a;if(e.op==="test"){if(a.test=T2(t,e.value),a.test===!1)throw new ss("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 ss("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return a}}else{n||(t=Md(t));let s=(e.path||"").split("/"),u=t,l=1,c=s.length,d,f,p;for(typeof r=="function"?p=r:p=cG;;){if(f=s[l],f&&f.indexOf("~")!=-1&&(f=P2(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&&!uG(f))throw new ss("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);uG(f)&&(f=~~f)}if(l>=c){if(r&&e.op==="add"&&f>u.length)throw new ss("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=Lir[e.op].call(e,u,f,t);if(m.test===!1)throw new ss("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return m}}else if(l>=c){let m=VL[e.op].call(e,u,f,t);if(m.test===!1)throw new ss("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return m}if(u=u[f],r&&l<c&&(!u||typeof u!="object"))throw new ss("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function AE(t,e,r,n=!0,o=!0){if(r&&!Array.isArray(e))throw new ss("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=Md(t));let i=new Array(e.length);for(let a=0,s=e.length;a<s;a++)i[a]=gR(t,e[a],r,!0,o,a),t=i[a].newDocument;return i.newDocument=t,i}function Fir(t,e,r){let n=gR(t,e);if(n.test===!1)throw new ss("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function cG(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new ss("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(VL[t.op]){if(typeof t.path!="string")throw new ss("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new ss('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 ss("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 ss("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")&&iG(t.value))throw new ss("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 ss("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,r)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==n)throw new ss("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,r)}else if(t.op==="move"||t.op==="copy"){var a={op:"_get",path:t.from,value:void 0},s=y4e([a],r);if(s&&s.name==="OPERATION_PATH_UNRESOLVABLE")throw new ss(" Line truncated
${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,r){e.child_runs.push(r)}_addRunToRunMap(e){let r=Wir(e.start_time,e.id,e.execution_order),n={...e};if(n.parent_run_id!==void 0){let o=this.runMap.get(n.parent_run_id);o&&(this._addChildRun(o,n),o.child_execution_order=Math.max(o.child_execution_order,n.child_execution_order),n.trace_id=o.trace_id,o.dotted_order!==void 0&&(n.dotted_order=[o.dotted_order,r].join(".")))}else n.trace_id=n.id,n.dotted_order=r;return this.runMap.set(n.id,n),n}async _endTrace(e){let r=e.parent_run_id!==void 0&&this.runMap.get(e.parent_run_id);r?r.child_execution_order=Math.max(r.child_execution_order,e.child_execution_order):await this.persistRun(e),this.runMap.delete(e.id),await this.onRunUpdate?.(e)}_getExecutionOrder(e){let r=e!==void 0&&this.runMap.get(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.runMap.get(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.runMap.get(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.runMap.get(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.runMap.get(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.runMap.get(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.runMap.get(r);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.outputs=rme(e,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=rme(i.inputs,"input")),await this.onChainEnd?.(a),await this._endTrace(a),a}async handleChainError(e,r,n,o,i){let a=this.runMap.get(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=rme(i.inputs,"input")),await this.onChainError?.(a),await this._endTrace(a),a}_createRunForToolStart(e,r,n,o,i,a,s){let u=this._getExecutionOrder(o),l=Date.now(),c={id:n,name:s??e.id[e.id.length-1],parent_run_id:o,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{input:r},execution_order:u,child_execution_order:u,run_type:"tool",child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(c)}async handleToolStart(e,r,n,o,i,a,s){let u=this.runMap.get(n)??this._createRunForToolStart(e,r,n,o,i,a,s);return await this.onRunCreate?.(u),await this.onToolStart?.(u),u}async handleToolEnd(e,r){let n=this.runMap.get(r);if(!n||n?.run_type!=="tool")throw new Error("No tool run to end");return n.end_time=Date.now(),n.outputs={output:e},n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await this.onToolEnd?.(n),await this._endTrace(n),n}async handleToolError(e,r){let n=this.runMap.get(r);if(!n||n?.run_type!=="tool")throw new Error("No tool run to end");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await this.onToolError?.(n),await this._endTrace(n),n}async handleAgentAction(e, Line truncated
${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,r){e.child_runs.push(r)}_addRunToRunMap(e){let r=Zir(e.start_time,e.id,e.execution_order),n={...e};if(n.parent_run_id!==void 0){let o=this.runMap.get(n.parent_run_id);o&&(this._addChildRun(o,n),o.child_execution_order=Math.max(o.child_execution_order,n.child_execution_order),n.trace_id=o.trace_id,o.dotted_order!==void 0&&(n.dotted_order=[o.dotted_order,r].join(".")))}else n.trace_id=n.id,n.dotted_order=r;return this.runMap.set(n.id,n),n}async _endTrace(e){let r=e.parent_run_id!==void 0&&this.runMap.get(e.parent_run_id);r?r.child_execution_order=Math.max(r.child_execution_order,e.child_execution_order):await this.persistRun(e),this.runMap.delete(e.id),await this.onRunUpdate?.(e)}_getExecutionOrder(e){let r=e!==void 0&&this.runMap.get(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.runMap.get(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.runMap.get(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.runMap.get(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.runMap.get(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.runMap.get(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.runMap.get(r);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.outputs=ime(e,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=ime(i.inputs,"input")),await this.onChainEnd?.(a),await this._endTrace(a),a}async handleChainError(e,r,n,o,i){let a=this.runMap.get(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=ime(i.inputs,"input")),await this.onChainError?.(a),await this._endTrace(a),a}_createRunForToolStart(e,r,n,o,i,a,s){let u=this._getExecutionOrder(o),l=Date.now(),c={id:n,name:s??e.id[e.id.length-1],parent_run_id:o,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{input:r},execution_order:u,child_execution_order:u,run_type:"tool",child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(c)}async handleToolStart(e,r,n,o,i,a,s){let u=this.runMap.get(n)??this._createRunForToolStart(e,r,n,o,i,a,s);return await this.onRunCreate?.(u),await this.onToolStart?.(u),u}async handleToolEnd(e,r){let n=this.runMap.get(r);if(!n||n?.run_type!=="tool")throw new Error("No tool run to end");return n.end_time=Date.now(),n.outputs={output:e},n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await this.onToolEnd?.(n),await this._endTrace(n),n}async handleToolError(e,r){let n=this.runMap.get(r);if(!n||n?.run_type!=="tool")throw new Error("No tool run to end");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await this.onToolError?.(n),await this._endTrace(n),n}async handleAgentAction(e, Line truncated
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
`,t}var I2=w(()=>{});function RE(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="tool_call")}function B4e(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 wR,pG=w(()=>{wR=class extends Error{constructor(e,r){super(e),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.output=r}}});function ome(t,e=WL){t=t.trim();let r=t.indexOf("```");if(r===-1)return e(t);let n=t.substring(r+3);n.startsWith(`json
`,t}var M2=w(()=>{});function RE(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="tool_call")}function U4e(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 wR,mG=w(()=>{wR=class extends Error{constructor(e,r){super(e),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.output=r}}});function sme(t,e=KL){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 WL(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 ime=w(()=>{});function jE(t){return typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"&&"source_type"in t&&(t.source_type==="url"||t.source_type==="base64"||t.source_type==="text"||t.source_type==="id")}function q4e(t){return jE(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}function U4e(t){return jE(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}function z4e(t){if(jE(t)){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url}};if(t.source_type==="base64"){if(!t.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${t.mime_type};base64,${t.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function ame({dataUrl:t,asTypedArray:e=!1}){let r=t.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),n;if(r){n=r[1].toLowerCase();let o=e?Uint8Array.from(atob(r[2]),i=>i.charCodeAt(0)):r[2];return{mime_type:n,data:o}}}function H4e(t,e){if(t.type==="text"){if(!e.fromStandardTextBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardTextBlock\` method.`);return e.fromStandardTextBlock(t)}if(t.type==="image"){if(!e.fromStandardImageBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardImageBlock\` method.`);return e.fromStandardImageBlock(t)}if(t.type==="audio"){if(!e.fromStandardAudioBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardAudioBlock\` method.`);return e.fromStandardAudioBlock(t)}if(t.type==="file"){if(!e.fromStandardFileBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardFileBlock\` method.`);return e.fromStandardFileBlock(t)}throw new Error(`Unable to convert content block type '${t.type}' to provider-specific format: not recognized.`)}var sme=w(()=>{});function Oh(t,e){return typeof t=="string"?t===""?e:typeof e=="string"?t+e:Array.isArray(e)&&e.some(r=>jE(r))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e]:Array.isArray(e)?M2(t,e)??[...t,...e]:e===""?t:Array.isArray(t)&&t.some(r=>jE(r))?[...t,{type:"file",source_type:"text",text:e}]:[...t,{type:"text",text:e}]}function V4e(t,e){return t==="error"||e==="error"?"error":"success"}function Gir(t,e){function r(n,o){if(typeof n!="object"||n===null||n===void 0)return n;if(o>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(a=>r(a,o+1));let i={};for(let a of Object.keys(n))i[a]=r(n[a],o+1);return i}return JSON.stringify(r(t,0),null,2)}function xs(t,e){let r={...t};for(let[n,o]of Object.entries(e))if(r[n]==null)r[n]=o;else{if(o==null)continue;if(typeof r[n]!=typeof o||Array.isArray(r[n])!==Array.isArray(o))throw new Error(`field[${n}] already exists in the message chunk, but with a different type.`);if(typeof r[n]=="string"){if(n==="type")continue;r[n]+=o}else if(typeof r[n]=="object"&&!Array.isArray(r[n]))r[n]=xs(r[n],o);else if(Array.isArray(r[n]))r[n]=M2(r[n],o);else{if(r[n]===o)continue;console.warn(`field[${n}] already exists in this message chunk and value has unsupported type.`)}}return r}function M2(t,e){if(!(t===void 0&&e===void 0)){if(t===void 0||e===void 0)return t||e;{let r=[...t];for(let n of e)if(typeof n=="object"&&"index"in n&&typeof n.index=="number"){let o=r.findIndex(i=>i.index===n.index);o!==-1?r[o]=xs(r[o],n):r.push(n)}else{if(typeof n=="object"&&"text"in n&&n.text==="")continue;r.push(n)}return r}}}function W4e(t,e){if(!t&&!e)throw new Error("Cannot merge two undefined objects.");if(!t||!e)return t||e;if(typeof t!=typeof e)throw new Error(`Cannot merge objects of different types.
`)&&(n=n.substring(1));let o=n.indexOf("```"),i=n;return o!==-1&&(i=n.substring(0,o)),e(i.trim())}function KL(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 ume=w(()=>{});function jE(t){return typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"&&"source_type"in t&&(t.source_type==="url"||t.source_type==="base64"||t.source_type==="text"||t.source_type==="id")}function z4e(t){return jE(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}function H4e(t){return jE(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}function V4e(t){if(jE(t)){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url}};if(t.source_type==="base64"){if(!t.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${t.mime_type};base64,${t.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function lme({dataUrl:t,asTypedArray:e=!1}){let r=t.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),n;if(r){n=r[1].toLowerCase();let o=e?Uint8Array.from(atob(r[2]),i=>i.charCodeAt(0)):r[2];return{mime_type:n,data:o}}}function W4e(t,e){if(t.type==="text"){if(!e.fromStandardTextBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardTextBlock\` method.`);return e.fromStandardTextBlock(t)}if(t.type==="image"){if(!e.fromStandardImageBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardImageBlock\` method.`);return e.fromStandardImageBlock(t)}if(t.type==="audio"){if(!e.fromStandardAudioBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardAudioBlock\` method.`);return e.fromStandardAudioBlock(t)}if(t.type==="file"){if(!e.fromStandardFileBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardFileBlock\` method.`);return e.fromStandardFileBlock(t)}throw new Error(`Unable to convert content block type '${t.type}' to provider-specific format: not recognized.`)}var cme=w(()=>{});function Oh(t,e){return typeof t=="string"?t===""?e:typeof e=="string"?t+e:Array.isArray(e)&&e.some(r=>jE(r))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e]:Array.isArray(e)?R2(t,e)??[...t,...e]:e===""?t:Array.isArray(t)&&t.some(r=>jE(r))?[...t,{type:"file",source_type:"text",text:e}]:[...t,{type:"text",text:e}]}function K4e(t,e){return t==="error"||e==="error"?"error":"success"}function Qir(t,e){function r(n,o){if(typeof n!="object"||n===null||n===void 0)return n;if(o>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(a=>r(a,o+1));let i={};for(let a of Object.keys(n))i[a]=r(n[a],o+1);return i}return JSON.stringify(r(t,0),null,2)}function xs(t,e){let r={...t};for(let[n,o]of Object.entries(e))if(r[n]==null)r[n]=o;else{if(o==null)continue;if(typeof r[n]!=typeof o||Array.isArray(r[n])!==Array.isArray(o))throw new Error(`field[${n}] already exists in the message chunk, but with a different type.`);if(typeof r[n]=="string"){if(n==="type")continue;r[n]+=o}else if(typeof r[n]=="object"&&!Array.isArray(r[n]))r[n]=xs(r[n],o);else if(Array.isArray(r[n]))r[n]=R2(r[n],o);else{if(r[n]===o)continue;console.warn(`field[${n}] already exists in this message chunk and value has unsupported type.`)}}return r}function R2(t,e){if(!(t===void 0&&e===void 0)){if(t===void 0||e===void 0)return t||e;{let r=[...t];for(let n of e)if(typeof n=="object"&&"index"in n&&typeof n.index=="number"){let o=r.findIndex(i=>i.index===n.index);o!==-1?r[o]=xs(r[o],n):r.push(n)}else{if(typeof n=="object"&&"text"in n&&n.text==="")continue;r.push(n)}return r}}}function G4e(t,e){if(!t&&!e)throw new Error("Cannot merge two undefined objects.");if(!t||!e)return t||e;if(typeof t!=typeof e)throw new Error(`Cannot merge objects of different types.
Left ${typeof t}
Right ${typeof e}`);if(typeof t=="string"&&typeof e=="string")return t+e;if(Array.isArray(t)&&Array.isArray(e))return M2(t,e);if(typeof t=="object"&&typeof e=="object")return xs(t,e);if(t===e)return t;throw new Error(`Can not merge objects of different types.
Right ${typeof e}`);if(typeof t=="string"&&typeof e=="string")return t+e;if(Array.isArray(t)&&Array.isArray(e))return R2(t,e);if(typeof t=="object"&&typeof e=="object")return xs(t,e);if(t===e)return t;throw new Error(`Can not merge objects of different types.
Left ${t}
Right ${e}`)}function K4e(t){return typeof t.role=="string"}function Ph(t){return typeof t?._getType=="function"}function ume(t){return Ph(t)&&typeof t.concat=="function"}var Sl,bp,Eh=w(()=>{yR();sme();Sl=class extends gp{get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}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(""):""}getType(){return this._getType()}constructor(e,r){typeof e=="string"&&(e={content:e,additional_kwargs:r,response_metadata:{}}),e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","messages"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"content",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"additional_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.content=e.content,this.additional_kwargs=e.additional_kwargs,this.response_metadata=e.response_metadata,this.id=e.id}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}}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;let r=Gir(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${r}`}};bp=class extends Sl{}});function G4e(t){return t!=null&&typeof t=="object"&&"lc_direct_tool_output"in t&&t.lc_direct_tool_output===!0}function J4e(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),a={name:o||"",args:i||{},id:n.id};e.push(a)}catch{r.push({name:o,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[e,r]}var PC,Th,KL=w(()=>{Eh();PC=class extends Sl{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}constructor(e,r,n){typeof e=="string"&&(e={content:e,name:n,tool_call_id:r}),super(e),Object.defineProperty(this,"lc_direct_tool_output",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}_getType(){return"tool"}static isInstance(e){return e._getType()==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},Th=class t extends bp{constructor(e){super(e),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}_getType(){return"tool"}concat(e){return new t({content:Oh(this.content,e.content),additional_kwargs:xs(this.additional_kwargs,e.additional_kwargs),response_metadata:xs(this.response_metadata,e.response_metadata),artifact:W4e(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:V4e(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}});function Oi(t){return t._getType()==="ai"}function lme(t){return t._getType()==="ai"}var gn,dr,SR=w(()=>{ime();Eh();KL();gn=class extends Sl{get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(e,r){let n;if(typeof e=="string")n={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:r??{}};else{n=e;let o=n.additional_kwargs?.tool_calls,i=n.tool_calls;o!=null&&o.length>0&&(i===void 0||i.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
Right ${e}`)}function J4e(t){return typeof t.role=="string"}function Ph(t){return typeof t?._getType=="function"}function dme(t){return Ph(t)&&typeof t.concat=="function"}var Sl,bp,Eh=w(()=>{yR();cme();Sl=class extends gp{get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}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(""):""}getType(){return this._getType()}constructor(e,r){typeof e=="string"&&(e={content:e,additional_kwargs:r,response_metadata:{}}),e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","messages"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"content",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"additional_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.content=e.content,this.additional_kwargs=e.additional_kwargs,this.response_metadata=e.response_metadata,this.id=e.id}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}}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;let r=Qir(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${r}`}};bp=class extends Sl{}});function Y4e(t){return t!=null&&typeof t=="object"&&"lc_direct_tool_output"in t&&t.lc_direct_tool_output===!0}function Z4e(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),a={name:o||"",args:i||{},id:n.id};e.push(a)}catch{r.push({name:o,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[e,r]}var EC,Th,GL=w(()=>{Eh();EC=class extends Sl{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}constructor(e,r,n){typeof e=="string"&&(e={content:e,name:n,tool_call_id:r}),super(e),Object.defineProperty(this,"lc_direct_tool_output",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}_getType(){return"tool"}static isInstance(e){return e._getType()==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},Th=class t extends bp{constructor(e){super(e),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}_getType(){return"tool"}concat(e){return new t({content:Oh(this.content,e.content),additional_kwargs:xs(this.additional_kwargs,e.additional_kwargs),response_metadata:xs(this.response_metadata,e.response_metadata),artifact:G4e(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:K4e(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}});function Oi(t){return t._getType()==="ai"}function fme(t){return t._getType()==="ai"}var gn,dr,SR=w(()=>{ume();Eh();GL();gn=class extends Sl{get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(e,r){let n;if(typeof e=="string")n={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:r??{}};else{n=e;let o=n.additional_kwargs?.tool_calls,i=n.tool_calls;o!=null&&o.length>0&&(i===void 0||i.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
Please upgrade your packages to versions that set`,"message tool calls. e.g., `yarn add @langchain/anthropic`,","yarn add @langchain/openai`, etc."].join(" "));try{if(o!=null&&i===void 0){let[a,s]=J4e(o);n.tool_calls=a??[],n.invalid_tool_calls=s??[]}else n.tool_calls=n.tool_calls??[],n.invalid_tool_calls=n.invalid_tool_calls??[]}catch{n.tool_calls=[],n.invalid_tool_calls=[]}}super(n),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof n!="string"&&(this.tool_calls=n.tool_calls??this.tool_calls,this.invalid_tool_calls=n.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=n.usage_metadata}static lc_name(){return"AIMessage"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}};dr=class t extends bp{constructor(e){let r;if(typeof e=="string")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=[],o=[];for(let i of e.tool_call_chunks){let a={};try{if(a=WL(i.args||"{}"),a===null||typeof a!="object"||Array.isArray(a))throw new Error("Malformed tool call chunk args.");n.push({name:i.name??"",args:a,id:i.id,type:"tool_call"})}catch{o.push({name:i.name,args:i.args,id:i.id,error:"Malformed args.",type:"invalid_tool_call"})}}r={...e,tool_calls:n,invalid_tool_calls:o,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(r),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tool_call_chunks",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){let r={content:Oh(this.content,e.content),additional_kwargs:xs(this.additional_kwargs,e.additional_kwargs),response_metadata:xs(this.response_metadata,e.response_metadata),tool_call_chunks:[],id:this.id??e.id};if(this.tool_call_chunks!==void 0||e.tool_call_chunks!==void 0){let n=M2(this.tool_call_chunks,e.tool_call_chunks);n!==void 0&&n.length>0&&(r.tool_call_chunks=n)}if(this.usage_metadata!==void 0||e.usage_metadata!==void 0){let n={...(this.usage_metadata?.input_token_details?.audio!==void 0||e.usage_metadata?.input_token_details?.audio!==void 0)&&{audio:(this.usage_metadata?.input_token_details?.audio??0)+(e.usage_metadata?.input_token_details?.audio??0)},...(this.usage_metadata?.input_token_details?.cache_read!==void 0||e.usage_metadata?.input_token_details?.cache_read!==void 0)&&{cache_read:(this.usage_metadata?.input_token_details?.cache_read??0)+(e.usage_metadata?.input_token_details?.cache_read??0)},...(this.usage_metadata?.input_token_details?.cache_creation!==void 0||e.usage_metadata?.input_token_details?.cache_creation!==void 0)&&{cache_creation:(this.usage_metadata?.input_token_details?.cache_creation??0)+(e.usage_metadata?.input_token_details?.cache_creation??0)}},o={...(this.usage_metadata?.output_token_details?.audio!==void 0||e.usage_metadata?.output_token_details?.audio!==void 0)&&{audio:(this.usage_metadata?.output_token_details?.audio??0)+(e.usage_metadata?.output_token_details?.audio??0)},...(this.usage_metadata?.output_token_details?.reasoning!==void 0||e.usage_metadata?.output_token_details?.reasoning!==void 0)&&{reasoning:(this.usage_metadata?.output_token_details?.reasoning??0)+(e.usage_metadata?.output_token_details?.reasoning??0)}},i=this.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},a=e.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},s={input_tokens:i.input_tokens+a.input_tokens,output_tokens:i.output_tokens+a.output_tokens,total_tokens:i.total_tokens+a.total_tokens,...Object.keys(n).length>0&&{input_token_details:n},...Object.keys(o).length>0&&{output_token_details:o}};r.usage_metadata=s}return new t(r)}}});var CsLine truncated
Please upgrade your packages to versions that set`,"message tool calls. e.g., `yarn add @langchain/anthropic`,","yarn add @langchain/openai`, etc."].join(" "));try{if(o!=null&&i===void 0){let[a,s]=Z4e(o);n.tool_calls=a??[],n.invalid_tool_calls=s??[]}else n.tool_calls=n.tool_calls??[],n.invalid_tool_calls=n.invalid_tool_calls??[]}catch{n.tool_calls=[],n.invalid_tool_calls=[]}}super(n),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof n!="string"&&(this.tool_calls=n.tool_calls??this.tool_calls,this.invalid_tool_calls=n.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=n.usage_metadata}static lc_name(){return"AIMessage"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}};dr=class t extends bp{constructor(e){let r;if(typeof e=="string")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=[],o=[];for(let i of e.tool_call_chunks){let a={};try{if(a=KL(i.args||"{}"),a===null||typeof a!="object"||Array.isArray(a))throw new Error("Malformed tool call chunk args.");n.push({name:i.name??"",args:a,id:i.id,type:"tool_call"})}catch{o.push({name:i.name,args:i.args,id:i.id,error:"Malformed args.",type:"invalid_tool_call"})}}r={...e,tool_calls:n,invalid_tool_calls:o,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(r),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tool_call_chunks",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){let r={content:Oh(this.content,e.content),additional_kwargs:xs(this.additional_kwargs,e.additional_kwargs),response_metadata:xs(this.response_metadata,e.response_metadata),tool_call_chunks:[],id:this.id??e.id};if(this.tool_call_chunks!==void 0||e.tool_call_chunks!==void 0){let n=R2(this.tool_call_chunks,e.tool_call_chunks);n!==void 0&&n.length>0&&(r.tool_call_chunks=n)}if(this.usage_metadata!==void 0||e.usage_metadata!==void 0){let n={...(this.usage_metadata?.input_token_details?.audio!==void 0||e.usage_metadata?.input_token_details?.audio!==void 0)&&{audio:(this.usage_metadata?.input_token_details?.audio??0)+(e.usage_metadata?.input_token_details?.audio??0)},...(this.usage_metadata?.input_token_details?.cache_read!==void 0||e.usage_metadata?.input_token_details?.cache_read!==void 0)&&{cache_read:(this.usage_metadata?.input_token_details?.cache_read??0)+(e.usage_metadata?.input_token_details?.cache_read??0)},...(this.usage_metadata?.input_token_details?.cache_creation!==void 0||e.usage_metadata?.input_token_details?.cache_creation!==void 0)&&{cache_creation:(this.usage_metadata?.input_token_details?.cache_creation??0)+(e.usage_metadata?.input_token_details?.cache_creation??0)}},o={...(this.usage_metadata?.output_token_details?.audio!==void 0||e.usage_metadata?.output_token_details?.audio!==void 0)&&{audio:(this.usage_metadata?.output_token_details?.audio??0)+(e.usage_metadata?.output_token_details?.audio??0)},...(this.usage_metadata?.output_token_details?.reasoning!==void 0||e.usage_metadata?.output_token_details?.reasoning!==void 0)&&{reasoning:(this.usage_metadata?.output_token_details?.reasoning??0)+(e.usage_metadata?.output_token_details?.reasoning??0)}},i=this.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},a=e.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},s={input_tokens:i.input_tokens+a.input_tokens,output_tokens:i.output_tokens+a.output_tokens,total_tokens:i.total_tokens+a.total_tokens,...Object.keys(n).length>0&&{input_token_details:n},...Object.keys(o).length>0&&{output_token_details:o}};r.usage_metadata=s}return new t(r)}}});var CsLine truncated
Received: ${JSON.stringify(t,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function fy(t){if(typeof t=="string")return new Os(t);if(Ph(t))return t;if(Array.isArray(t)){let[e,r]=t;return cme({type:e,content:r})}else if(K4e(t)){let{role:e,...r}=t;return cme({...r,type:e})}else return cme(t)}function Rf(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()==="function")i="Function";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 dme(t){let e=t._getType();if(e==="human")return new Mf({...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 dr({...r})}else{if(e==="system")return new Rd({...t});if(e==="function")return new ym({...t});if(Cs.isInstance(t))return new If({...t});throw new Error("Unknown message type.")}}var NE=w(()=>{I2();pG();SR();Eh();mG();hG();R2();gG();KL()});var fme=w(()=>{QK()});var pme=w(()=>{ZK()});var mme,Y4e,Z4e=w(()=>{pme();bR();Y4e=()=>{if(mme===void 0){let t=ot("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};mme=new mR(t)}return mme}});var GL,X4e=w(()=>{fme();Kpe();bR();vR();Z4e();GL=class t extends xh{constructor(e={}){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"langchain_tracer"}),Object.defineProperty(this,"projectName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let{exampleId:r,projectName:n,client:o}=e;this.projectName=n??ot("LANGCHAIN_PROJECT")??ot("LANGCHAIN_SESSION"),this.exampleId=r,this.client=o??Y4e();let i=t.getTraceableRunTree();i&&this.updateFromRunTree(i)}async _convertToCreate(e,r=void 0){return{...e,extra:{...e.extra,runtime:await R4e()},child_runs:void 0,session_name:this.projectName,reference_example_id:e.parent_run_id?void 0:r}}async persistRun(e){}async onRunCreate(e){let r=await this._convertToCreate(e,this.exampleId);await this.client.createRun(r)}async onRunUpdate(e){let r={end_time:e.end_time,error:e.error,outputs:e.outputs,events:e.events,inputs:e.inputs,trace_id:e.trace_id,dotted_order:e.dotted_order,parent_run_id:e.parent_run_id,extra:e.extra,session_name:this.projectName};await this.client.updateRun(e.id,r)}getRun(e){return this.runMap.get(e)}updateFromRunTree(e){let r=e,n=new Set;for(;r.parent_run&&!(n.has(r.id)||(n.add(r.id),!r.parent_run));)r=r.parent_run;n.clear();let o=[r];for(;o.length>0;){let i=o.shift();!i||n.has(i.id)||(n.add(i.id),this.runMap.set(i.id,i),i.child_runs&&o.push(...i.child_runs))}this.client=e.client??this.client,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId}convertToRunTree(e){let r={},n=[];for(let[o,i]of this.runMap){let a=new CC({...i,child_runs:[],parent_run:void 0,client:this.client,project_name:this.projectName,reference_example_id:this.exampleId,tracingEnabled:!0});r[o]=a,n.push([o,i.dotted_order])}n.sort((o,i)=>!o[1]||!i[1]?0:o[1].localeCompare(i[1]));for(let[o]of n){let i=this.runMap.get(o),a=r[o];if(!(!i||!a)&&i.parent_run_id){let s=r[i.parent_run_id];s&&(s.child_runs.push(a),a.parent_run=s)}}return r[e]}static getTraceableRunTree(){try{return f4e()}catch{return}}}});var Q4e,xR,e3e,DE,j2=w(()=>{Q4e=Symbol.for("ls:tracing_async_local_storage"),xR=Symbol.for("lc:context_variables"),e3e=t=>{globalThis[Q4e]=t},DE=()=>globalThis[Q4e]});function Xir(){let t="default"in yG.default?yG.default.default:yG.default;return new t({autoStart:!0,concurrency:1})}function Qir(){return typeof N2>"u"&&(N2=Xir()),N2}async function Ps(t,e){if(e===!0){let r=DE();r!==void 0?await r.run(void 0,async()=>t()):await t()}else N2=Qir(),N2.add(async()=>{let r=DE();r!==void 0?await r.run(void 0,async()=>t()):await t()})}var yG,N2,t3e=w(()=>{yG=F(NK(),1);j2()});var r3e=w(()=>{t3e()});var n3e,o3e=w(()=>{bR();n3e=t=>t!==void 0?t:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(r=>ot(r)==="true")});function hme(t){let e=DE();return e===void 0?void 0:e.getStore()?.[xR]?.[t]}var ear,i3e,a3e=w(()=>{fme();j2();ear=Symbol("lc:configure_hooks"),i3e=()=>hme(ear)||[]});function CR(t){return t?Array.isArray(t)||"name"in t?{callbacks:t}:t:{}}function D2(t){return"name"in t?t:_R.fromMethods(t)}var gme,JL,yme,bG,bme,_me,Bs,LE=w(()=>{TE();T2();$4e();NE();bR();X4e();r3e();o3e();vR();a3e();gme=class{setHandler(e){return this.setHandlers([e])}},JL=class{constructor(e,r,n,o,i,a,s,u){Object.defineProperty(this,"runId",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:o}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:u})}get parentRunId(){return this._parentRunId}async handleText Line truncated
Received: ${JSON.stringify(t,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function fy(t){if(typeof t=="string")return new Os(t);if(Ph(t))return t;if(Array.isArray(t)){let[e,r]=t;return pme({type:e,content:r})}else if(J4e(t)){let{role:e,...r}=t;return pme({...r,type:e})}else return pme(t)}function Rf(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()==="function")i="Function";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 mme(t){let e=t._getType();if(e==="human")return new Mf({...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 dr({...r})}else{if(e==="system")return new Rd({...t});if(e==="function")return new ym({...t});if(Cs.isInstance(t))return new If({...t});throw new Error("Unknown message type.")}}var NE=w(()=>{M2();mG();SR();Eh();hG();gG();j2();yG();GL()});var hme=w(()=>{eG()});var gme=w(()=>{XK()});var yme,X4e,Q4e=w(()=>{gme();bR();X4e=()=>{if(yme===void 0){let t=ot("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};yme=new mR(t)}return yme}});var JL,e3e=w(()=>{hme();Ype();bR();vR();Q4e();JL=class t extends xh{constructor(e={}){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"langchain_tracer"}),Object.defineProperty(this,"projectName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let{exampleId:r,projectName:n,client:o}=e;this.projectName=n??ot("LANGCHAIN_PROJECT")??ot("LANGCHAIN_SESSION"),this.exampleId=r,this.client=o??X4e();let i=t.getTraceableRunTree();i&&this.updateFromRunTree(i)}async _convertToCreate(e,r=void 0){return{...e,extra:{...e.extra,runtime:await N4e()},child_runs:void 0,session_name:this.projectName,reference_example_id:e.parent_run_id?void 0:r}}async persistRun(e){}async onRunCreate(e){let r=await this._convertToCreate(e,this.exampleId);await this.client.createRun(r)}async onRunUpdate(e){let r={end_time:e.end_time,error:e.error,outputs:e.outputs,events:e.events,inputs:e.inputs,trace_id:e.trace_id,dotted_order:e.dotted_order,parent_run_id:e.parent_run_id,extra:e.extra,session_name:this.projectName};await this.client.updateRun(e.id,r)}getRun(e){return this.runMap.get(e)}updateFromRunTree(e){let r=e,n=new Set;for(;r.parent_run&&!(n.has(r.id)||(n.add(r.id),!r.parent_run));)r=r.parent_run;n.clear();let o=[r];for(;o.length>0;){let i=o.shift();!i||n.has(i.id)||(n.add(i.id),this.runMap.set(i.id,i),i.child_runs&&o.push(...i.child_runs))}this.client=e.client??this.client,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId}convertToRunTree(e){let r={},n=[];for(let[o,i]of this.runMap){let a=new OC({...i,child_runs:[],parent_run:void 0,client:this.client,project_name:this.projectName,reference_example_id:this.exampleId,tracingEnabled:!0});r[o]=a,n.push([o,i.dotted_order])}n.sort((o,i)=>!o[1]||!i[1]?0:o[1].localeCompare(i[1]));for(let[o]of n){let i=this.runMap.get(o),a=r[o];if(!(!i||!a)&&i.parent_run_id){let s=r[i.parent_run_id];s&&(s.child_runs.push(a),a.parent_run=s)}}return r[e]}static getTraceableRunTree(){try{return m4e()}catch{return}}}});var t3e,xR,r3e,DE,N2=w(()=>{t3e=Symbol.for("ls:tracing_async_local_storage"),xR=Symbol.for("lc:context_variables"),r3e=t=>{globalThis[t3e]=t},DE=()=>globalThis[t3e]});function nar(){let t="default"in bG.default?bG.default.default:bG.default;return new t({autoStart:!0,concurrency:1})}function oar(){return typeof D2>"u"&&(D2=nar()),D2}async function Ps(t,e){if(e===!0){let r=DE();r!==void 0?await r.run(void 0,async()=>t()):await t()}else D2=oar(),D2.add(async()=>{let r=DE();r!==void 0?await r.run(void 0,async()=>t()):await t()})}var bG,D2,n3e=w(()=>{bG=F(DK(),1);N2()});var o3e=w(()=>{n3e()});var i3e,a3e=w(()=>{bR();i3e=t=>t!==void 0?t:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(r=>ot(r)==="true")});function bme(t){let e=DE();return e===void 0?void 0:e.getStore()?.[xR]?.[t]}var iar,s3e,u3e=w(()=>{hme();N2();iar=Symbol("lc:configure_hooks"),s3e=()=>bme(iar)||[]});function CR(t){return t?Array.isArray(t)||"name"in t?{callbacks:t}:t:{}}function L2(t){return"name"in t?t:_R.fromMethods(t)}var _me,YL,vme,_G,wme,Sme,Bs,LE=w(()=>{TE();A2();q4e();NE();bR();e3e();o3e();a3e();vR();u3e();_me=class{setHandler(e){return this.setHandlers([e])}},YL=class{constructor(e,r,n,o,i,a,s,u){Object.defineProperty(this,"runId",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:o}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:u})}get parentRunId(){return this._parentRunId}async handleText Line truncated
]))`;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 kme,my,uar,IG=w(()=>{FE();my={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:()=>(kme===void 0&&(kme=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),kme),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-_]*$/};uar=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function MG(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===de.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:fr(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:fr(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===de.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=AG(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===de.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===de.ZodBranded&&t.keyType._def.type._def.typeName===de.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=EG(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var RG=w(()=>{Td();qs();IG();TG()});function j3e(t,e){if(e.mapStrategy==="record")return MG(t,e);let r=fr(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=fr(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 Bme=w(()=>{qs();RG()});function N3e(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 qme=w(()=>{});function D3e(){return{not:{}}}var Ume=w(()=>{});function L3e(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var zme=w(()=>{});function k3e(t,e){if(e.target==="openApi3")return F3e(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in q2&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=q2[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)= Line truncated
`;return e}function Y3e(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}'}}}%%
]`;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 qme,my,par,MG=w(()=>{FE();my={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:()=>(qme===void 0&&(qme=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),qme),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-_]*$/};par=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function RG(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===de.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:fr(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:fr(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===de.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=IG(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===de.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===de.ZodBranded&&t.keyType._def.type._def.typeName===de.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=TG(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var jG=w(()=>{Td();qs();MG();AG()});function D3e(t,e){if(e.mapStrategy==="record")return RG(t,e);let r=fr(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=fr(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 zme=w(()=>{qs();jG()});function L3e(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 Hme=w(()=>{});function F3e(){return{not:{}}}var Vme=w(()=>{});function k3e(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Wme=w(()=>{});function B3e(t,e){if(e.target==="openApi3")return $3e(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in U2&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=U2[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)= Line truncated
`;return e}function X3e(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,b]of Object.entries(t)){let g=b.name.split(":").pop()??"",S=har.some(O=>g.startsWith(O)&&g.endsWith(O))?`<p>${g}</p>`:g;Object.keys(b.metadata??{}).length&&(S+=`<hr/><small><em>${Object.entries(b.metadata??{}).map(([O,P])=>`${O} = ${P}`).join(`
`)}</em></small>`);let x=(m[h]??m[p]).replace("{0}",rhe(h)).replace("{1}",S);l+=` ${x}
`;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,b]of Object.entries(t)){let g=b.name.split(":").pop()??"",S=war.some(O=>g.startsWith(O)&&g.endsWith(O))?`<p>${g}</p>`:g;Object.keys(b.metadata??{}).length&&(S+=`<hr/><small><em>${Object.entries(b.metadata??{}).map(([O,P])=>`${O} = ${P}`).join(`
`)}</em></small>`);let x=(m[h]??m[p]).replace("{0}",ihe(h)).replace("{1}",S);l+=` ${x}
`}}let c={};for(let p of e){let m=p.source.split(":"),h=p.target.split(":"),b=m.filter((g,y)=>g===h[y]).join(":");c[b]||(c[b]=[]),c[b].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 b=m.split(":").pop();if(d.has(b))throw new Error(`Found duplicate subgraph '${b}' -- 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(b),l+=` subgraph ${b}
`}for(let b of p){let{source:g,target:y,data:S,conditional:x}=b,O="";if(S!==void 0){let P=S,E=P.split(" ");E.length>u&&(P=Array.from({length:Math.ceil(E.length/u)},(A,I)=>E.slice(I*u,(I+1)*u).join(" ")).join("&nbsp;<br>&nbsp;")),O=x?` -. &nbsp;${P}&nbsp; .-> `:` -- &nbsp;${P}&nbsp; --> `}else O=x?" -.-> ":" --> ";l+=` ${rhe(g)}${O}${rhe(y)};
`}for(let b of p){let{source:g,target:y,data:S,conditional:x}=b,O="";if(S!==void 0){let P=S,E=P.split(" ");E.length>u&&(P=Array.from({length:Math.ceil(E.length/u)},(A,I)=>E.slice(I*u,(I+1)*u).join(" ")).join("&nbsp;<br>&nbsp;")),O=x?` -. &nbsp;${P}&nbsp; .-> `:` -- &nbsp;${P}&nbsp; --> `}else O=x?" -.-> ":" --> ";l+=` ${ihe(g)}${O}${ihe(y)};
`}for(let b in c)b.startsWith(`${m}:`)&&b!==m&&f(c[b],b);m&&!h&&(l+=` end
`)}f(c[""]??[],"");for(let p in c)!p.includes(":")&&p!==""&&f(c[p],p);return a&&(l+=gar(i??{})),l}async function Z3e(t,e){let{backgroundColor:r="white"}=e??{},n=btoa(t);r!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));let o=`https://mermaid.ink/img/${n}?bgColor=${r}`,i=await fetch(o);if(!i.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${i.status}`,`Status text: ${i.statusText}`].join(`
`));return await i.blob()}var har,X3e=w(()=>{har=["*","_","`"]});function yar(t,e){if(t!==void 0&&!EE(t))return t;if(B2(e))try{let r=e.getName();return r=r.startsWith("Runnable")?r.slice(8):r,r}catch{return e.getName()}else return e.name??"UnknownSchema"}function bar(t){return B2(t.data)?{type:"runnable",data:{id:t.data.lc_id,name:t.data.getName()}}:{type:"schema",data:{...So(t.data.schema),title:t.data.name}}}function Q3e(t,e=[]){let r=new Set(t.edges.filter(o=>!e.includes(o.source)).map(o=>o.target)),n=[];for(let o of Object.values(t.nodes))!e.includes(o.id)&&!r.has(o.id)&&n.push(o);return n.length===1?n[0]:void 0}function eHe(t,e=[]){let r=new Set(t.edges.filter(o=>!e.includes(o.target)).map(o=>o.source)),n=[];for(let o of Object.values(t.nodes))!e.includes(o.id)&&!r.has(o.id)&&n.push(o);return n.length===1?n[0]:void 0}var U2,tHe=w(()=>{Ec();TE();xme();X3e();U2=class t{constructor(e){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){let e={};return Object.values(this.nodes).forEach((r,n)=>{e[r.id]=EE(r.id)?n:r.id}),{nodes:Object.values(this.nodes).map(r=>({id:e[r.id],...bar(r)})),edges:this.edges.map(r=>{let n={source:e[r.source],target:e[r.target]};return typeof r.data<"u"&&(n.data=r.data),typeof r.conditional<"u"&&(n.conditional=r.conditional),n})}}addNode(e,r,n){if(r!==void 0&&this.nodes[r]!==void 0)throw new Error(`Node with id ${r} already exists`);let o=r??as(),i={id:o,data:e,name:yar(r,e),metadata:n};return this.nodes[o]=i,i}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(r=>r.source!==e.id&&r.target!==e.id)}addEdge(e,r,n,o){if(this.nodes[e.id]===void 0)throw new Error(`Source node ${e.id} not in graph`);if(this.nodes[r.id]===void 0)throw new Error(`Target node ${r.id} not in graph`);let i={source:e.id,target:r.id,data:n,conditional:o};return this.edges.push(i),i}firstNode(){return Q3e(this)}lastNode(){return eHe(this)}extend(e,r=""){let n=r;Object.values(e.nodes).map(l=>l.id).every(EE)&&(n="");let i=l=>n?`${n}:${l}`:l;Object.entries(e.nodes).forEach(([l,c])=>{this.nodes[i(l)]={...c,id:i(l)}});let a=e.edges.map(l=>({...l,source:i(l.source),target:i(l.target)}));this.edges=[...this.edges,...a];let s=e.firstNode(),u=e.lastNode();return[s?{id:i(s.id),data:s.data}:void 0,u?{id:i(u.id),data:u.data}:void 0]}trimFirstNode(){let e=this.firstNode();e&&Q3e(this,[e.id])&&this.removeNode(e)}trimLastNode(){let e=this.lastNode();e&&eHe(this,[e.id])&&this.removeNode(e)}reid(){let e=Object.fromEntries(Object.values(this.nodes).map(o=>[o.id,o.name])),r=new Map;Object.values(e).forEach(o=>{r.set(o,(r.get(o)||0)+1)});let n=o=>{let i=e[o];return EE(o)&&r.get(i)===1?i:o};return new t({nodes:Object.fromEntries(Object.entries(this.nodes).map(([o,i])=>[n(o),{...i,id:n(o)}])),edges:this.edges.map(o=>({...o,source:n(o.source),target:n(o.target)}))})}drawMermaid(e){let{withStyles:r,curveStyle:n,nodeColors:o={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:i}=e??{},a=this.reid(),s=a.firstNode(),u=a.lastNode();return Y3e(a.nodes,a.edges,{firstNode:s?.id,lastNode:u?.id,withStyles:r,curveStyle:n,nodeColors:o,wrapLabelNWords:i})}async drawMermaidPng(e){let r=this.drawMermaid(e);return Z3e(r,{backgroundColor:e?.backgroundColor})}}});function rHe(t){let e=new TextEncoder,r=new ReadableStream({async start(n){for await(let o of t)n.enqueue(e.encode(`event: data
`)}f(c[""]??[],"");for(let p in c)!p.includes(":")&&p!==""&&f(c[p],p);return a&&(l+=Sar(i??{})),l}async function Q3e(t,e){let{backgroundColor:r="white"}=e??{},n=btoa(t);r!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));let o=`https://mermaid.ink/img/${n}?bgColor=${r}`,i=await fetch(o);if(!i.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${i.status}`,`Status text: ${i.statusText}`].join(`
`));return await i.blob()}var war,eHe=w(()=>{war=["*","_","`"]});function xar(t,e){if(t!==void 0&&!EE(t))return t;if(q2(e))try{let r=e.getName();return r=r.startsWith("Runnable")?r.slice(8):r,r}catch{return e.getName()}else return e.name??"UnknownSchema"}function Car(t){return q2(t.data)?{type:"runnable",data:{id:t.data.lc_id,name:t.data.getName()}}:{type:"schema",data:{...So(t.data.schema),title:t.data.name}}}function tHe(t,e=[]){let r=new Set(t.edges.filter(o=>!e.includes(o.source)).map(o=>o.target)),n=[];for(let o of Object.values(t.nodes))!e.includes(o.id)&&!r.has(o.id)&&n.push(o);return n.length===1?n[0]:void 0}function rHe(t,e=[]){let r=new Set(t.edges.filter(o=>!e.includes(o.target)).map(o=>o.source)),n=[];for(let o of Object.values(t.nodes))!e.includes(o.id)&&!r.has(o.id)&&n.push(o);return n.length===1?n[0]:void 0}var z2,nHe=w(()=>{Ec();TE();Pme();eHe();z2=class t{constructor(e){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){let e={};return Object.values(this.nodes).forEach((r,n)=>{e[r.id]=EE(r.id)?n:r.id}),{nodes:Object.values(this.nodes).map(r=>({id:e[r.id],...Car(r)})),edges:this.edges.map(r=>{let n={source:e[r.source],target:e[r.target]};return typeof r.data<"u"&&(n.data=r.data),typeof r.conditional<"u"&&(n.conditional=r.conditional),n})}}addNode(e,r,n){if(r!==void 0&&this.nodes[r]!==void 0)throw new Error(`Node with id ${r} already exists`);let o=r??as(),i={id:o,data:e,name:xar(r,e),metadata:n};return this.nodes[o]=i,i}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(r=>r.source!==e.id&&r.target!==e.id)}addEdge(e,r,n,o){if(this.nodes[e.id]===void 0)throw new Error(`Source node ${e.id} not in graph`);if(this.nodes[r.id]===void 0)throw new Error(`Target node ${r.id} not in graph`);let i={source:e.id,target:r.id,data:n,conditional:o};return this.edges.push(i),i}firstNode(){return tHe(this)}lastNode(){return rHe(this)}extend(e,r=""){let n=r;Object.values(e.nodes).map(l=>l.id).every(EE)&&(n="");let i=l=>n?`${n}:${l}`:l;Object.entries(e.nodes).forEach(([l,c])=>{this.nodes[i(l)]={...c,id:i(l)}});let a=e.edges.map(l=>({...l,source:i(l.source),target:i(l.target)}));this.edges=[...this.edges,...a];let s=e.firstNode(),u=e.lastNode();return[s?{id:i(s.id),data:s.data}:void 0,u?{id:i(u.id),data:u.data}:void 0]}trimFirstNode(){let e=this.firstNode();e&&tHe(this,[e.id])&&this.removeNode(e)}trimLastNode(){let e=this.lastNode();e&&rHe(this,[e.id])&&this.removeNode(e)}reid(){let e=Object.fromEntries(Object.values(this.nodes).map(o=>[o.id,o.name])),r=new Map;Object.values(e).forEach(o=>{r.set(o,(r.get(o)||0)+1)});let n=o=>{let i=e[o];return EE(o)&&r.get(i)===1?i:o};return new t({nodes:Object.fromEntries(Object.entries(this.nodes).map(([o,i])=>[n(o),{...i,id:n(o)}])),edges:this.edges.map(o=>({...o,source:n(o.source),target:n(o.target)}))})}drawMermaid(e){let{withStyles:r,curveStyle:n,nodeColors:o={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:i}=e??{},a=this.reid(),s=a.firstNode(),u=a.lastNode();return X3e(a.nodes,a.edges,{firstNode:s?.id,lastNode:u?.id,withStyles:r,curveStyle:n,nodeColors:o,wrapLabelNWords:i})}async drawMermaidPng(e){let r=this.drawMermaid(e);return Q3e(r,{backgroundColor:e?.backgroundColor})}}});function oHe(t){let e=new TextEncoder,r=new ReadableStream({async start(n){for await(let o of t)n.enqueue(e.encode(`event: data
data: ${JSON.stringify(o)}
`));n.enqueue(e.encode(`event: end
`)),n.close()}});return Nd.fromReadableStream(r)}var nHe=w(()=>{Wb()});function nhe(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}function NG(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function*ohe(t,e){for(;;){let{value:r,done:n}=jd.runWithConfig(bm(t),e.next.bind(e),!0);if(n)break;yield r}}async function*DG(t,e){let r=e[Symbol.asyncIterator]();for(;;){let{value:n,done:o}=await jd.runWithConfig(bm(t),r.next.bind(e),!0);if(o)break;yield n}}var oHe,iHe=w(()=>{YL();Hb();oHe=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function"});function xl(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function _ar(t){if(nG(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}function AC(t){if(typeof t=="function")return new Nf({func:t});if(xn.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){let e={};for(let[r,n]of Object.entries(t))e[r]=AC(n);return new kE({steps:e})}else throw new Error(`Expected a Runnable, function or object.
Instead got an unsupported type.`)}function war(t,e){let r=e.name??t.getName(),n=e.description??e.schema?.description;return e.schema.constructor===Wr.ZodString?new z2({name:r,description:n,schema:Wr.object({input:Wr.string()}).transform(o=>o.input),bound:t}):new z2({name:r,description:n,schema:e.schema,bound:t})}var ihe,xn,IC,LG,FG,bi,kE,ahe,Nf,kG,QL,$G,z2,Df=w(()=>{Td();ihe=F(PK(),1);TE();Kpe();p3e();h3e();yR();Wb();wme();Hb();XL();y3e();xme();YL();tHe();nHe();iHe();pG();xn=class extends gp{constructor(){super(...arguments),Object.defineProperty(this,"lc_runnable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}getName(e){let r=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${r}${e}`:r}bind(e){return new IC({bound:this,kwargs:e,config:{}})}map(){return new LG({bound:this})}withRetry(e){return new FG({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new IC({bound:this,config:e,kwargs:{}})}withFallbacks(e){let r=Array.isArray(e)?e:e.fallbacks;return new kG({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(un);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)=>un(i===0?e:n))}return Array.from({length:r},()=>un(e))}async batch(e,r,n){let o=this._getOptionsList(r??{},e.length),i=o[0]?.maxConcurrency??n?.maxConcurrency,a=new _m({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=un(r),o=new TC({generator:this._streamIterator(e,n),config:n});return await o.setup,Nd.fromAsyncGenerator(o)}_separateRunnableConfigFromCallOptions(e){let r;e===void 0?r=un(e):r=un({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=un(n),a=await(await _p(o))?.handleChainStart(this.toJSON(),xl(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 Vb(u,n?.signal)}catch(u){throw await a?.handleChainError(u),u}return await a?.handleChainEnd(xl(s,"output")),s}async _batchWithConfig(e,r,n,o){let i=this._getOptionsList(n??{},r.length),a=await Promise.all(i.map(_p)),s=await Promise.all(a.map(async(l,c)=>{let d=await l?.handleChainStart(this.toJSON(),xl(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 Vb(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(xl(u,"output")))),u}async*_transformStreamWithConfig(e,r,n){let o,i=!0,a,s=!0,u=un(n),l=await _p(u);async function*c(){for await(let f of e){if(i)if(o===void 0)o=f;else try{o=Hl(o,f)}catch{o=void 0,i=!1}yield f}}let d;try{let f=await l3e(r.bind(this),c(),async()=>l?.handleChainStart(this.toJSON(),{input:""},u.runId,u.runType,void 0,void 0,u.runName??this.getName()),n?.signal,u);delete u.runId,d=f.setup;let p=d?.handlers.find(m3e),m=f.output;p!==void 0&&d!==void 0&&(m=p.tapOutputIterable(d.runId,m));let h=d?.handlers.find(f3e);h!==void 0&&d!==void 0&&(m=h.tapOutputIterable(d.runId,m));for await(let b of m)if(yield b,s)if(a===void 0)a=b;else try{a=Hl(a,b)}catch{a=void 0,s=!1}}catch(f){throw await d?.handleChainError(f,void 0,void 0,void 0,{inputs:xl(o,"input")}),f}await d?.handleChainEnd(a??{},void 0,void 0,void 0,{inputs:xl(o,"input")})}getGraph(e){let r=new U2,n=r.addNode({name:`${this.getName()}Input`,schema:Wr.any()}),o=r.addNode(this),i=r.addNode({name:`${this.getName()}Output`,schema:Wr.any()});return r.addEdge(n,o),r.addEdge(o,i),r}pipe(e){return new bi({first:this,last:AC(e)})}pick(e){return this.pipe(new $G(e))}assign(e){return this.pipe(new QL(new kE({steps:e})))}async*transform(e,r){let n;for await(let o of e)n===void 0?n=o:n=Hl(n,o);yield*this._streamIterator(n,un(r))}async*streamLog(e,r,n){let o=new F2({...n,autoClose:!1,_schemaFormat:"original"}),i=un(r);yield*this._streamLog(e,o,i)}async*_streamLog(e,r,n){let{callbacks:o}=n;if(o===void 0)n.callbacks=[r];else if(Array. Line truncated
`)),n.close()}});return Nd.fromReadableStream(r)}var iHe=w(()=>{Wb()});function ahe(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}function DG(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function*she(t,e){for(;;){let{value:r,done:n}=jd.runWithConfig(bm(t),e.next.bind(e),!0);if(n)break;yield r}}async function*LG(t,e){let r=e[Symbol.asyncIterator]();for(;;){let{value:n,done:o}=await jd.runWithConfig(bm(t),r.next.bind(e),!0);if(o)break;yield n}}var aHe,sHe=w(()=>{ZL();Hb();aHe=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function"});function xl(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function Oar(t){if(oG(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}function IC(t){if(typeof t=="function")return new Nf({func:t});if(Cn.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){let e={};for(let[r,n]of Object.entries(t))e[r]=IC(n);return new kE({steps:e})}else throw new Error(`Expected a Runnable, function or object.
Instead got an unsupported type.`)}function Par(t,e){let r=e.name??t.getName(),n=e.description??e.schema?.description;return e.schema.constructor===Wr.ZodString?new H2({name:r,description:n,schema:Wr.object({input:Wr.string()}).transform(o=>o.input),bound:t}):new H2({name:r,description:n,schema:e.schema,bound:t})}var uhe,Cn,MC,FG,kG,bi,kE,lhe,Nf,$G,eF,BG,H2,Df=w(()=>{Td();uhe=F(EK(),1);TE();Ype();h3e();y3e();yR();Wb();Cme();Hb();QL();_3e();Pme();ZL();nHe();iHe();sHe();mG();Cn=class extends gp{constructor(){super(...arguments),Object.defineProperty(this,"lc_runnable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}getName(e){let r=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${r}${e}`:r}bind(e){return new MC({bound:this,kwargs:e,config:{}})}map(){return new FG({bound:this})}withRetry(e){return new kG({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new MC({bound:this,config:e,kwargs:{}})}withFallbacks(e){let r=Array.isArray(e)?e:e.fallbacks;return new $G({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(un);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)=>un(i===0?e:n))}return Array.from({length:r},()=>un(e))}async batch(e,r,n){let o=this._getOptionsList(r??{},e.length),i=o[0]?.maxConcurrency??n?.maxConcurrency,a=new _m({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=un(r),o=new AC({generator:this._streamIterator(e,n),config:n});return await o.setup,Nd.fromAsyncGenerator(o)}_separateRunnableConfigFromCallOptions(e){let r;e===void 0?r=un(e):r=un({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=un(n),a=await(await _p(o))?.handleChainStart(this.toJSON(),xl(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 Vb(u,n?.signal)}catch(u){throw await a?.handleChainError(u),u}return await a?.handleChainEnd(xl(s,"output")),s}async _batchWithConfig(e,r,n,o){let i=this._getOptionsList(n??{},r.length),a=await Promise.all(i.map(_p)),s=await Promise.all(a.map(async(l,c)=>{let d=await l?.handleChainStart(this.toJSON(),xl(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 Vb(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(xl(u,"output")))),u}async*_transformStreamWithConfig(e,r,n){let o,i=!0,a,s=!0,u=un(n),l=await _p(u);async function*c(){for await(let f of e){if(i)if(o===void 0)o=f;else try{o=Hl(o,f)}catch{o=void 0,i=!1}yield f}}let d;try{let f=await d3e(r.bind(this),c(),async()=>l?.handleChainStart(this.toJSON(),{input:""},u.runId,u.runType,void 0,void 0,u.runName??this.getName()),n?.signal,u);delete u.runId,d=f.setup;let p=d?.handlers.find(g3e),m=f.output;p!==void 0&&d!==void 0&&(m=p.tapOutputIterable(d.runId,m));let h=d?.handlers.find(m3e);h!==void 0&&d!==void 0&&(m=h.tapOutputIterable(d.runId,m));for await(let b of m)if(yield b,s)if(a===void 0)a=b;else try{a=Hl(a,b)}catch{a=void 0,s=!1}}catch(f){throw await d?.handleChainError(f,void 0,void 0,void 0,{inputs:xl(o,"input")}),f}await d?.handleChainEnd(a??{},void 0,void 0,void 0,{inputs:xl(o,"input")})}getGraph(e){let r=new z2,n=r.addNode({name:`${this.getName()}Input`,schema:Wr.any()}),o=r.addNode(this),i=r.addNode({name:`${this.getName()}Output`,schema:Wr.any()});return r.addEdge(n,o),r.addEdge(o,i),r}pipe(e){return new bi({first:this,last:IC(e)})}pick(e){return this.pipe(new BG(e))}assign(e){return this.pipe(new eF(new kE({steps:e})))}async*transform(e,r){let n;for await(let o of e)n===void 0?n=o:n=Hl(n,o);yield*this._streamIterator(n,un(r))}async*streamLog(e,r,n){let o=new k2({...n,autoClose:!1,_schemaFormat:"original"}),i=un(r);yield*this._streamLog(e,o,i)}async*_streamLog(e,r,n){let{callbacks:o}=n;if(o===void 0)n.callbacks=[r];else if(Array. Line truncated
Known schemas:
- ${Object.keys(n).join(`
- `)}`,new Error(ce)}let oe=`${s}/$ref`,se=oa(t,Pe,r,n,o,i,a,oe,u);if(se.valid||te.push({instanceLocation:a,keyword:"$ref",keywordLocation:oe,error:"A subschema had errors."},...se.errors),r==="4"||r==="7")return{valid:te.length===0,errors:te}}if(Array.isArray(m)){let Re=m.length,Pe=!1;for(let oe=0;oe<Re;oe++)if(c===m[oe]||m[oe]==="integer"&&c==="number"&&t%1===0&&t===t){Pe=!0;break}Pe||te.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)&&te.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m}".`}):m!==void 0&&c!==m&&te.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m}".`});if(h!==void 0&&(c==="object"||c==="array"?MC(t,h)||te.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):t!==h&&te.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),b!==void 0&&(c==="object"||c==="array"?b.some(Re=>MC(t,Re))||te.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`}):b.some(Re=>t===Re)||te.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`})),y!==void 0){let Re=`${s}/not`;oa(t,y,r,n,o,i,a,Re).valid&&te.push({instanceLocation:a,keyword:"not",keywordLocation:Re,error:'Instance matched "not" schema.'})}let et=[];if(S!==void 0){let Re=`${s}/anyOf`,Pe=te.length,oe=!1;for(let se=0;se<S.length;se++){let ce=S[se],Ce=Object.create(u),Je=oa(t,ce,r,n,o,p===!0?i:null,a,`${Re}/${se}`,Ce);te.push(...Je.errors),oe=oe||Je.valid,Je.valid&&et.push(Ce)}oe?te.length=Pe:te.splice(Pe,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:Re,error:"Instance does not match any subschemas."})}if(x!==void 0){let Re=`${s}/allOf`,Pe=te.length,oe=!0;for(let se=0;se<x.length;se++){let ce=x[se],Ce=Object.create(u),Je=oa(t,ce,r,n,o,p===!0?i:null,a,`${Re}/${se}`,Ce);te.push(...Je.errors),oe=oe&&Je.valid,Je.valid&&et.push(Ce)}oe?te.length=Pe:te.splice(Pe,0,{instanceLocation:a,keyword:"allOf",keywordLocation:Re,error:"Instance does not match every subschema."})}if(O!==void 0){let Re=`${s}/oneOf`,Pe=te.length,oe=O.filter((se,ce)=>{let Ce=Object.create(u),Je=oa(t,se,r,n,o,p===!0?i:null,a,`${Re}/${ce}`,Ce);return te.push(...Je.errors),Je.valid&&et.push(Ce),Je.valid}).length;oe===1?te.length=Pe:te.splice(Pe,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:Re,error:`Instance does not match exactly one subschema (${oe} matches).`})}if((c==="object"||c==="array")&&Object.assign(u,...et),P!==void 0){let Re=`${s}/if`;if(oa(t,P,r,n,o,i,a,Re,u).valid){if(E!==void 0){let oe=oa(t,E,r,n,o,i,a,`${s}/then`,u);oe.valid||te.push({instanceLocation:a,keyword:"if",keywordLocation:Re,error:'Instance does not match "then" schema.'},...oe.errors)}}else if(A!==void 0){let oe=oa(t,A,r,n,o,i,a,`${s}/else`,u);oe.valid||te.push({instanceLocation:a,keyword:"if",keywordLocation:Re,error:'Instance does not match "else" schema.'},...oe.errors)}}if(c==="object"){if(g!==void 0)for(let se of g)se in t||te.push({instanceLocation:a,keyword:"required",keywordLocation:`${s}/required`,error:`Instance does not have required property "${se}".`});let Re=Object.keys(t);if(k!==void 0&&Re.length<k&&te.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${k} properties.`}),z!==void 0&&Re.length>z&&te.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${z} properties.`}),V!==void 0){let se=`${s}/propertyNames`;for(let ce in t){let Ce=`${a}/${wm(ce)}`,Je=oa(ce,V,r,n,o,i,Ce,se);Je.valid||te.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:se,error:`Property name "${ce}" does not match schema.`},...Je.errors)}}if(Q!==void 0){let se=`${s}/dependantRequired`;for(let ce in Q)if(ce in t){let Ce=Q[ce];for(let Je of Ce)Je in t||te.push({instanceLocation:a,keyword:"dependentRequired",keywordLocation:se,error:`Instance has "${ce}" but does not have "${Je}".`})}}if(J!==void 0)for(let se in J){let ce=`${s}/dependentSchemas`;if(se in t){let Ce=oa(t,J[se],r,n,o,i,a,`${ce}/${wm(se)}`,u);Ce.valid||te.push({instanceLocation:a,keyword:"dependentSchemas",keywordLocation:ce,error:`Instance has "${se}" but does not match dependant schema.`},...Ce.errors)}}if(D!==void 0){let se=`${s}/dependencies`;for(let ce in D)if(ce in t){let Ce=D[ce];if(Array.isArray(Ce))for(let Je of Ce)Je in t||te.push({instanceLocation:a,keyword:"dependencies",keywordLocation:se,error:`Instance has "${ce}" but does not have "${Je}".`});else{let Je=oa(t,Ce,r,n,o,i,a,`${se}/${wm(ce)}`);Je.valid||te.push({instanceLoLine truncated
- `)}`,new Error(ce)}let oe=`${s}/$ref`,se=oa(t,Pe,r,n,o,i,a,oe,u);if(se.valid||te.push({instanceLocation:a,keyword:"$ref",keywordLocation:oe,error:"A subschema had errors."},...se.errors),r==="4"||r==="7")return{valid:te.length===0,errors:te}}if(Array.isArray(m)){let Re=m.length,Pe=!1;for(let oe=0;oe<Re;oe++)if(c===m[oe]||m[oe]==="integer"&&c==="number"&&t%1===0&&t===t){Pe=!0;break}Pe||te.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)&&te.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m}".`}):m!==void 0&&c!==m&&te.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m}".`});if(h!==void 0&&(c==="object"||c==="array"?RC(t,h)||te.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):t!==h&&te.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),b!==void 0&&(c==="object"||c==="array"?b.some(Re=>RC(t,Re))||te.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`}):b.some(Re=>t===Re)||te.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`})),y!==void 0){let Re=`${s}/not`;oa(t,y,r,n,o,i,a,Re).valid&&te.push({instanceLocation:a,keyword:"not",keywordLocation:Re,error:'Instance matched "not" schema.'})}let et=[];if(S!==void 0){let Re=`${s}/anyOf`,Pe=te.length,oe=!1;for(let se=0;se<S.length;se++){let ce=S[se],Ce=Object.create(u),Je=oa(t,ce,r,n,o,p===!0?i:null,a,`${Re}/${se}`,Ce);te.push(...Je.errors),oe=oe||Je.valid,Je.valid&&et.push(Ce)}oe?te.length=Pe:te.splice(Pe,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:Re,error:"Instance does not match any subschemas."})}if(x!==void 0){let Re=`${s}/allOf`,Pe=te.length,oe=!0;for(let se=0;se<x.length;se++){let ce=x[se],Ce=Object.create(u),Je=oa(t,ce,r,n,o,p===!0?i:null,a,`${Re}/${se}`,Ce);te.push(...Je.errors),oe=oe&&Je.valid,Je.valid&&et.push(Ce)}oe?te.length=Pe:te.splice(Pe,0,{instanceLocation:a,keyword:"allOf",keywordLocation:Re,error:"Instance does not match every subschema."})}if(O!==void 0){let Re=`${s}/oneOf`,Pe=te.length,oe=O.filter((se,ce)=>{let Ce=Object.create(u),Je=oa(t,se,r,n,o,p===!0?i:null,a,`${Re}/${ce}`,Ce);return te.push(...Je.errors),Je.valid&&et.push(Ce),Je.valid}).length;oe===1?te.length=Pe:te.splice(Pe,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:Re,error:`Instance does not match exactly one subschema (${oe} matches).`})}if((c==="object"||c==="array")&&Object.assign(u,...et),P!==void 0){let Re=`${s}/if`;if(oa(t,P,r,n,o,i,a,Re,u).valid){if(E!==void 0){let oe=oa(t,E,r,n,o,i,a,`${s}/then`,u);oe.valid||te.push({instanceLocation:a,keyword:"if",keywordLocation:Re,error:'Instance does not match "then" schema.'},...oe.errors)}}else if(A!==void 0){let oe=oa(t,A,r,n,o,i,a,`${s}/else`,u);oe.valid||te.push({instanceLocation:a,keyword:"if",keywordLocation:Re,error:'Instance does not match "else" schema.'},...oe.errors)}}if(c==="object"){if(g!==void 0)for(let se of g)se in t||te.push({instanceLocation:a,keyword:"required",keywordLocation:`${s}/required`,error:`Instance does not have required property "${se}".`});let Re=Object.keys(t);if(k!==void 0&&Re.length<k&&te.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${k} properties.`}),z!==void 0&&Re.length>z&&te.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${z} properties.`}),V!==void 0){let se=`${s}/propertyNames`;for(let ce in t){let Ce=`${a}/${wm(ce)}`,Je=oa(ce,V,r,n,o,i,Ce,se);Je.valid||te.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:se,error:`Property name "${ce}" does not match schema.`},...Je.errors)}}if(Q!==void 0){let se=`${s}/dependantRequired`;for(let ce in Q)if(ce in t){let Ce=Q[ce];for(let Je of Ce)Je in t||te.push({instanceLocation:a,keyword:"dependentRequired",keywordLocation:se,error:`Instance has "${ce}" but does not have "${Je}".`})}}if(J!==void 0)for(let se in J){let ce=`${s}/dependentSchemas`;if(se in t){let Ce=oa(t,J[se],r,n,o,i,a,`${ce}/${wm(se)}`,u);Ce.valid||te.push({instanceLocation:a,keyword:"dependentSchemas",keywordLocation:ce,error:`Instance has "${se}" but does not match dependant schema.`},...Ce.errors)}}if(D!==void 0){let se=`${s}/dependencies`;for(let ce in D)if(ce in t){let Ce=D[ce];if(Array.isArray(Ce))for(let Je of Ce)Je in t||te.push({instanceLocation:a,keyword:"dependencies",keywordLocation:se,error:`Instance has "${ce}" but does not have "${Je}".`});else{let Je=oa(t,Ce,r,n,o,i,a,`${se}/${wm(ce)}`);Je.valid||te.push({instanceLoLine truncated
"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
@@ -84,34 +84,34 @@ Here is the JSON Schema instance your output must adhere to. Include the enclosi
\`\`\`json
${JSON.stringify(So(this.schema))}
\`\`\`
`}async parse(e){try{let n=(e.includes("```")?e.trim().split(/```(?:json)?/)[1]:e.trim()).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(o,i)=>`"${i.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await this.schema.parseAsync(JSON.parse(n))}catch(r){throw new vm(`Failed to parse. Text: "${e}". Error: ${r}`,e)}}}});var mhe=w(()=>{Jpe()});var Ac,hhe=w(()=>{$E();mhe();ime();Ac=class extends AR{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}static lc_name(){return"JsonOutputParser"}_diff(e,r){if(r)return e?dG(e,r):[{op:"replace",path:"",value:r}]}async parsePartialResult(e){return ome(e[0].text)}async parse(e){return ome(e,JSON.parse)}getFormatInstructions(){return""}}});var vHe=w(()=>{});var wHe=w(()=>{$E();mhe();vHe()});var SHe=w(()=>{eF();gHe();yHe();bHe();_He();$E();hhe();wHe()});var gy=w(()=>{SHe()});var V2,tF,rF,HG,W2=w(()=>{yR();R2();NE();V2=class extends gp{},tF=class extends V2{static lc_name(){return"StringPromptValue"}constructor(e){super({value:e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.value=e}toString(){return this.value}toChatMessages(){return[new Os(this.value)]}},rF=class extends V2{static lc_name(){return"ChatPromptValue"}constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.messages=e.messages}toString(){return Rf(this.messages)}toChatMessages(){return this.messages}},HG=class extends V2{static lc_name(){return"ImagePromptValue"}constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"imageUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new Os({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}}});var jC,K2=w(()=>{W2();nF();jC=class extends Kb{async formatPromptValue(e){let r=await this.format(e);return new tF(r)}}});function yhe(t){return typeof t=="function"}function rsr(t){return iF(t)?"array":typeof t}function ghe(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function xHe(t,e){return t!=null&&typeof t=="object"&&e in t}function nsr(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}function isr(t,e){return osr.call(t,e)}function ssr(t){return!isr(asr,t)}function lsr(t){return String(t).replace(/[&<>"'`=\/]/g,function(r){return usr[r]})}function msr(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(A){if(typeof A=="string"&&(A=A.split(dsr,2)),!iF(A)||A.length!==2)throw new Error("Invalid tags: "+A);d=new RegExp(ghe(A[0])+"\\s*"),f=new RegExp("\\s*"+ghe(A[1])),p=new RegExp("\\s*"+ghe("}"+A[1]))}m(e||Ah.tags);for(var h=new J2(t),b,g,y,S,x,O;!h.eos();){if(b=h.pos,y=h.scanUntil(d),y)for(var P=0,E=y.length;P<E;++P)S=y.charAt(P),ssr(S)?(i.push(o.length),u+=S):(s=!0,r=!0,u+=" "),o.push(["text",S,b,b+1]),b+=1,S===`
`&&(c(),u="",l=0,r=!1);if(!h.scan(d))break;if(a=!0,g=h.scan(psr)||"name",h.scan(csr),g==="="?(y=h.scanUntil(CHe),h.scan(CHe),h.scanUntil(f)):g==="{"?(y=h.scanUntil(p),h.scan(fsr),h.scanUntil(f),g="&"):y=h.scanUntil(f),!h.scan(f))throw new Error("Unclosed tag at "+h.pos);if(g==">"?x=[g,y,b,h.pos,u,l,r]:x=[g,y,b,h.pos],l++,o.push(x),g==="#"||g==="^")n.push(x);else if(g==="/"){if(O=n.pop(),!O)throw new Error('Unopened section "'+y+'" at '+b);if(O[1]!==y)throw new Error('Unclosed section "'+O[1]+'" at '+b)}else g==="name"||g==="{"||g==="&"?s=!0:g==="="&&m(y)}if(c(),O=n.pop(),O)throw new Error('Unclosed section "'+O[1]+'" at '+h.pos);return gsr(hsr(o))}function hsr(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 gsr(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 J2(t){this.string=t,this.tail=t,this.pos=0}function oF(t,e){this.view=t,this.cache={".":this.view},this.parent=e}function Lf(){this.templateCache={_cache:{},set:function(e,r){this._cache[e]=r},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}var tsr,iF,osr,asr,usr,csr,dsr,CHe,fsr,psr,Ah,G2,VG,OHe=w(()=>{tsr=Object.prototype.toString,iF=Array.isArray||function(e){return tsr.call(e)==="[object Array]"};osr=RegExp.prototype.test;asr=/\S/;usr={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};csr=/\s*/,dsr=/\s+/,CHe=/\s*=/,fsr=/\s*\}/,psr=/#|\^|\/|>|\{|&|=|!/;J2.prototype.eos=function(){return this.tail===""};J2.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};J2.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};oF.prototype.push=function(e){return new oF(e,this)};oF.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=xHe(i,a[s])||nsr(i,a[s])),i=i[a[s++]];else i=o.view[e],u=xHe(o.view,e);if(u){n=i;break}o=o.parent}r[e]=n}return yhe(n)&&(n=n.call(this.view)),n};Lf.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};Lf.prototype.parse=function(e,r){var n=this.templateCache,o=e+":"+(r||Ah.tags).join(":"),i=typeof n<"u",a=i?n.get(o):void 0;return a==null&&(a=msr(e,r),i&&n.set(o,a)),a};Lf.prototype.render=function(e,r,n,o){var i=this.getConfigTags(o),a=this.parse(e,i),s=r instanceof oF?r:new oF(r,void 0);return this.renderTokens(a,s,n,e,o)};Lf.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};Lf.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(iF(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(yhe(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}};Lf.prototype.renderInverted=function(e,r,n,o,i){var a=r.lookup(e[1]);if(!a||iF(a)&&a.length===0)return this.renderTokens(e[4],r,n,o,i)};Lf.prototype.indentPartial=function(e,r,n){for(var o=r.replace(/[^ \t]/g,""),i=e.split(`
`}async parse(e){try{let n=(e.includes("```")?e.trim().split(/```(?:json)?/)[1]:e.trim()).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(o,i)=>`"${i.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await this.schema.parseAsync(JSON.parse(n))}catch(r){throw new vm(`Failed to parse. Text: "${e}". Error: ${r}`,e)}}}});var yhe=w(()=>{Xpe()});var Ac,bhe=w(()=>{$E();yhe();ume();Ac=class extends AR{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}static lc_name(){return"JsonOutputParser"}_diff(e,r){if(r)return e?fG(e,r):[{op:"replace",path:"",value:r}]}async parsePartialResult(e){return sme(e[0].text)}async parse(e){return sme(e,JSON.parse)}getFormatInstructions(){return""}}});var SHe=w(()=>{});var xHe=w(()=>{$E();yhe();SHe()});var CHe=w(()=>{tF();bHe();_He();vHe();wHe();$E();bhe();xHe()});var gy=w(()=>{CHe()});var W2,rF,nF,VG,K2=w(()=>{yR();j2();NE();W2=class extends gp{},rF=class extends W2{static lc_name(){return"StringPromptValue"}constructor(e){super({value:e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.value=e}toString(){return this.value}toChatMessages(){return[new Os(this.value)]}},nF=class extends W2{static lc_name(){return"ChatPromptValue"}constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.messages=e.messages}toString(){return Rf(this.messages)}toChatMessages(){return this.messages}},VG=class extends W2{static lc_name(){return"ImagePromptValue"}constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"imageUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new Os({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}}});var NC,G2=w(()=>{K2();oF();NC=class extends Kb{async formatPromptValue(e){let r=await this.format(e);return new rF(r)}}});function vhe(t){return typeof t=="function"}function ssr(t){return aF(t)?"array":typeof t}function _he(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function OHe(t,e){return t!=null&&typeof t=="object"&&e in t}function usr(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}function csr(t,e){return lsr.call(t,e)}function fsr(t){return!csr(dsr,t)}function msr(t){return String(t).replace(/[&<>"'`=\/]/g,function(r){return psr[r]})}function _sr(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(A){if(typeof A=="string"&&(A=A.split(gsr,2)),!aF(A)||A.length!==2)throw new Error("Invalid tags: "+A);d=new RegExp(_he(A[0])+"\\s*"),f=new RegExp("\\s*"+_he(A[1])),p=new RegExp("\\s*"+_he("}"+A[1]))}m(e||Ah.tags);for(var h=new Y2(t),b,g,y,S,x,O;!h.eos();){if(b=h.pos,y=h.scanUntil(d),y)for(var P=0,E=y.length;P<E;++P)S=y.charAt(P),fsr(S)?(i.push(o.length),u+=S):(s=!0,r=!0,u+=" "),o.push(["text",S,b,b+1]),b+=1,S===`
`&&(c(),u="",l=0,r=!1);if(!h.scan(d))break;if(a=!0,g=h.scan(bsr)||"name",h.scan(hsr),g==="="?(y=h.scanUntil(PHe),h.scan(PHe),h.scanUntil(f)):g==="{"?(y=h.scanUntil(p),h.scan(ysr),h.scanUntil(f),g="&"):y=h.scanUntil(f),!h.scan(f))throw new Error("Unclosed tag at "+h.pos);if(g==">"?x=[g,y,b,h.pos,u,l,r]:x=[g,y,b,h.pos],l++,o.push(x),g==="#"||g==="^")n.push(x);else if(g==="/"){if(O=n.pop(),!O)throw new Error('Unopened section "'+y+'" at '+b);if(O[1]!==y)throw new Error('Unclosed section "'+O[1]+'" at '+b)}else g==="name"||g==="{"||g==="&"?s=!0:g==="="&&m(y)}if(c(),O=n.pop(),O)throw new Error('Unclosed section "'+O[1]+'" at '+h.pos);return wsr(vsr(o))}function vsr(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 wsr(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 Y2(t){this.string=t,this.tail=t,this.pos=0}function iF(t,e){this.view=t,this.cache={".":this.view},this.parent=e}function Lf(){this.templateCache={_cache:{},set:function(e,r){this._cache[e]=r},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}var asr,aF,lsr,dsr,psr,hsr,gsr,PHe,ysr,bsr,Ah,J2,WG,EHe=w(()=>{asr=Object.prototype.toString,aF=Array.isArray||function(e){return asr.call(e)==="[object Array]"};lsr=RegExp.prototype.test;dsr=/\S/;psr={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};hsr=/\s*/,gsr=/\s+/,PHe=/\s*=/,ysr=/\s*\}/,bsr=/#|\^|\/|>|\{|&|=|!/;Y2.prototype.eos=function(){return this.tail===""};Y2.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};Y2.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};iF.prototype.push=function(e){return new iF(e,this)};iF.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=OHe(i,a[s])||usr(i,a[s])),i=i[a[s++]];else i=o.view[e],u=OHe(o.view,e);if(u){n=i;break}o=o.parent}r[e]=n}return vhe(n)&&(n=n.call(this.view)),n};Lf.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};Lf.prototype.parse=function(e,r){var n=this.templateCache,o=e+":"+(r||Ah.tags).join(":"),i=typeof n<"u",a=i?n.get(o):void 0;return a==null&&(a=_sr(e,r),i&&n.set(o,a)),a};Lf.prototype.render=function(e,r,n,o){var i=this.getConfigTags(o),a=this.parse(e,i),s=r instanceof iF?r:new iF(r,void 0);return this.renderTokens(a,s,n,e,o)};Lf.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};Lf.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(aF(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(vhe(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}};Lf.prototype.renderInverted=function(e,r,n,o,i){var a=r.lookup(e[1]);if(!a||aF(a)&&a.length===0)return this.renderTokens(e[4],r,n,o,i)};Lf.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(`
`)};Lf.prototype.renderPartial=function(e,r,n,o){if(n){var i=this.getConfigTags(o),a=yhe(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)}}};Lf.prototype.unescapedValue=function(e,r){var n=r.lookup(e[1]);if(n!=null)return n};Lf.prototype.escapedValue=function(e,r,n){var o=this.getConfigEscape(n)||Ah.escape,i=r.lookup(e[1]);if(i!=null)return typeof i=="number"&&o===Ah.escape?String(i):o(i)};Lf.prototype.rawValue=function(e){return e[1]};Lf.prototype.getConfigTags=function(e){return iF(e)?e:e&&typeof e=="object"?e.tags:void 0};Lf.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!iF(e))return e.escape};Ah={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){G2.templateCache=t},get templateCache(){return G2.templateCache}},G2=new Lf;Ah.clearCache=function(){return G2.clearCache()};Ah.parse=function(e,r){return G2.parse(e,r)};Ah.render=function(e,r,n,o){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+rsr(e)+'" was given as the first argument for mustache#render(template, view, partials)');return G2.render(e,r,n,o)};Ah.escape=lsr;Ah.Scanner=J2;Ah.Context=oF;Ah.Writer=Lf;VG=Ah});function PHe(){VG.escape=t=>t}var Y2,ysr,WG,bsr,_sr,bhe,vsr,Sp,Z2,IR,MR=w(()=>{OHe();I2();Y2=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},ysr=t=>t.map(e=>e[0]==="name"?{type:"variable",name:e[1].includes(".")?e[1].split(".")[0]:e[1]}:["#","&","^",">"].includes(e[0])?{type:"variable",name:e[1]}:{type:"literal",text:e[1]}),WG=t=>{PHe();let e=VG.parse(t);return ysr(e)},bsr=(t,e)=>Y2(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},""),_sr=(t,e)=>(PHe(),VG.render(t,e)),bhe={"f-string":bsr,mustache:_sr},vsr={"f-string":Y2,mustache:WG},Sp=(t,e,r)=>{try{return bhe[e](t,r)}catch(n){throw ME(n,"INVALID_PROMPT_INPUT")}},Z2=(t,e)=>vsr[e](t),IR=(t,e,r)=>{if(!(e in bhe)){let n=Object.keys(bhe);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")Sp(o.text,e,n);else if(o.type==="image_url")if(typeof o.image_url=="string")Sp(o.image_url,e,n);else{let i=o.image_url.url;Sp(i,e,n)}else throw new Error(`Invalid message template received. ${JSON.stringify(o,null,2)}`)}):Sp(t,e,n)}catch(n){throw new Error(`Invalid prompt schema: ${n.message}`)}}});var _he={};Cf(_he,{PromptTemplate:()=>Dd});var Dd,aF=w(()=>{K2();MR();Dd=class t extends jC{static lc_name(){return"PromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"additionalContentFields",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e.templateFormat==="mustache"&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),IR(this.template,this.templateFormat,r)}}_getPromptType(){return"prompt"}async format(e){let r=await this.mergePartialAndUserVariables(e);return Sp(this.template,this.templateFormat,r)}static fromExamples(e,r,n,o=`
`)};Lf.prototype.renderPartial=function(e,r,n,o){if(n){var i=this.getConfigTags(o),a=vhe(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)}}};Lf.prototype.unescapedValue=function(e,r){var n=r.lookup(e[1]);if(n!=null)return n};Lf.prototype.escapedValue=function(e,r,n){var o=this.getConfigEscape(n)||Ah.escape,i=r.lookup(e[1]);if(i!=null)return typeof i=="number"&&o===Ah.escape?String(i):o(i)};Lf.prototype.rawValue=function(e){return e[1]};Lf.prototype.getConfigTags=function(e){return aF(e)?e:e&&typeof e=="object"?e.tags:void 0};Lf.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!aF(e))return e.escape};Ah={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){J2.templateCache=t},get templateCache(){return J2.templateCache}},J2=new Lf;Ah.clearCache=function(){return J2.clearCache()};Ah.parse=function(e,r){return J2.parse(e,r)};Ah.render=function(e,r,n,o){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+ssr(e)+'" was given as the first argument for mustache#render(template, view, partials)');return J2.render(e,r,n,o)};Ah.escape=msr;Ah.Scanner=Y2;Ah.Context=iF;Ah.Writer=Lf;WG=Ah});function THe(){WG.escape=t=>t}var Z2,Ssr,KG,xsr,Csr,whe,Osr,Sp,X2,IR,MR=w(()=>{EHe();M2();Z2=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},Ssr=t=>t.map(e=>e[0]==="name"?{type:"variable",name:e[1].includes(".")?e[1].split(".")[0]:e[1]}:["#","&","^",">"].includes(e[0])?{type:"variable",name:e[1]}:{type:"literal",text:e[1]}),KG=t=>{THe();let e=WG.parse(t);return Ssr(e)},xsr=(t,e)=>Z2(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},""),Csr=(t,e)=>(THe(),WG.render(t,e)),whe={"f-string":xsr,mustache:Csr},Osr={"f-string":Z2,mustache:KG},Sp=(t,e,r)=>{try{return whe[e](t,r)}catch(n){throw ME(n,"INVALID_PROMPT_INPUT")}},X2=(t,e)=>Osr[e](t),IR=(t,e,r)=>{if(!(e in whe)){let n=Object.keys(whe);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")Sp(o.text,e,n);else if(o.type==="image_url")if(typeof o.image_url=="string")Sp(o.image_url,e,n);else{let i=o.image_url.url;Sp(i,e,n)}else throw new Error(`Invalid message template received. ${JSON.stringify(o,null,2)}`)}):Sp(t,e,n)}catch(n){throw new Error(`Invalid prompt schema: ${n.message}`)}}});var She={};Cf(She,{PromptTemplate:()=>Dd});var Dd,sF=w(()=>{G2();MR();Dd=class t extends NC{static lc_name(){return"PromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"additionalContentFields",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e.templateFormat==="mustache"&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),IR(this.template,this.templateFormat,r)}}_getPromptType(){return"prompt"}async format(e){let r=await this.mergePartialAndUserVariables(e);return Sp(this.template,this.templateFormat,r)}static fromExamples(e,r,n,o=`
`,i=""){let a=[i,...e,r].join(o);return new t({inputVariables:n,template:a})}static fromTemplate(e,r){let{templateFormat:n="f-string",...o}=r??{},i=new Set;return Z2(e,n).forEach(a=>{a.type==="variable"&&i.add(a.name)}),new t({inputVariables:[...i],templateFormat:n,template:e,...o})}async partial(e){let r=this.inputVariables.filter(i=>!(i in e)),n={...this.partialVariables??{},...e},o={...this,inputVariables:r,partialVariables:n};return new t(o)}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(e){if(!e.template)throw new Error("Prompt template must have a template");return new t({inputVariables:e.input_variables,template:e.template,templateFormat:e.template_format})}}});var sF,vhe=w(()=>{W2();nF();MR();sF=class t extends Kb{static lc_name(){return"ImagePromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","image"]}),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"additionalContentFields",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.template=e.template,this.templateFormat=e.templateFormat??this.templateFormat,this.validateTemplate=e.validateTemplate??this.validateTemplate,this.additionalContentFields=e.additionalContentFields,this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),IR([{type:"image_url",image_url:this.template}],this.templateFormat,r)}}_getPromptType(){return"prompt"}async partial(e){let r=this.inputVariables.filter(i=>!(i in e)),n={...this.partialVariables??{},...e},o={...this,inputVariables:r,partialVariables:n};return new t(o)}async format(e){let r={};for(let[a,s]of Object.entries(this.template))typeof s=="string"?r[a]=Sp(s,this.templateFormat,e):r[a]=s;let n=e.url||r.url,o=e.detail||r.detail;if(!n)throw new Error("Must provide either an image URL.");if(typeof n!="string")throw new Error("url must be a string.");let i={url:n};return o&&(i.detail=o),i}async formatPromptValue(e){let r=await this.format(e);return new HG(r)}}});function whe(t,e){let r=[];for(let n of Object.values(t))if(typeof n=="string")Z2(n,e).forEach(o=>{o.type==="variable"&&r.push(o.name)});else if(Array.isArray(n))for(let o of n)typeof o=="string"?Z2(o,e).forEach(i=>{i.type==="variable"&&r.push(i.name)}):typeof o=="object"&&r.push(...whe(o,e));else typeof n=="object"&&n!==null&&r.push(...whe(n,e));return Array.from(new Set(r))}function She(t,e,r){let n={};for(let[o,i]of Object.entries(t))if(typeof i=="string")n[o]=Sp(i,r,e);else if(Array.isArray(i)){let a=[];for(let s of i)typeof s=="string"?a.push(Sp(s,r,e)):typeof s=="object"&&a.push(She(s,e,r));n[o]=a}else typeof i=="object"&&i!==null?n[o]=She(i,e,r):n[o]=i;return n}var X2,xhe=w(()=>{Df();MR();X2=class extends xn{static lc_name(){return"DictPromptTemplate"}constructor(e){let r=e.templateFormat??"f-string",n=whe(e.template,r);super({inputVariables:n,...e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","dict"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.template=e.template,this.templateFormat=r,this.inputVariables=n}async format(e){return She(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:"prompt"})}}});function wsr(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function Ssr(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 xsr(t){return typeof t.formatMessages=="function"}function Csr(t,e){if(xsr(t)||Ph(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 i=o.slice(2,-2);return new Gb({variableName:i,optional:!0})}else if(typeof o=="string"&&o[0]==="{"&&o[o.length-1]==="}"){let i=o.slice(1,-1);return new Gb({variableName:i,optiona Line truncated
`,i=""){let a=[i,...e,r].join(o);return new t({inputVariables:n,template:a})}static fromTemplate(e,r){let{templateFormat:n="f-string",...o}=r??{},i=new Set;return X2(e,n).forEach(a=>{a.type==="variable"&&i.add(a.name)}),new t({inputVariables:[...i],templateFormat:n,template:e,...o})}async partial(e){let r=this.inputVariables.filter(i=>!(i in e)),n={...this.partialVariables??{},...e},o={...this,inputVariables:r,partialVariables:n};return new t(o)}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(e){if(!e.template)throw new Error("Prompt template must have a template");return new t({inputVariables:e.input_variables,template:e.template,templateFormat:e.template_format})}}});var uF,xhe=w(()=>{K2();oF();MR();uF=class t extends Kb{static lc_name(){return"ImagePromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","image"]}),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"additionalContentFields",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.template=e.template,this.templateFormat=e.templateFormat??this.templateFormat,this.validateTemplate=e.validateTemplate??this.validateTemplate,this.additionalContentFields=e.additionalContentFields,this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),IR([{type:"image_url",image_url:this.template}],this.templateFormat,r)}}_getPromptType(){return"prompt"}async partial(e){let r=this.inputVariables.filter(i=>!(i in e)),n={...this.partialVariables??{},...e},o={...this,inputVariables:r,partialVariables:n};return new t(o)}async format(e){let r={};for(let[a,s]of Object.entries(this.template))typeof s=="string"?r[a]=Sp(s,this.templateFormat,e):r[a]=s;let n=e.url||r.url,o=e.detail||r.detail;if(!n)throw new Error("Must provide either an image URL.");if(typeof n!="string")throw new Error("url must be a string.");let i={url:n};return o&&(i.detail=o),i}async formatPromptValue(e){let r=await this.format(e);return new VG(r)}}});function Che(t,e){let r=[];for(let n of Object.values(t))if(typeof n=="string")X2(n,e).forEach(o=>{o.type==="variable"&&r.push(o.name)});else if(Array.isArray(n))for(let o of n)typeof o=="string"?X2(o,e).forEach(i=>{i.type==="variable"&&r.push(i.name)}):typeof o=="object"&&r.push(...Che(o,e));else typeof n=="object"&&n!==null&&r.push(...Che(n,e));return Array.from(new Set(r))}function Ohe(t,e,r){let n={};for(let[o,i]of Object.entries(t))if(typeof i=="string")n[o]=Sp(i,r,e);else if(Array.isArray(i)){let a=[];for(let s of i)typeof s=="string"?a.push(Sp(s,r,e)):typeof s=="object"&&a.push(Ohe(s,e,r));n[o]=a}else typeof i=="object"&&i!==null?n[o]=Ohe(i,e,r):n[o]=i;return n}var Q2,Phe=w(()=>{Df();MR();Q2=class extends Cn{static lc_name(){return"DictPromptTemplate"}constructor(e){let r=e.templateFormat??"f-string",n=Che(e.template,r);super({inputVariables:n,...e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","dict"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.template=e.template,this.templateFormat=r,this.inputVariables=n}async format(e){return Ohe(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:"prompt"})}}});function Psr(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function Esr(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 Tsr(t){return typeof t.formatMessages=="function"}function Asr(t,e){if(Tsr(t)||Ph(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 i=o.slice(2,-2);return new Gb({variableName:i,optional:!0})}else if(typeof o=="string"&&o[0]==="{"&&o[o.length-1]==="}"){let i=o.slice(1,-1);return new Gb({variableName:i,optiona Line truncated
`));throw a.name="InputFormatError",a.lc_error_code=o.lc_error_code,a}return n}},Che=class extends Q2{constructor(e){"prompt"in e||(e={prompt:e}),super(e),Object.defineProperty(this,"prompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}},e4=class extends Kb{constructor(e){super(e)}async format(e){return(await this.formatPromptValue(e)).toString()}async formatPromptValue(e){let r=await this.formatMessages(e);return new rF(r)}},Ohe=class extends Che{static lc_name(){return"ChatMessagePromptTemplate"}constructor(e,r){"prompt"in e||(e={prompt:e,role:r}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}async format(e){return new Cs(await this.prompt.format(e),this.role)}static fromTemplate(e,r,n){return new this(Dd.fromTemplate(e,{templateFormat:n?.templateFormat}),r)}};t4=class extends Q2{static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}constructor(e,r){if("prompt"in e||(e={prompt:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","chat"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"additionalOptions",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"prompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"messageClass",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chatMessageClass",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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}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(Dd.fromTemplate(e,r));let n=[];for(let o of e)if(typeof o=="string")n.push(Dd.fromTemplate(o,r));else if(o!==null)if(wsr(o)){let i="";typeof o.text=="string"&&(i=o.text??"");let a={...r,additionalContentFields:o};n.push(Dd.fromTemplate(i,a))}else if(Ssr(o)){let i=o.image_url??"",a,s=[];if(typeof i=="string"){let u;r?.templateFormat==="mustache"?u=WG(i):u=Y2(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.
`));throw a.name="InputFormatError",a.lc_error_code=o.lc_error_code,a}return n}},Ehe=class extends e4{constructor(e){"prompt"in e||(e={prompt:e}),super(e),Object.defineProperty(this,"prompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}},t4=class extends Kb{constructor(e){super(e)}async format(e){return(await this.formatPromptValue(e)).toString()}async formatPromptValue(e){let r=await this.formatMessages(e);return new nF(r)}},The=class extends Ehe{static lc_name(){return"ChatMessagePromptTemplate"}constructor(e,r){"prompt"in e||(e={prompt:e,role:r}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}async format(e){return new Cs(await this.prompt.format(e),this.role)}static fromTemplate(e,r,n){return new this(Dd.fromTemplate(e,{templateFormat:n?.templateFormat}),r)}};r4=class extends e4{static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}constructor(e,r){if("prompt"in e||(e={prompt:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","chat"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"additionalOptions",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"prompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"messageClass",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chatMessageClass",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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}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(Dd.fromTemplate(e,r));let n=[];for(let o of e)if(typeof o=="string")n.push(Dd.fromTemplate(o,r));else if(o!==null)if(Psr(o)){let i="";typeof o.text=="string"&&(i=o.text??"");let a={...r,additionalContentFields:o};n.push(Dd.fromTemplate(i,a))}else if(Esr(o)){let i=o.image_url??"",a,s=[];if(typeof i=="string"){let u;r?.templateFormat==="mustache"?u=KG(i):u=Z2(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 sF({template:i,inputVariables:s,templateFormat:r?.templateFormat,additionalContentFields:o})}else if(typeof i=="object"){if("url"in i){let u;r?.templateFormat==="mustache"?u=WG(i.url):u=Y2(i.url),s=u.flatMap(l=>l.type==="variable"?[l.name]:[])}else s=[];a=new sF({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 X2({template:o,templateFormat:r?.templateFormat}));return new this({prompt:n,additionalOptions:r})}async format(e){if(this.prompt instanceof jC){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 jC){let i=await n.format(o),a;"additionalContentFields"in n&&(a=n.additionalContentFields),r.push({...a,type:"text",text:i})}else if(n instanceof sF){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 X2){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)]}},Jb=class extends t4{static _messageClass(){return Os}static lc_name(){return"HumanMessagePromptTemplate"}},Phe=class extends t4{static _messageClass(){return gn}static lc_name(){return"AIMessagePromptTemplate"}},BE=class extends t4{static _messageClass(){return EC}static lc_name(){return"SystemMessagePromptTemplate"}};xp=class t extends e4{static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}constructor(e){if(super(e),Object.defineProperty(this,"promptMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),e.templateFormat==="mustache"&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){let r=new Set;for(let s of this.promptMessages)if(!(s instanceof Sl))for(let u of s.inputVariables)r.add(u);let n=this.inputVariables,o=new Set(this.partialVariables?n.concat(Object.keys(this.partialVariables)):n),i=new Set([...o].filter(s=>!r.has(s)));if(i.size>0)throw new Error(`Input variables \`${[...i]}\` are not used in any of the prompt messages.`);let a=new Set([...r].filter(s=>!o.has(s)));if(a.size>0)throw new Error(`Input variables \`${[...a]}\` are used in prompt messages but not in the prompt template.`)}}_getPromptType(){return"chat"}async _parseImagePrompts(e,r){if(typeof e.content=="string")return e;let n=await Promise.all(e.content.map(async o=>{if(o.type!=="image_url")return o;let i="";typeof o.image_url=="string"?i=o.image_url:i=o.image_url.url;let s=await Dd.fromTemplate(i,{templateFormat:this.templateFormat}).format(r);return typeof o.image_url!="string"&&"url"in o.image_url?o.image_url.url=s:o.image_url=s,o}));return e.content=n,e}async formatMessages(e){let r=await this.mergePartialAndUserVariables(e),n=[];for(let o of this.promptMessages)if(o instanceof Sl)n.push(await this._parseImagePrompts(o,r));else{let i=o.inputVariables.reduce((s,u)=>{if(!(u in r)&&!(Osr(o)&&o.optional))throw ME(new Error(`Missing value for input variable \`${u.toString()}\``),"INVALID_PROMPT_INPUT");return s[u]=r[u],s},{}),a=await o.formatMessages(i);n=n.concat(a)}return n}async partial(e){let r=this.inputVariables.filter(i=>!(i in e)),n={...this.partialVariables??{},...e},o={...this,inputVariables:r,partialVariables:n};return new t(o)}static fromTemplate(e,r){let n=Dd.fromTemplate(e,r),o=new Jb({prompt:n});return this.fromMessages([o])}static fromMessages(e,r){let n=e.reduce((a,s)=>a.concat(s instanceof t?s.promptMessages:[Csr(s,r)]),[]),o=e.reduce((a,s)=>s instanceof t?Object.assign(a,s.partialVariables):a,Object.create(null)),i=new Set;for(let a of n)if(!(a instanceof Sl))for(let s of a.inputVariables)s in o||i.add(s);return new this({...r,inputVariables:[...i],promptMessages:n,partialVariables:o,templateFormat:r?.templateFormat})}static fromPromptMessages(e){return this.fromMessages(e)}}});var EHe={};Cf(EHe,{FewShotChatMessagePromptTemplate:()=>The,FewShotPromptTemplate:()=>Ehe});var Ehe,The,Ahe=w(()=>{K2();MR();aF();r4();Ehe=class t extends jC{constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"examples",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleSelector",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"examplePrompt",{enumerable:!0Line truncated
From: ${i}`);s=[l[0]]}else s=[];i={url:i},a=new uF({template:i,inputVariables:s,templateFormat:r?.templateFormat,additionalContentFields:o})}else if(typeof i=="object"){if("url"in i){let u;r?.templateFormat==="mustache"?u=KG(i.url):u=Z2(i.url),s=u.flatMap(l=>l.type==="variable"?[l.name]:[])}else s=[];a=new uF({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 Q2({template:o,templateFormat:r?.templateFormat}));return new this({prompt:n,additionalOptions:r})}async format(e){if(this.prompt instanceof NC){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 NC){let i=await n.format(o),a;"additionalContentFields"in n&&(a=n.additionalContentFields),r.push({...a,type:"text",text:i})}else if(n instanceof uF){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 Q2){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)]}},Jb=class extends r4{static _messageClass(){return Os}static lc_name(){return"HumanMessagePromptTemplate"}},Ahe=class extends r4{static _messageClass(){return gn}static lc_name(){return"AIMessagePromptTemplate"}},BE=class extends r4{static _messageClass(){return TC}static lc_name(){return"SystemMessagePromptTemplate"}};xp=class t extends t4{static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}constructor(e){if(super(e),Object.defineProperty(this,"promptMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),e.templateFormat==="mustache"&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){let r=new Set;for(let s of this.promptMessages)if(!(s instanceof Sl))for(let u of s.inputVariables)r.add(u);let n=this.inputVariables,o=new Set(this.partialVariables?n.concat(Object.keys(this.partialVariables)):n),i=new Set([...o].filter(s=>!r.has(s)));if(i.size>0)throw new Error(`Input variables \`${[...i]}\` are not used in any of the prompt messages.`);let a=new Set([...r].filter(s=>!o.has(s)));if(a.size>0)throw new Error(`Input variables \`${[...a]}\` are used in prompt messages but not in the prompt template.`)}}_getPromptType(){return"chat"}async _parseImagePrompts(e,r){if(typeof e.content=="string")return e;let n=await Promise.all(e.content.map(async o=>{if(o.type!=="image_url")return o;let i="";typeof o.image_url=="string"?i=o.image_url:i=o.image_url.url;let s=await Dd.fromTemplate(i,{templateFormat:this.templateFormat}).format(r);return typeof o.image_url!="string"&&"url"in o.image_url?o.image_url.url=s:o.image_url=s,o}));return e.content=n,e}async formatMessages(e){let r=await this.mergePartialAndUserVariables(e),n=[];for(let o of this.promptMessages)if(o instanceof Sl)n.push(await this._parseImagePrompts(o,r));else{let i=o.inputVariables.reduce((s,u)=>{if(!(u in r)&&!(Isr(o)&&o.optional))throw ME(new Error(`Missing value for input variable \`${u.toString()}\``),"INVALID_PROMPT_INPUT");return s[u]=r[u],s},{}),a=await o.formatMessages(i);n=n.concat(a)}return n}async partial(e){let r=this.inputVariables.filter(i=>!(i in e)),n={...this.partialVariables??{},...e},o={...this,inputVariables:r,partialVariables:n};return new t(o)}static fromTemplate(e,r){let n=Dd.fromTemplate(e,r),o=new Jb({prompt:n});return this.fromMessages([o])}static fromMessages(e,r){let n=e.reduce((a,s)=>a.concat(s instanceof t?s.promptMessages:[Asr(s,r)]),[]),o=e.reduce((a,s)=>s instanceof t?Object.assign(a,s.partialVariables):a,Object.create(null)),i=new Set;for(let a of n)if(!(a instanceof Sl))for(let s of a.inputVariables)s in o||i.add(s);return new this({...r,inputVariables:[...i],promptMessages:n,partialVariables:o,templateFormat:r?.templateFormat})}static fromPromptMessages(e){return this.fromMessages(e)}}});var AHe={};Cf(AHe,{FewShotChatMessagePromptTemplate:()=>Mhe,FewShotPromptTemplate:()=>Ihe});var Ihe,Mhe,Rhe=w(()=>{G2();MR();sF();n4();Ihe=class t extends NC{constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"examples",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleSelector",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"examplePrompt",{enumerable:!0Line truncated
`}),Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.assign(this,e),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 r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),IR(this.prefix+this.suffix,this.templateFormat,r)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(e){let r=this.inputVariables.filter(i=>!(i in e)),n={...this.partialVariables??{},...e},o={...this,inputVariables:r,partialVariables:n};return new t(o)}async format(e){let r=await this.mergePartialAndUserVariables(e),n=await this.getExamples(r),o=await Promise.all(n.map(a=>this.examplePrompt.format(a))),i=[this.prefix,...o,this.suffix].join(this.exampleSeparator);return Sp(i,this.templateFormat,r)}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(e){let{example_prompt:r}=e;if(!r)throw new Error("Missing example prompt");let n=await Dd.deserialize(r),o;if(Array.isArray(e.examples))o=e.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new t({inputVariables:e.input_variables,examplePrompt:n,examples:o,exampleSeparator:e.example_separator,prefix:e.prefix,suffix:e.suffix,templateFormat:e.template_format})}},The=class t extends e4{_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"examples",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleSelector",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"examplePrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"suffix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"exampleSeparator",{enumerable:!0,configurable:!0,writable:!0,value:`
`}),Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.assign(this,e),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 r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),IR(this.prefix+this.suffix,this.templateFormat,r)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(e){let r=this.inputVariables.filter(i=>!(i in e)),n={...this.partialVariables??{},...e},o={...this,inputVariables:r,partialVariables:n};return new t(o)}async format(e){let r=await this.mergePartialAndUserVariables(e),n=await this.getExamples(r),o=await Promise.all(n.map(a=>this.examplePrompt.format(a))),i=[this.prefix,...o,this.suffix].join(this.exampleSeparator);return Sp(i,this.templateFormat,r)}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(e){let{example_prompt:r}=e;if(!r)throw new Error("Missing example prompt");let n=await Dd.deserialize(r),o;if(Array.isArray(e.examples))o=e.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new t({inputVariables:e.input_variables,examplePrompt:n,examples:o,exampleSeparator:e.example_separator,prefix:e.prefix,suffix:e.suffix,templateFormat:e.template_format})}},Mhe=class t extends t4{_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"examples",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleSelector",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"examplePrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"suffix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"exampleSeparator",{enumerable:!0,configurable:!0,writable:!0,value:`
`}),Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.examples=e.examples,this.examplePrompt=e.examplePrompt,this.exampleSeparator=e.exampleSeparator??`
`,this.exampleSelector=e.exampleSelector,this.prefix=e.prefix??"",this.suffix=e.suffix??"",this.templateFormat=e.templateFormat??"f-string",this.validateTemplate=e.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 r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),IR(this.prefix+this.suffix,this.templateFormat,r)}}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(e){let r=await this.mergePartialAndUserVariables(e),n=await this.getExamples(r);n=n.map(i=>{let a={};return this.examplePrompt.inputVariables.forEach(s=>{a[s]=i[s]}),a});let o=[];for(let i of n){let a=await this.examplePrompt.formatMessages(i);o.push(...a)}return o}async format(e){let r=await this.mergePartialAndUserVariables(e),n=await this.getExamples(r),i=(await Promise.all(n.map(s=>this.examplePrompt.formatMessages(s)))).flat().map(s=>s.content),a=[this.prefix,...i,this.suffix].join(this.exampleSeparator);return Sp(a,this.templateFormat,r)}async partial(e){let r=this.inputVariables.filter(i=>!(i in e)),n={...this.partialVariables??{},...e},o={...this,inputVariables:r,partialVariables:n};return new t(o)}}});var Kb,nF=w(()=>{Df();Kb=class extends xn{get lc_attributes(){return{partialVariables:void 0}}constructor(e){super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts",this._getPromptType()]}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputParser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"partialVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0});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)}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"})}serialize(){throw new Error("Use .toJSON() instead")}static async deserialize(e){switch(e._type){case"prompt":{let{PromptTemplate:r}=await Promise.resolve().then(()=>(aF(),_he));return r.deserialize(e)}case void 0:{let{PromptTemplate:r}=await Promise.resolve().then(()=>(aF(),_he));return r.deserialize({...e,_type:"prompt"})}case"few_shot":{let{FewShotPromptTemplate:r}=await Promise.resolve().then(()=>(Ahe(),EHe));return r.deserialize(e)}default:throw new Error(`Invalid prompt type in config: ${e._type}`)}}}});var THe=w(()=>{nF();r4()});var AHe=w(()=>{});var IHe=w(()=>{r4()});var MHe=w(()=>{nF();r4();Ahe();THe();aF();AHe();K2();MR();vhe();IHe();xhe()});var qE=w(()=>{MHe()});var Sm=w(()=>{uhe()});var Ihe,Mhe=w(()=>{Ihe=t=>t.map(e=>e.pageContent).join(`
`,this.exampleSelector=e.exampleSelector,this.prefix=e.prefix??"",this.suffix=e.suffix??"",this.templateFormat=e.templateFormat??"f-string",this.validateTemplate=e.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 r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),IR(this.prefix+this.suffix,this.templateFormat,r)}}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(e){let r=await this.mergePartialAndUserVariables(e),n=await this.getExamples(r);n=n.map(i=>{let a={};return this.examplePrompt.inputVariables.forEach(s=>{a[s]=i[s]}),a});let o=[];for(let i of n){let a=await this.examplePrompt.formatMessages(i);o.push(...a)}return o}async format(e){let r=await this.mergePartialAndUserVariables(e),n=await this.getExamples(r),i=(await Promise.all(n.map(s=>this.examplePrompt.formatMessages(s)))).flat().map(s=>s.content),a=[this.prefix,...i,this.suffix].join(this.exampleSeparator);return Sp(a,this.templateFormat,r)}async partial(e){let r=this.inputVariables.filter(i=>!(i in e)),n={...this.partialVariables??{},...e},o={...this,inputVariables:r,partialVariables:n};return new t(o)}}});var Kb,oF=w(()=>{Df();Kb=class extends Cn{get lc_attributes(){return{partialVariables:void 0}}constructor(e){super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts",this._getPromptType()]}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputParser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"partialVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0});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)}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"})}serialize(){throw new Error("Use .toJSON() instead")}static async deserialize(e){switch(e._type){case"prompt":{let{PromptTemplate:r}=await Promise.resolve().then(()=>(sF(),She));return r.deserialize(e)}case void 0:{let{PromptTemplate:r}=await Promise.resolve().then(()=>(sF(),She));return r.deserialize({...e,_type:"prompt"})}case"few_shot":{let{FewShotPromptTemplate:r}=await Promise.resolve().then(()=>(Rhe(),AHe));return r.deserialize(e)}default:throw new Error(`Invalid prompt type in config: ${e._type}`)}}}});var IHe=w(()=>{oF();n4()});var MHe=w(()=>{});var RHe=w(()=>{n4()});var jHe=w(()=>{oF();n4();Rhe();IHe();sF();MHe();G2();MR();xhe();RHe();Phe()});var qE=w(()=>{jHe()});var Sm=w(()=>{dhe()});var jhe,Nhe=w(()=>{jhe=t=>t.map(e=>e.pageContent).join(`
`)});var RHe=w(()=>{Mhe()});function Ih(t,e){let r=`atom${++Psr}`,n={toString(){return(Sa.env?Sa.env.MODE:void 0)!=="production"&&this.debugLabel?r+":"+this.debugLabel:r}};return typeof t=="function"?n.read=t:(n.init=t,n.read=Esr,n.write=Tsr),e&&(n.write=e),n}function Esr(t){return t(this)}function Tsr(t,e,r){return e(this,typeof r=="function"?r(t(this)):r)}var Sa,Psr,jHe,Rhe,jhe,GG,Dhe,Asr,Isr,Lhe,NHe,KG,FHe,DHe,uF,Nhe,Msr,Rsr,LHe,UE,kHe,lF,n4,$He,Fhe=w(()=>{Sa={},Psr=0;jHe=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,Rhe=t=>"init"in t,jhe=t=>!!t.write,GG=new WeakMap,Dhe=t=>{var e;return Lhe(t)&&!((e=GG.get(t))!=null&&e[1])},Asr=(t,e)=>{let r=GG.get(t);if(r)r[1]=!0,r[0].forEach(n=>n(e));else if((Sa.env?Sa.env.MODE:void 0)!=="production")throw new Error("[Bug] cancelable promise not found")},Isr=t=>{if(GG.has(t))return;let e=[new Set,!1];GG.set(t,e);let r=()=>{e[1]=!0};t.then(r,r),t.onCancel=n=>{e[0].add(n)}},Lhe=t=>typeof t?.then=="function",NHe=t=>"v"in t||"e"in t,KG=t=>{if("e"in t)throw t.e;if((Sa.env?Sa.env.MODE:void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},FHe=(t,e,r)=>{r.p.has(t)||(r.p.add(t),e.then(()=>{r.p.delete(t)},()=>{r.p.delete(t)}))},DHe=(t,e,r,n,o)=>{var i;if((Sa.env?Sa.env.MODE:void 0)!=="production"&&n===e)throw new Error("[Bug] atom cannot depend on itself");r.d.set(n,o.n),Dhe(r.v)&&FHe(e,r.v,o),(i=o.m)==null||i.t.add(e),t&&Msr(t,n,e)},uF=()=>[new Map,new Map,new Set],Nhe=(t,e,r)=>{t[0].has(e)||t[0].set(e,new Set),t[1].set(e,r)},Msr=(t,e,r)=>{let n=t[0].get(e);n&&n.add(r)},Rsr=(t,e)=>t[0].get(e),LHe=(t,e)=>{t[2].add(e)},UE=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},kHe=(...[t,e,r,n])=>{let o;(Sa.env?Sa.env.MODE:void 0)!=="production"&&(o=new Set);let i=(S,x,O)=>{let P="v"in x,E=x.v,A=Dhe(x.v)?x.v:null;if(Lhe(O)){Isr(O);for(let I of x.d.keys())FHe(S,O,t(I));x.v=O,delete x.e}else x.v=O,delete x.e;(!P||!Object.is(E,x.v))&&(++x.n,A&&Asr(A,O))},a=(S,x,O)=>{var P;let E=t(x);if(NHe(E)&&(E.m&&!O?.has(x)||Array.from(E.d).every(([$,k])=>a(S,$,O).n===k)))return E;E.d.clear();let A=!0,I=$=>{if(jHe(x,$)){let z=t($);if(!NHe(z))if(Rhe($))i($,z,$.init);else throw new Error("no atom init");return KG(z)}let k=a(S,$,O);try{return KG(k)}finally{if(A)DHe(S,x,E,$,k);else{let z=uF();DHe(z,x,E,$,k),p(z,x,E),UE(z)}}},R,N,j={get signal(){return R||(R=new AbortController),R.signal},get setSelf(){return(Sa.env?Sa.env.MODE:void 0)!=="production"&&!jhe(x)&&console.warn("setSelf function cannot be used with read-only atom"),!N&&jhe(x)&&(N=(...$)=>{if((Sa.env?Sa.env.MODE:void 0)!=="production"&&A&&console.warn("setSelf function cannot be called in sync"),!A)return f(x,...$)}),N}};try{let $=e(x,I,j);if(i(x,E,$),Lhe($)){(P=$.onCancel)==null||P.call($,()=>R?.abort());let k=()=>{if(E.m){let z=uF();p(z,x,E),UE(z)}};$.then(k,k)}return E}catch($){return delete E.v,E.e=$,++E.n,E}finally{A=!1}},s=S=>KG(a(void 0,S)),u=(S,x,O)=>{var P,E;let A=new Map;for(let I of((P=O.m)==null?void 0:P.t)||[])A.set(I,t(I));for(let I of O.p)A.set(I,t(I));return(E=Rsr(S,x))==null||E.forEach(I=>{A.set(I,t(I))}),A};function l(S,x,O){let P=[],E=new Set,A=new Set,I=[[x,O]];for(;I.length>0;){let[R,N]=I[I.length-1];if(A.has(R)){I.pop();continue}if(E.has(R)){P.push([R,N,N.n]),A.add(R),I.pop();continue}E.add(R);for(let[j,$]of u(S,R,N))R!==j&&!E.has(j)&&I.push([j,$])}return[P,A]}let c=(S,x,O)=>{let[P,E]=l(S,x,O),A=new Set([x]);for(let I=P.length-1;I>=0;--I){let[R,N,j]=P[I],$=!1;for(let k of N.d.keys())if(k!==R&&A.has(k)){$=!0;break}$&&(a(S,R,E),p(S,R,N),j!==N.n&&(Nhe(S,R,N),A.add(R))),E.delete(R)}},d=(S,x,...O)=>{let P=!0,E=I=>KG(a(S,I)),A=(I,...R)=>{let N=t(I);try{if(jHe(x,I)){if(!Rhe(I))throw new Error("atom not writable");let j=N.n,$=R[0];i(I,N,$),p(S,I,N),j!==N.n&&(Nhe(S,I,N),c(S,I,N));return}else return d(S,I,...R)}finally{P||UE(S)}};try{return r(x,E,A,...O)}finally{P=!1}},f=(S,...x)=>{let O=uF();try{return d(O,S,...x)}finally{UE(O)}},p=(S,x,O)=>{if(O.m&&!Dhe(O.v)){for(let P of O.d.keys())O.m.d.has(P)||(m(S,P,t(P)).t.add(x),O.m.d.add(P));for(let P of O.m.d||[])if(!O.d.has(P)){O.m.d.delete(P);let E=h(S,P,t(P));E?.t.delete(x)}}},m=(S,x,O)=>{if(!O.m){a(S,x);for(let P of O.d.keys())m(S,P,t(P)).t.add(x);if(O.m={l:new Set,d:new Set(O.d.keys()),t:new Set},(Sa.env?Sa.env.MODE:void 0)!=="production"&&o.add(x),jhe(x)){let P=O.m,E,A=(I,R)=>{let N=!0;E=(...j)=>{try{return d(I,x,...j)}finally{N||UE(I)}};try{return R()}finally{N=!1}};LHe(S,()=>{let I=A(S,()=>n(x,(...R)=>E(...R)));I&&(P.u=R=>A(R,I))})}}return O.m},h=(S,x,O)=>{if(O.m&&!O.m.l.size&&!Array.from(O.m.t).some(P=>{var E;return(E=t(P).m)==null?void 0:E.d.has(x)})){let P=O.m.u;P&&LHe(S,()=>P(S)),delete O.m,(Sa.env?Sa.env.MODE:void 0)!=="production"&&o.delete(x);for(let E of O.d.keys()){let A=h(S,E,t(E));A?.t.delete(x)}return}return O.m},y={ge Line truncated
`)});var NHe=w(()=>{Nhe()});function Ih(t,e){let r=`atom${++Msr}`,n={toString(){return(Sa.env?Sa.env.MODE:void 0)!=="production"&&this.debugLabel?r+":"+this.debugLabel:r}};return typeof t=="function"?n.read=t:(n.init=t,n.read=Rsr,n.write=jsr),e&&(n.write=e),n}function Rsr(t){return t(this)}function jsr(t,e,r){return e(this,typeof r=="function"?r(t(this)):r)}var Sa,Msr,DHe,Dhe,Lhe,JG,khe,Nsr,Dsr,$he,LHe,GG,$He,FHe,lF,Fhe,Lsr,Fsr,kHe,UE,BHe,cF,o4,qHe,Bhe=w(()=>{Sa={},Msr=0;DHe=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,Dhe=t=>"init"in t,Lhe=t=>!!t.write,JG=new WeakMap,khe=t=>{var e;return $he(t)&&!((e=JG.get(t))!=null&&e[1])},Nsr=(t,e)=>{let r=JG.get(t);if(r)r[1]=!0,r[0].forEach(n=>n(e));else if((Sa.env?Sa.env.MODE:void 0)!=="production")throw new Error("[Bug] cancelable promise not found")},Dsr=t=>{if(JG.has(t))return;let e=[new Set,!1];JG.set(t,e);let r=()=>{e[1]=!0};t.then(r,r),t.onCancel=n=>{e[0].add(n)}},$he=t=>typeof t?.then=="function",LHe=t=>"v"in t||"e"in t,GG=t=>{if("e"in t)throw t.e;if((Sa.env?Sa.env.MODE:void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},$He=(t,e,r)=>{r.p.has(t)||(r.p.add(t),e.then(()=>{r.p.delete(t)},()=>{r.p.delete(t)}))},FHe=(t,e,r,n,o)=>{var i;if((Sa.env?Sa.env.MODE:void 0)!=="production"&&n===e)throw new Error("[Bug] atom cannot depend on itself");r.d.set(n,o.n),khe(r.v)&&$He(e,r.v,o),(i=o.m)==null||i.t.add(e),t&&Lsr(t,n,e)},lF=()=>[new Map,new Map,new Set],Fhe=(t,e,r)=>{t[0].has(e)||t[0].set(e,new Set),t[1].set(e,r)},Lsr=(t,e,r)=>{let n=t[0].get(e);n&&n.add(r)},Fsr=(t,e)=>t[0].get(e),kHe=(t,e)=>{t[2].add(e)},UE=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},BHe=(...[t,e,r,n])=>{let o;(Sa.env?Sa.env.MODE:void 0)!=="production"&&(o=new Set);let i=(S,x,O)=>{let P="v"in x,E=x.v,A=khe(x.v)?x.v:null;if($he(O)){Dsr(O);for(let I of x.d.keys())$He(S,O,t(I));x.v=O,delete x.e}else x.v=O,delete x.e;(!P||!Object.is(E,x.v))&&(++x.n,A&&Nsr(A,O))},a=(S,x,O)=>{var P;let E=t(x);if(LHe(E)&&(E.m&&!O?.has(x)||Array.from(E.d).every(([$,k])=>a(S,$,O).n===k)))return E;E.d.clear();let A=!0,I=$=>{if(DHe(x,$)){let z=t($);if(!LHe(z))if(Dhe($))i($,z,$.init);else throw new Error("no atom init");return GG(z)}let k=a(S,$,O);try{return GG(k)}finally{if(A)FHe(S,x,E,$,k);else{let z=lF();FHe(z,x,E,$,k),p(z,x,E),UE(z)}}},R,N,j={get signal(){return R||(R=new AbortController),R.signal},get setSelf(){return(Sa.env?Sa.env.MODE:void 0)!=="production"&&!Lhe(x)&&console.warn("setSelf function cannot be used with read-only atom"),!N&&Lhe(x)&&(N=(...$)=>{if((Sa.env?Sa.env.MODE:void 0)!=="production"&&A&&console.warn("setSelf function cannot be called in sync"),!A)return f(x,...$)}),N}};try{let $=e(x,I,j);if(i(x,E,$),$he($)){(P=$.onCancel)==null||P.call($,()=>R?.abort());let k=()=>{if(E.m){let z=lF();p(z,x,E),UE(z)}};$.then(k,k)}return E}catch($){return delete E.v,E.e=$,++E.n,E}finally{A=!1}},s=S=>GG(a(void 0,S)),u=(S,x,O)=>{var P,E;let A=new Map;for(let I of((P=O.m)==null?void 0:P.t)||[])A.set(I,t(I));for(let I of O.p)A.set(I,t(I));return(E=Fsr(S,x))==null||E.forEach(I=>{A.set(I,t(I))}),A};function l(S,x,O){let P=[],E=new Set,A=new Set,I=[[x,O]];for(;I.length>0;){let[R,N]=I[I.length-1];if(A.has(R)){I.pop();continue}if(E.has(R)){P.push([R,N,N.n]),A.add(R),I.pop();continue}E.add(R);for(let[j,$]of u(S,R,N))R!==j&&!E.has(j)&&I.push([j,$])}return[P,A]}let c=(S,x,O)=>{let[P,E]=l(S,x,O),A=new Set([x]);for(let I=P.length-1;I>=0;--I){let[R,N,j]=P[I],$=!1;for(let k of N.d.keys())if(k!==R&&A.has(k)){$=!0;break}$&&(a(S,R,E),p(S,R,N),j!==N.n&&(Fhe(S,R,N),A.add(R))),E.delete(R)}},d=(S,x,...O)=>{let P=!0,E=I=>GG(a(S,I)),A=(I,...R)=>{let N=t(I);try{if(DHe(x,I)){if(!Dhe(I))throw new Error("atom not writable");let j=N.n,$=R[0];i(I,N,$),p(S,I,N),j!==N.n&&(Fhe(S,I,N),c(S,I,N));return}else return d(S,I,...R)}finally{P||UE(S)}};try{return r(x,E,A,...O)}finally{P=!1}},f=(S,...x)=>{let O=lF();try{return d(O,S,...x)}finally{UE(O)}},p=(S,x,O)=>{if(O.m&&!khe(O.v)){for(let P of O.d.keys())O.m.d.has(P)||(m(S,P,t(P)).t.add(x),O.m.d.add(P));for(let P of O.m.d||[])if(!O.d.has(P)){O.m.d.delete(P);let E=h(S,P,t(P));E?.t.delete(x)}}},m=(S,x,O)=>{if(!O.m){a(S,x);for(let P of O.d.keys())m(S,P,t(P)).t.add(x);if(O.m={l:new Set,d:new Set(O.d.keys()),t:new Set},(Sa.env?Sa.env.MODE:void 0)!=="production"&&o.add(x),Lhe(x)){let P=O.m,E,A=(I,R)=>{let N=!0;E=(...j)=>{try{return d(I,x,...j)}finally{N||UE(I)}};try{return R()}finally{N=!1}};kHe(S,()=>{let I=A(S,()=>n(x,(...R)=>E(...R)));I&&(P.u=R=>A(R,I))})}}return O.m},h=(S,x,O)=>{if(O.m&&!O.m.l.size&&!Array.from(O.m.t).some(P=>{var E;return(E=t(P).m)==null?void 0:E.d.has(x)})){let P=O.m.u;P&&kHe(S,()=>P(S)),delete O.m,(Sa.env?Sa.env.MODE:void 0)!=="production"&&o.delete(x);for(let E of O.d.keys()){let A=h(S,E,t(E));A?.t.delete(x)}return}return O.m},y={ge Line truncated
<user_custom_instructions>
${t}
</user_custom_instructions>`:e}function Zsr(t){return t.activeModels=rVe(t.activeModels,Zb),t.activeEmbeddingModels=rVe(t.activeEmbeddingModels,jR),t}function kr(t){return`${t.name}|${t.provider}`}function rVe(t,e){let r=new Map;return e.filter(n=>n.core).forEach(n=>{r.set(kr(n),{...n})}),t.forEach(n=>{let o=kr(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 ls,RR,nr=w(()=>{s4();l2();$r();ls=lF(),RR=Ih(Ic)});function ie(...t){ue().debug&&console.log(...t)}function fe(...t){ue().debug&&console.error(...t)}function Mh(...t){ue().debug&&console.warn(...t)}var yo=w(()=>{nr()});var uVe=v((Vhe,dF)=>{(function(t,e){typeof Vhe=="object"&&typeof dF<"u"?dF.exports=e():typeof define=="function"&&define.amd?define(e):t.moment=e()})(Vhe,function(){"use strict";var t;function e(){return t.apply(null,arguments)}function r(_){t=_}function n(_){return _ instanceof Array||Object.prototype.toString.call(_)==="[object Array]"}function o(_){return _!=null&&Object.prototype.toString.call(_)==="[object Object]"}function i(_,C){return Object.prototype.hasOwnProperty.call(_,C)}function a(_){if(Object.getOwnPropertyNames)return Object.getOwnPropertyNames(_).length===0;var C;for(C in _)if(i(_,C))return!1;return!0}function s(_){return _===void 0}function u(_){return typeof _=="number"||Object.prototype.toString.call(_)==="[object Number]"}function l(_){return _ instanceof Date||Object.prototype.toString.call(_)==="[object Date]"}function c(_,C){var T=[],M,L=_.length;for(M=0;M<L;++M)T.push(C(_[M],M));return T}function d(_,C){for(var T in C)i(C,T)&&(_[T]=C[T]);return i(C,"toString")&&(_.toString=C.toString),i(C,"valueOf")&&(_.valueOf=C.valueOf),_}function f(_,C,T,M){return zqe(_,C,T,M,!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(_){return _._pf==null&&(_._pf=p()),_._pf}var h;Array.prototype.some?h=Array.prototype.some:h=function(_){var C=Object(this),T=C.length>>>0,M;for(M=0;M<T;M++)if(M in C&&_.call(this,C[M],M,C))return!0;return!1};function b(_){if(_._isValid==null){var C=m(_),T=h.call(C.parsedDateParts,function(L){return L!=null}),M=!isNaN(_._d.getTime())&&C.overflow<0&&!C.empty&&!C.invalidEra&&!C.invalidMonth&&!C.invalidWeekday&&!C.weekdayMismatch&&!C.nullInput&&!C.invalidFormat&&!C.userInvalidated&&(!C.meridiem||C.meridiem&&T);if(_._strict&&(M=M&&C.charsLeftOver===0&&C.unusedTokens.length===0&&C.bigHour===void 0),Object.isFrozen==null||!Object.isFrozen(_))_._isValid=M;else return M}return _._isValid}function g(_){var C=f(NaN);return _!=null?d(m(C),_):m(C).userInvalidated=!0,C}var y=e.momentProperties=[],S=!1;function x(_,C){var T,M,L,Z=y.length;if(s(C._isAMomentObject)||(_._isAMomentObject=C._isAMomentObject),s(C._i)||(_._i=C._i),s(C._f)||(_._f=C._f),s(C._l)||(_._l=C._l),s(C._strict)||(_._strict=C._strict),s(C._tzm)||(_._tzm=C._tzm),s(C._isUTC)||(_._isUTC=C._isUTC),s(C._offset)||(_._offset=C._offset),s(C._pf)||(_._pf=m(C)),s(C._locale)||(_._locale=C._locale),Z>0)for(T=0;T<Z;T++)M=y[T],L=C[M],s(L)||(_[M]=L);return _}function O(_){x(this,_),this._d=new Date(_._d!=null?_._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),S===!1&&(S=!0,e.updateOffset(this),S=!1)}function P(_){return _ instanceof O||_!=null&&_._isAMomentObject!=null}function E(_){e.suppressDeprecationWarnings===!1&&typeof console<"u"&&console.warn&&console.warn("Deprecation warning: "+_)}function A(_,C){var T=!0;return d(function(){if(e.deprecationHandler!=null&&e.deprecationHandler(null,_),T){var M=[],L,Z,he,tr=arguments.length;for(Z=0;Z<tr;Z++){if(L="",typeof arguments[Z]=="object"){L+=`
</user_custom_instructions>`:e}function rur(t){return t.activeModels=oVe(t.activeModels,Zb),t.activeEmbeddingModels=oVe(t.activeEmbeddingModels,jR),t}function kr(t){return`${t.name}|${t.provider}`}function oVe(t,e){let r=new Map;return e.filter(n=>n.core).forEach(n=>{r.set(kr(n),{...n})}),t.forEach(n=>{let o=kr(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 ls,RR,nr=w(()=>{u4();c2();$r();ls=cF(),RR=Ih(Ic)});function ie(...t){ue().debug&&console.log(...t)}function fe(...t){ue().debug&&console.error(...t)}function Mh(...t){ue().debug&&console.warn(...t)}var yo=w(()=>{nr()});var cVe=v((Ghe,fF)=>{(function(t,e){typeof Ghe=="object"&&typeof fF<"u"?fF.exports=e():typeof define=="function"&&define.amd?define(e):t.moment=e()})(Ghe,function(){"use strict";var t;function e(){return t.apply(null,arguments)}function r(_){t=_}function n(_){return _ instanceof Array||Object.prototype.toString.call(_)==="[object Array]"}function o(_){return _!=null&&Object.prototype.toString.call(_)==="[object Object]"}function i(_,C){return Object.prototype.hasOwnProperty.call(_,C)}function a(_){if(Object.getOwnPropertyNames)return Object.getOwnPropertyNames(_).length===0;var C;for(C in _)if(i(_,C))return!1;return!0}function s(_){return _===void 0}function u(_){return typeof _=="number"||Object.prototype.toString.call(_)==="[object Number]"}function l(_){return _ instanceof Date||Object.prototype.toString.call(_)==="[object Date]"}function c(_,C){var T=[],M,L=_.length;for(M=0;M<L;++M)T.push(C(_[M],M));return T}function d(_,C){for(var T in C)i(C,T)&&(_[T]=C[T]);return i(C,"toString")&&(_.toString=C.toString),i(C,"valueOf")&&(_.valueOf=C.valueOf),_}function f(_,C,T,M){return Vqe(_,C,T,M,!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(_){return _._pf==null&&(_._pf=p()),_._pf}var h;Array.prototype.some?h=Array.prototype.some:h=function(_){var C=Object(this),T=C.length>>>0,M;for(M=0;M<T;M++)if(M in C&&_.call(this,C[M],M,C))return!0;return!1};function b(_){if(_._isValid==null){var C=m(_),T=h.call(C.parsedDateParts,function(L){return L!=null}),M=!isNaN(_._d.getTime())&&C.overflow<0&&!C.empty&&!C.invalidEra&&!C.invalidMonth&&!C.invalidWeekday&&!C.weekdayMismatch&&!C.nullInput&&!C.invalidFormat&&!C.userInvalidated&&(!C.meridiem||C.meridiem&&T);if(_._strict&&(M=M&&C.charsLeftOver===0&&C.unusedTokens.length===0&&C.bigHour===void 0),Object.isFrozen==null||!Object.isFrozen(_))_._isValid=M;else return M}return _._isValid}function g(_){var C=f(NaN);return _!=null?d(m(C),_):m(C).userInvalidated=!0,C}var y=e.momentProperties=[],S=!1;function x(_,C){var T,M,L,Z=y.length;if(s(C._isAMomentObject)||(_._isAMomentObject=C._isAMomentObject),s(C._i)||(_._i=C._i),s(C._f)||(_._f=C._f),s(C._l)||(_._l=C._l),s(C._strict)||(_._strict=C._strict),s(C._tzm)||(_._tzm=C._tzm),s(C._isUTC)||(_._isUTC=C._isUTC),s(C._offset)||(_._offset=C._offset),s(C._pf)||(_._pf=m(C)),s(C._locale)||(_._locale=C._locale),Z>0)for(T=0;T<Z;T++)M=y[T],L=C[M],s(L)||(_[M]=L);return _}function O(_){x(this,_),this._d=new Date(_._d!=null?_._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),S===!1&&(S=!0,e.updateOffset(this),S=!1)}function P(_){return _ instanceof O||_!=null&&_._isAMomentObject!=null}function E(_){e.suppressDeprecationWarnings===!1&&typeof console<"u"&&console.warn&&console.warn("Deprecation warning: "+_)}function A(_,C){var T=!0;return d(function(){if(e.deprecationHandler!=null&&e.deprecationHandler(null,_),T){var M=[],L,Z,he,tr=arguments.length;for(Z=0;Z<tr;Z++){if(L="",typeof arguments[Z]=="object"){L+=`
[`+Z+"] ";for(he in arguments[0])i(arguments[0],he)&&(L+=he+": "+arguments[0][he]+", ");L=L.slice(0,-2)}else L=arguments[Z];M.push(L)}E(_+`
Arguments: `+Array.prototype.slice.call(M).join("")+`
`+new Error().stack),T=!1}return C.apply(this,arguments)},C)}var I={};function R(_,C){e.deprecationHandler!=null&&e.deprecationHandler(_,C),I[_]||(E(C),I[_]=!0)}e.suppressDeprecationWarnings=!1,e.deprecationHandler=null;function N(_){return typeof Function<"u"&&_ instanceof Function||Object.prototype.toString.call(_)==="[object Function]"}function j(_){var C,T;for(T in _)i(_,T)&&(C=_[T],N(C)?this[T]=C:this["_"+T]=C);this._config=_,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)}function $(_,C){var T=d({},_),M;for(M in C)i(C,M)&&(o(_[M])&&o(C[M])?(T[M]={},d(T[M],_[M]),d(T[M],C[M])):C[M]!=null?T[M]=C[M]:delete T[M]);for(M in _)i(_,M)&&!i(C,M)&&o(_[M])&&(T[M]=d({},T[M]));return T}function k(_){_!=null&&this.set(_)}var z;Object.keys?z=Object.keys:z=function(_){var C,T=[];for(C in _)i(_,C)&&T.push(C);return T};var V={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"};function Q(_,C,T){var M=this._calendar[_]||this._calendar.sameElse;return N(M)?M.call(C,T):M}function J(_,C,T){var M=""+Math.abs(_),L=C-M.length,Z=_>=0;return(Z?T?"+":"":"-")+Math.pow(10,Math.max(0,L)).toString().substr(1)+M}var D=/(\[[^\[]*\])|(\\)?([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,B=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,q={},K={};function H(_,C,T,M){var L=M;typeof M=="string"&&(L=function(){return this[M]()}),_&&(K[_]=L),C&&(K[C[0]]=function(){return J(L.apply(this,arguments),C[1],C[2])}),T&&(K[T]=function(){return this.localeData().ordinal(L.apply(this,arguments),_)})}function ee(_){return _.match(/\[[\s\S]/)?_.replace(/^\[|\]$/g,""):_.replace(/\\/g,"")}function U(_){var C=_.match(D),T,M;for(T=0,M=C.length;T<M;T++)K[C[T]]?C[T]=K[C[T]]:C[T]=ee(C[T]);return function(L){var Z="",he;for(he=0;he<M;he++)Z+=N(C[he])?C[he].call(L,_):C[he];return Z}}function W(_,C){return _.isValid()?(C=Y(C,_.localeData()),q[C]=q[C]||U(C),q[C](_)):_.localeData().invalidDate()}function Y(_,C){var T=5;function M(L){return C.longDateFormat(L)||L}for(B.lastIndex=0;T>=0&&B.test(_);)_=_.replace(B,M),B.lastIndex=0,T-=1;return _}var ae={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 Oe(_){var C=this._longDateFormat[_],T=this._longDateFormat[_.toUpperCase()];return C||!T?C:(this._longDateFormat[_]=T.match(D).map(function(M){return M==="MMMM"||M==="MM"||M==="DD"||M==="dddd"?M.slice(1):M}).join(""),this._longDateFormat[_])}var le="Invalid date";function Be(){return this._invalidDate}var ze="%d",rt=/\d{1,2}/;function cr(_){return this._ordinal.replace("%d",_)}var wn={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 Le(_,C,T,M){var L=this._relativeTime[T];return N(L)?L(_,C,T,M):L.replace(/%d/i,_)}function pt(_,C){var T=this._relativeTime[_>0?"future":"past"];return N(T)?T(C):T.replace(/%s/i,C)}var mt={};function ht(_,C){var T=_.toLowerCase();mt[T]=mt[T+"s"]=mt[C]=_}function te(_){return typeof _=="string"?mt[_]||mt[_.toLowerCase()]:void 0}function et(_){var C={},T,M;for(M in _)i(_,M)&&(T=te(M),T&&(C[T]=_[M]));return C}var Re={};function Pe(_,C){Re[_]=C}function oe(_){var C=[],T;for(T in _)i(_,T)&&C.push({unit:T,priority:Re[T]});return C.sort(function(M,L){return M.priority-L.priority}),C}function se(_){return _%4===0&&_%100!==0||_%400===0}function ce(_){return _<0?Math.ceil(_)||0:Math.floor(_)}function Ce(_){var C=+_,T=0;return C!==0&&isFinite(C)&&(T=ce(C)),T}function Je(_,C){return function(T){return T!=null?(ea(this,_,T),e.updateOffset(this,C),this):ir(this,_)}}function ir(_,C){return _.isValid()?_._d["get"+(_._isUTC?"UTC":"")+C]():NaN}function ea(_,C,T){_.isValid()&&!isNaN(T)&&(C==="FullYear"&&se(_.year())&&_.month()===1&&_.date()===29?(T=Ce(T),_._d["set"+(_._isUTC?"UTC":"")+C](T,_.month(),iK(T,_.month()))):_._d["set"+(_._isUTC?"UTC":"")+C](T))}function ta(_){return _=te(_),N(this[_])?this[_]():this}function xc(_,C){if(typeof _=="object"){_=et(_);var T=oe(_),M,L=T.length;for(M=0;M<L;M++)this[T[M].unit](_[T[M].unit])}else if(_=te(_),N(this[_]))return this[_](C);return this}var Cd=/\d/,qi=/\d\d/,lp=/\d{3}/,yf=/\d{4}/,bf=/[+-]?\d{6}/,Sn=/\d\d?/,_f=/\d\d\d\d?/,sC=/\d\d\d\d\d\d?/,kb=/\d{1,3}/,is=/\d{1,4}/,$s=/[+-]?\d{1,6}/,La=/\d+/,vf=/[+-]?\d+/,Od=/Z|[+-]\d\d:?\d\d/gi,ws=/Z|[+-]\d\d(?::?\d\d)?/gi,cp=/[+-]?\d+(\.\d{1,3})?/,wf=/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,In;In={};function Ye(_,C,T){In[_]=N(C)?C:function(M,L){return M&&T?T:C}}function Sf(_,C){return i(In,_)?In[_](C._strict,C._l Line truncated
`+new Error().stack),T=!1}return C.apply(this,arguments)},C)}var I={};function R(_,C){e.deprecationHandler!=null&&e.deprecationHandler(_,C),I[_]||(E(C),I[_]=!0)}e.suppressDeprecationWarnings=!1,e.deprecationHandler=null;function N(_){return typeof Function<"u"&&_ instanceof Function||Object.prototype.toString.call(_)==="[object Function]"}function j(_){var C,T;for(T in _)i(_,T)&&(C=_[T],N(C)?this[T]=C:this["_"+T]=C);this._config=_,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)}function $(_,C){var T=d({},_),M;for(M in C)i(C,M)&&(o(_[M])&&o(C[M])?(T[M]={},d(T[M],_[M]),d(T[M],C[M])):C[M]!=null?T[M]=C[M]:delete T[M]);for(M in _)i(_,M)&&!i(C,M)&&o(_[M])&&(T[M]=d({},T[M]));return T}function k(_){_!=null&&this.set(_)}var z;Object.keys?z=Object.keys:z=function(_){var C,T=[];for(C in _)i(_,C)&&T.push(C);return T};var V={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"};function Q(_,C,T){var M=this._calendar[_]||this._calendar.sameElse;return N(M)?M.call(C,T):M}function J(_,C,T){var M=""+Math.abs(_),L=C-M.length,Z=_>=0;return(Z?T?"+":"":"-")+Math.pow(10,Math.max(0,L)).toString().substr(1)+M}var D=/(\[[^\[]*\])|(\\)?([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,B=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,q={},K={};function H(_,C,T,M){var L=M;typeof M=="string"&&(L=function(){return this[M]()}),_&&(K[_]=L),C&&(K[C[0]]=function(){return J(L.apply(this,arguments),C[1],C[2])}),T&&(K[T]=function(){return this.localeData().ordinal(L.apply(this,arguments),_)})}function ee(_){return _.match(/\[[\s\S]/)?_.replace(/^\[|\]$/g,""):_.replace(/\\/g,"")}function U(_){var C=_.match(D),T,M;for(T=0,M=C.length;T<M;T++)K[C[T]]?C[T]=K[C[T]]:C[T]=ee(C[T]);return function(L){var Z="",he;for(he=0;he<M;he++)Z+=N(C[he])?C[he].call(L,_):C[he];return Z}}function W(_,C){return _.isValid()?(C=Y(C,_.localeData()),q[C]=q[C]||U(C),q[C](_)):_.localeData().invalidDate()}function Y(_,C){var T=5;function M(L){return C.longDateFormat(L)||L}for(B.lastIndex=0;T>=0&&B.test(_);)_=_.replace(B,M),B.lastIndex=0,T-=1;return _}var ae={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 Oe(_){var C=this._longDateFormat[_],T=this._longDateFormat[_.toUpperCase()];return C||!T?C:(this._longDateFormat[_]=T.match(D).map(function(M){return M==="MMMM"||M==="MM"||M==="DD"||M==="dddd"?M.slice(1):M}).join(""),this._longDateFormat[_])}var le="Invalid date";function Be(){return this._invalidDate}var ze="%d",rt=/\d{1,2}/;function cr(_){return this._ordinal.replace("%d",_)}var Sn={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 je(_,C,T,M){var L=this._relativeTime[T];return N(L)?L(_,C,T,M):L.replace(/%d/i,_)}function mt(_,C){var T=this._relativeTime[_>0?"future":"past"];return N(T)?T(C):T.replace(/%s/i,C)}var ht={};function ft(_,C){var T=_.toLowerCase();ht[T]=ht[T+"s"]=ht[C]=_}function te(_){return typeof _=="string"?ht[_]||ht[_.toLowerCase()]:void 0}function et(_){var C={},T,M;for(M in _)i(_,M)&&(T=te(M),T&&(C[T]=_[M]));return C}var Re={};function Pe(_,C){Re[_]=C}function oe(_){var C=[],T;for(T in _)i(_,T)&&C.push({unit:T,priority:Re[T]});return C.sort(function(M,L){return M.priority-L.priority}),C}function se(_){return _%4===0&&_%100!==0||_%400===0}function ce(_){return _<0?Math.ceil(_)||0:Math.floor(_)}function Ce(_){var C=+_,T=0;return C!==0&&isFinite(C)&&(T=ce(C)),T}function Je(_,C){return function(T){return T!=null?(ea(this,_,T),e.updateOffset(this,C),this):ir(this,_)}}function ir(_,C){return _.isValid()?_._d["get"+(_._isUTC?"UTC":"")+C]():NaN}function ea(_,C,T){_.isValid()&&!isNaN(T)&&(C==="FullYear"&&se(_.year())&&_.month()===1&&_.date()===29?(T=Ce(T),_._d["set"+(_._isUTC?"UTC":"")+C](T,_.month(),aK(T,_.month()))):_._d["set"+(_._isUTC?"UTC":"")+C](T))}function ta(_){return _=te(_),N(this[_])?this[_]():this}function xc(_,C){if(typeof _=="object"){_=et(_);var T=oe(_),M,L=T.length;for(M=0;M<L;M++)this[T[M].unit](_[T[M].unit])}else if(_=te(_),N(this[_]))return this[_](C);return this}var Cd=/\d/,qi=/\d\d/,lp=/\d{3}/,yf=/\d{4}/,bf=/[+-]?\d{6}/,xn=/\d\d?/,_f=/\d\d\d\d?/,uC=/\d\d\d\d\d\d?/,kb=/\d{1,3}/,is=/\d{1,4}/,$s=/[+-]?\d{1,6}/,La=/\d+/,vf=/[+-]?\d+/,Od=/Z|[+-]\d\d:?\d\d/gi,ws=/Z|[+-]\d\d(?::?\d\d)?/gi,cp=/[+-]?\d+(\.\d{1,3})?/,wf=/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,In;In={};function Ye(_,C,T){In[_]=N(C)?C:function(M,L){return M&&T?T:C}}function Sf(_,C){return i(In,_)?In[_](C._strict,C._l Line truncated
${t?.cause?"more message: "+t.cause.message:""}
${e?t.stack:""}`:JSON.stringify(t)}function u4(t,e){let r={...t};return e.forEach(n=>{delete r[n]}),r}function eJ(t,e){let[r,n]=t.split("|"),o=e.find(i=>i.name===r&&i.provider===n);if(!o)throw new Error(`No model configuration found for: ${t}`);return o}function Xb(t){let e=hF[t];return{...e,label:e.label||t}}function kf(t,e){let r=hF[t]?.label||t;return r+(e?.believerExclusive&&r==="Copilot Plus"?"(Believer)":"")}async function l4(t,e=!1){let r=app.workspace.getMostRecentLeaf();if(!r){new Rh.Notice("No active leaf found.");return}if(r.view instanceof Rh.MarkdownView||(r=app.workspace.getLeaf(!1),await r.setViewState({type:"markdown",state:r.view.getState()})),!(r.view instanceof Rh.MarkdownView)){new Rh.Notice("Failed to open a markdown view.");return}let n=r.view.editor,o=n.getCursor("from"),i=n.getCursor("to"),a=FR(t);e?n.replaceRange(a,o,i):n.replaceRange(a,i),new Rh.Notice("Message inserted into the active note.")}function tJ(t,e){let r;return(...n)=>{clearTimeout(r),r=setTimeout(()=>t(...n),e)}}function rJ(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 bVe(){try{return{version:(await(0,Rh.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 LR(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 nJ(t,e="system"){return LR(t)?"human":e}function ege(){let t=["3rd party (openai-format)","ollama","lm-studio","azure openai","copilot-plus","copilot-plus-jina"];return Object.entries(hF).filter(([e])=>!t.includes(e)).map(([e])=>e)}function mF(t,e){let r=!!ege().find(i=>i===t.provider),n=Qb[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 rur(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>e.text).join(""):String(t||"")}function FR(t){let r=rur(t).replace(/<think>[\s\S]*?<\/think>/g,"");return r=r.replace(/<think>[\s\S]*$/g,""),r.trim()}function _Ve(){return crypto.randomUUID()}async function yy(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}}var Ghe,Rh,Whe,Jhe,Qsr,eur,fVe,Vl,Xhe,Cn=w(()=>{Fd();$r();yo();Ghe=F(uVe()),Rh=require("obsidian"),Whe={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}`};Jhe=(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})};Qsr=t=>t.last.bound.modelName||t.last.bound.model,eur=t=>t.last.bound.retriever!==void 0,fVe=t=>Qsr(t)||eur(t),Vl=(t,e="local")=>{let r=(0,Ghe.default)(t);return e==="utc"&&r.utc(),{fileName:r.format("YYYYMMDD_HHmmss"),display:r.format("YYYY/MM/DD HH:mm:ss"),epoch:r.valueOf()}};Xhe=/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|shorts\/)|youtu\.be\/)([^\s&]+)/});var gF,tge,c4,Fd=w(()=>{gy();qE();Sm();RHe();Cn();gF=class gF{static createNewLLMChain(e){let{llm:r,memory:n,prompt:o,abortController:i}=e,a=r.bind({signal:i?.signal}),s=bi.from([{input:u=>u.input,memory:()=>n.loadMemoryVariables({})},{input:u=>u.input,history:u=>u.memory.history},o,a]);return gF.instances.set("llm_chain",s),console.log("New LLM chain created."),s}static getLLMChainFromMap(e){let r=gF.instances.get("llm_chain");return r||(r=gF.createNewLLMChain(e)),r}static createConversationalRetrievalChain(e,r,n){let{llm:o,retriever:i,systemMessage:a}=e,u=Dd.fromTemplate(`Given the following conversation and a follow up question,
${e?t.stack:""}`:JSON.stringify(t)}function l4(t,e){let r={...t};return e.forEach(n=>{delete r[n]}),r}function tJ(t,e){let[r,n]=t.split("|"),o=e.find(i=>i.name===r&&i.provider===n);if(!o)throw new Error(`No model configuration found for: ${t}`);return o}function Xb(t){let e=gF[t];return{...e,label:e.label||t}}function kf(t,e){let r=gF[t]?.label||t;return r+(e?.believerExclusive&&r==="Copilot Plus"?"(Believer)":"")}async function c4(t,e=!1){let r=app.workspace.getMostRecentLeaf();if(!r){new Rh.Notice("No active leaf found.");return}if(r.view instanceof Rh.MarkdownView||(r=app.workspace.getLeaf(!1),await r.setViewState({type:"markdown",state:r.view.getState()})),!(r.view instanceof Rh.MarkdownView)){new Rh.Notice("Failed to open a markdown view.");return}let n=r.view.editor,o=n.getCursor("from"),i=n.getCursor("to"),a=kR(t);e?n.replaceRange(a,o,i):n.replaceRange(a,i),new Rh.Notice("Message inserted into the active note.")}function rJ(t,e){let r;return(...n)=>{clearTimeout(r),r=setTimeout(()=>t(...n),e)}}function nJ(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 vVe(){try{return{version:(await(0,Rh.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 FR(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 oJ(t,e="system"){return FR(t)?"human":e}function nge(){let t=["3rd party (openai-format)","ollama","lm-studio","azure openai","copilot-plus","copilot-plus-jina"];return Object.entries(gF).filter(([e])=>!t.includes(e)).map(([e])=>e)}function hF(t,e){let r=!!nge().find(i=>i===t.provider),n=Qb[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 sur(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>e.text).join(""):String(t||"")}function kR(t){let r=sur(t).replace(/<think>[\s\S]*?<\/think>/g,"");return r=r.replace(/<think>[\s\S]*$/g,""),r.trim()}function wVe(){return crypto.randomUUID()}async function yy(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}}var Zhe,Rh,Jhe,Xhe,our,iur,mVe,Vl,tge,yn=w(()=>{Fd();$r();yo();Zhe=F(cVe()),Rh=require("obsidian"),Jhe={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}`};Xhe=(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})};our=t=>t.last.bound.modelName||t.last.bound.model,iur=t=>t.last.bound.retriever!==void 0,mVe=t=>our(t)||iur(t),Vl=(t,e="local")=>{let r=(0,Zhe.default)(t);return e==="utc"&&r.utc(),{fileName:r.format("YYYYMMDD_HHmmss"),display:r.format("YYYY/MM/DD HH:mm:ss"),epoch:r.valueOf()}};tge=/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|shorts\/)|youtu\.be\/)([^\s&]+)/});var yF,oge,d4,Fd=w(()=>{gy();qE();Sm();NHe();yn();yF=class yF{static createNewLLMChain(e){let{llm:r,memory:n,prompt:o,abortController:i}=e,a=r.bind({signal:i?.signal}),s=bi.from([{input:u=>u.input,memory:()=>n.loadMemoryVariables({})},{input:u=>u.input,history:u=>u.memory.history},o,a]);return yF.instances.set("llm_chain",s),console.log("New LLM chain created."),s}static getLLMChainFromMap(e){let r=yF.instances.get("llm_chain");return r||(r=yF.createNewLLMChain(e)),r}static createConversationalRetrievalChain(e,r,n){let{llm:o,retriever:i,systemMessage:a}=e,u=Dd.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.
@@ -128,7 +128,7 @@ Answer the question with as detailed as possible based only on the following con
Question: {question}
`),d=b=>b.map(y=>`Human: ${y[0]}
Assistant: ${y[1]}`).join(`
`),f=bi.from([{question:b=>(n&&console.log("Input Question: ",b.question),b.question),chat_history:b=>{let g=d(b.chat_history);return n&&console.log("Formatted Chat History: ",g),g}},u,o,new zG,b=>{let g=FR(b);return n&&console.log("Standalone Question: ",g),g}]),p=async b=>(r(b),Ihe(b)),m=bi.from([{context:i.pipe(p),question:new go,system_message:()=>a},c,o]);return f.pipe(m)}};gF.instances=new Map;tge=gF,c4=tge});var d4=w(()=>{});var VE,Es,Pi,e_,aVe,sVe,f4,oJ,wVe,rge,SVe,nge,oge,t_,LC,jh,DC,WE,Zb,HE,jR,Khe,hF,Qb,xVe,Br,ige,Nh,Ic,Dh,$r=w(()=>{l2();Fd();d4();VE="https://api.brevilabs.com/v1",Es="copilot-chat-view",Pi="user",e_="ai",aVe=`You are Obsidian Copilot, a helpful assistant that integrates AI to Obsidian note-taking.
`),f=bi.from([{question:b=>(n&&console.log("Input Question: ",b.question),b.question),chat_history:b=>{let g=d(b.chat_history);return n&&console.log("Formatted Chat History: ",g),g}},u,o,new HG,b=>{let g=kR(b);return n&&console.log("Standalone Question: ",g),g}]),p=async b=>(r(b),jhe(b)),m=bi.from([{context:i.pipe(p),question:new go,system_message:()=>a},c,o]);return f.pipe(m)}};yF.instances=new Map;oge=yF,d4=oge});var f4=w(()=>{});var VE,Es,Pi,e_,SVe,xVe,uVe,lVe,p4,iJ,OVe,ige,PVe,age,sge,t_,FC,jh,LC,WE,Zb,HE,jR,Yhe,gF,Qb,EVe,Br,uge,Nh,Ic,Dh,$r=w(()=>{c2();Fd();f4();VE="https://api.brevilabs.com/v1",Es="copilot-chat-view",Pi="user",e_="ai",SVe="copilot-conversations",xVe="copilot-custom-prompts",uVe=`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.
@@ -141,7 +141,7 @@ Assistant: ${y[1]}`).join(`
10. When generating a table, use compact formatting without excessive whitespace.
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.`,sVe=`Return the new note content or canvas JSON in a special JSON format.
13. If the user mentions "tags", it most likely means tags in Obsidian note properties.`,lVe=`Return the new note content or canvas JSON in a special JSON format.
# 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.
@@ -201,88 +201,88 @@ Assistant: ${y[1]}`).join(`
- Every node must have: id, type, x, y, width, height
- Every edge must have: id, fromNode, toNode
- All IDs must be unique
- Edge fromNode and toNode must reference existing node IDs`,f4="note_context",oJ=`Copilot index does not exist. Please index your vault first!
- Edge fromNode and toNode must reference existing node IDs`,p4="note_context",iJ=`Copilot index does not exist. Please index your vault first!
1. Set a working embedding model in QA settings. If it's not a local model, don't forget to set the API key.
2. Click 'Refresh Index for Vault' and wait for indexing to complete. If you encounter the rate limiting error, please turn your request per second down in QA setting.`,wVe=6e3,rge=.4,SVe=.4,nge=15,oge=448e3,t_={DEFAULT:"",READING_FILES:"Reading files",SEARCHING_WEB:"Searching the web",READING_FILE_TREE:"Reading file tree"},LC={SETTINGS:"settings",EXPIRED_MODAL:"expired_modal",CHAT_MODE_SELECT:"chat_mode_select",MODE_SELECT_TOOLTIP:"mode_select_tooltip"},jh={MAX_TOKENS:6e3,TEMPERATURE:.1},DC=(m=>(m.OPENAI="openai",m.OPENAI_FORMAT="3rd party (openai-format)",m.AZURE_OPENAI="azure openai",m.ANTHROPIC="anthropic",m.COHEREAI="cohereai",m.GOOGLE="google",m.XAI="xai",m.OPENROUTERAI="openrouterai",m.GROQ="groq",m.OLLAMA="ollama",m.LM_STUDIO="lm-studio",m.COPILOT_PLUS="copilot-plus",m.MISTRAL="mistralai",m.DEEPSEEK="deepseek",m))(DC||{}),WE={reasoning:"This model supports general reasoning tasks.",vision:"This model supports image inputs.",websearch:"This model can access the internet."},Zb=[{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-preview-06-17",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:"gpt-4.1",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-4.1-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-4.1-nano",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"o4-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["reasoning"]},{name:"claude-sonnet-4-20250514",provider:"anthropic",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"claude-3-7-sonnet-latest",provider:"anthropic",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"claude-3-5-sonnet-latest",provider:"anthropic",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"claude-3-5-haiku-latest",provider:"anthropic",enabled:!0,isBuiltIn:!0},{name:"grok-3-beta",provider:"xai",enabled:!0,isBuiltIn:!0},{name:"grok-3-mini-beta",provider:"xai",enabled:!0,isBuiltIn:!0},{name:"gemini-2.5-flash",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gemini-2.5-pro",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"command-r",provider:"cohereai",enabled:!0,isBuiltIn:!0},{name:"command-r-plus",provider:"cohereai",enabled:!0,isBuiltIn:!0},{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"]}],HE=(l=>(l.OPENAI="openai",l.COHEREAI="cohereai",l.GOOGLE="google",l.AZURE_OPENAI="azure openai",l.OLLAMA="ollama",l.LM_STUDIO="lm-studio",l.OPENAI_FORMAT="3rd party (openai-format)",l.COPILOT_PLUS="copilot-plus",l.COPILOT_PLUS_JINA="copilot-plus-jina",l))(HE||{}),jR=[{name:"copilot-plus-small",provider:"copilot-plus",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,plusExclusive:!0},{name:"copilot-plus-large",provider:"copilot-plus-jina",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,plusExclusive:!0,believerExclusive:!0,dimensions:1024},{name:"copilot-plus-multilingual",provider:"copilot-plus-jina",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,plusExclusive:!0,dimensions:512},{name:"text-embedding-3-small",provider:"openai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0},{name:"text-embedding-3-large",provider:"openai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"embed-multilingual-light-v3.0",provider:"cohereai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"text-embedding-004",provider:"google",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"azure-openai",provider:"azure openai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0}],Khe="nomic-embed-text",hF={openai:{label:"OpenAI",host:"https://api.openai.com",keyManagementURL:"https://platform.openai.com/api-keys",listModelURL:"https://api.openai.com/v1/models",testModel:"gpt-4.1"},"azure openai":{label:"Azure OpenAI",host:"",keyManagementURL:"",listModelURL:"",testModel:"azure-openai"},anthropic:{label:"Anthropic",host:"https://api.anthropic.com/",keyManagementURL:"https://console.anthropic.com/settings/keys",listModelURL:"https://api.anthropic.com/v1/models",testModel:"claude-3-5-sonnet-latest"},cohereai:{label:"Cohere",host:"https://api.cohere.com",keyManagementURL:"https://dashboard.cohere.ai/api-keys",listModelURL:"https://api.cohere.com/v1/models",testModel:"command-r"},google:{label:"G Line truncated
`+Nge+t}var Dge=!1;function Lge(t,e){if(!t||Dge)return"";Dge=!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(`
2. Click 'Refresh Index for Vault' and wait for indexing to complete. If you encounter the rate limiting error, please turn your request per second down in QA setting.`,OVe=6e3,ige=.4,PVe=.4,age=15,sge=448e3,t_={DEFAULT:"",READING_FILES:"Reading files",SEARCHING_WEB:"Searching the web",READING_FILE_TREE:"Reading file tree"},FC={SETTINGS:"settings",EXPIRED_MODAL:"expired_modal",CHAT_MODE_SELECT:"chat_mode_select",MODE_SELECT_TOOLTIP:"mode_select_tooltip"},jh={MAX_TOKENS:6e3,TEMPERATURE:.1},LC=(m=>(m.OPENAI="openai",m.OPENAI_FORMAT="3rd party (openai-format)",m.AZURE_OPENAI="azure openai",m.ANTHROPIC="anthropic",m.COHEREAI="cohereai",m.GOOGLE="google",m.XAI="xai",m.OPENROUTERAI="openrouterai",m.GROQ="groq",m.OLLAMA="ollama",m.LM_STUDIO="lm-studio",m.COPILOT_PLUS="copilot-plus",m.MISTRAL="mistralai",m.DEEPSEEK="deepseek",m))(LC||{}),WE={reasoning:"This model supports general reasoning tasks.",vision:"This model supports image inputs.",websearch:"This model can access the internet."},Zb=[{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-preview-06-17",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:"gpt-4.1",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-4.1-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-4.1-nano",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"o4-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["reasoning"]},{name:"claude-sonnet-4-20250514",provider:"anthropic",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"claude-3-7-sonnet-latest",provider:"anthropic",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"claude-3-5-sonnet-latest",provider:"anthropic",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"claude-3-5-haiku-latest",provider:"anthropic",enabled:!0,isBuiltIn:!0},{name:"grok-3-beta",provider:"xai",enabled:!0,isBuiltIn:!0},{name:"grok-3-mini-beta",provider:"xai",enabled:!0,isBuiltIn:!0},{name:"gemini-2.5-flash",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gemini-2.5-pro",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"command-r",provider:"cohereai",enabled:!0,isBuiltIn:!0},{name:"command-r-plus",provider:"cohereai",enabled:!0,isBuiltIn:!0},{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"]}],HE=(l=>(l.OPENAI="openai",l.COHEREAI="cohereai",l.GOOGLE="google",l.AZURE_OPENAI="azure openai",l.OLLAMA="ollama",l.LM_STUDIO="lm-studio",l.OPENAI_FORMAT="3rd party (openai-format)",l.COPILOT_PLUS="copilot-plus",l.COPILOT_PLUS_JINA="copilot-plus-jina",l))(HE||{}),jR=[{name:"copilot-plus-small",provider:"copilot-plus",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,plusExclusive:!0},{name:"copilot-plus-large",provider:"copilot-plus-jina",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,plusExclusive:!0,believerExclusive:!0,dimensions:1024},{name:"copilot-plus-multilingual",provider:"copilot-plus-jina",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,plusExclusive:!0,dimensions:512},{name:"text-embedding-3-small",provider:"openai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0},{name:"text-embedding-3-large",provider:"openai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"embed-multilingual-light-v3.0",provider:"cohereai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"text-embedding-004",provider:"google",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"azure-openai",provider:"azure openai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0}],Yhe="nomic-embed-text",gF={openai:{label:"OpenAI",host:"https://api.openai.com",keyManagementURL:"https://platform.openai.com/api-keys",listModelURL:"https://api.openai.com/v1/models",testModel:"gpt-4.1"},"azure openai":{label:"Azure OpenAI",host:"",keyManagementURL:"",listModelURL:"",testModel:"azure-openai"},anthropic:{label:"Anthropic",host:"https://api.anthropic.com/",keyManagementURL:"https://console.anthropic.com/settings/keys",listModelURL:"https://api.anthropic.com/v1/models",testModel:"claude-3-5-sonnet-latest"},cohereai:{label:"Cohere",host:"https://api.cohere.com",keyManagementURL:"https://dashboard.cohere.ai/api-keys",listModelURL:"https://api.cohere.com/v1/models",testModel:"command-r"},google:{label:"G Line truncated
`+Fge+t}var kge=!1;function $ge(t,e){if(!t||kge)return"";kge=!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{Dge=!1,Error.prepareStackTrace=r}return(t=t?t.displayName||t.name:"")?P4(t):""}function zur(t){switch(t.tag){case 5:return P4(t.type);case 16:return P4("Lazy");case 13:return P4("Suspense");case 19:return P4("SuspenseList");case 0:case 2:case 15:return t=Lge(t.type,!1),t;case 11:return t=Lge(t.type.render,!1),t;case 1:return t=Lge(t.type,!0),t;default:return""}}function aye(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 PF:return"Fragment";case OF:return"Portal";case nye:return"Profiler";case Zye:return"StrictMode";case oye:return"Suspense";case iye:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case O6e:return(t.displayName||"Context")+".Consumer";case C6e:return(t._context.displayName||"Context")+".Provider";case Xye:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case Qye:return e=t.displayName||null,e!==null?e:aye(t.type)||"Memo";case ZE:e=t._payload,t=t._init;try{return aye(t(e))}catch{}}return null}function Hur(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 aye(e);case 8:return e===Zye?"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 dT(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function E6e(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function Vur(t){var e=E6e(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 SJ(t){t._valueTracker||(t._valueTracker=Vur(t))}function T6e(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var r=e.getValue(),n="";return t&&(n=E6e(t)?t.checked?"true":"false":t.value),t=n,t!==r?(e.setValue(t),!0):!1}function YJ(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 sye(t,e){var r=e.checked;return $a({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??t._wrapperState.initialChecked})}function _8e(t,e){var r=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;r=dT(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 A6e(t,e){e=e.checked,e!=null&&Yye(t,"checked",e,!1)}function uye(t,e){A6e(t,e);var r=dT(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")?lye(t,e.type,r):e.hasOwnProperty("defaultValue")&&lye(t,e.type,dT(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}function v8e(t,e,r){if(e.hasOwnProperty("value")||e.hasOwnProperty("defaultValue")){var n=e.type;if(!(n!=="submit"&&n!=="reset"||e.value!==void 0&&e.value!==null))return;e=""+t._wrapperState.initialValue,r||e===t.value||(t.value=e),t.defaultValue=e}r=t.name,r!==""&&(t.name=""),t.defaultChecked=!!t._wrapperState.initialChecked,r!==""&&(t.name=r)}function lye(t,e,r){(e!=="number"||YJ(t.ownerDocument)!==t)&&(r==null?t.defaultValue=""+t._wrapperState.initialValue:t.defaultValue!==""+r&&(t.defaultValue=""+r))}var E4=Array.isArray;function FF(t,e,r,n){if(t=t.options,e){e={};for(var o=0;o<r.length;o++)e["$"+r[o]]=!0;for(r=0;r<t.length;r++)o=e.hasOwnProperty("$"+t[r].value),t[r].selected!==o&&(t[r].selected=o),o&&n&&(t[r].defaultSelected=!0)}else{for(r=""+dT(r),e=null,o=0;o<t.length;o++){if(t[o].value===r){t[o].selected=!0,n&&(t[o].defaultSelected=!0);return}e!==null||t[o].disabled||(e=t[o])}e!==null&&(e.sele Line truncated
`).replace(Qlr,"")}function NJ(t,e,r){if(e=H8e(e),H8e(t)!==e&&r)throw Error(qe(425))}function o7(){}var xye=null,Cye=null;function Oye(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 Pye=typeof setTimeout=="function"?setTimeout:void 0,ecr=typeof clearTimeout=="function"?clearTimeout:void 0,V8e=typeof Promise=="function"?Promise:void 0,tcr=typeof queueMicrotask=="function"?queueMicrotask:typeof V8e<"u"?function(t){return V8e.resolve(null).then(t).catch(rcr)}:Pye;function rcr(t){setTimeout(function(){throw t})}function Wge(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),H4(e);return}n--}else r!=="$"&&r!=="$?"&&r!=="$!"||n++;r=o}while(r);H4(e)}function aT(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 W8e(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 ZF=Math.random().toString(36).slice(2),s_="__reactFiber$"+ZF,J4="__reactProps$"+ZF,HC="__reactContainer$"+ZF,Eye="__reactEvents$"+ZF,ncr="__reactListeners$"+ZF,ocr="__reactHandles$"+ZF;function KR(t){var e=t[s_];if(e)return e;for(var r=t.parentNode;r;){if(e=r[HC]||r[s_]){if(r=e.alternate,e.child!==null||r!==null&&r.child!==null)for(t=W8e(t);t!==null;){if(r=t[s_])return r;t=W8e(t)}return e}t=r,r=t.parentNode}return null}function o3(t){return t=t[s_]||t[HC],!t||t.tag!==5&&t.tag!==6&&t.tag!==13&&t.tag!==3?null:t}function IF(t){if(t.tag===5||t.tag===6)return t.stateNode;throw Error(qe(33))}function C7(t){return t[J4]||null}var Tye=[],MF=-1;function mT(t){return{current:t}}function aa(t){0>MF||(t.current=Tye[MF],Tye[MF]=null,MF--)}function zi(t,e){MF++,Tye[MF]=t.current,t.current=e}var fT={},Ud=mT(fT),Ap=mT(!1),XR=fT;function HF(t,e){var r=t.type.contextTypes;if(!r)return fT;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 Ip(t){return t=t.childContextTypes,t!=null}function i7(){aa(Ap),aa(Ud)}function K8e(t,e,r){if(Ud.current!==fT)throw Error(qe(168));zi(Ud,e),zi(Ap,r)}function y5e(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(qe(108,Hur(t)||"Unknown",o));return $a({},r,n)}function a7(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||fT,XR=Ud.current,zi(Ud,t),zi(Ap,Ap.current),!0}function G8e(t,e,r){var n=t.stateNode;if(!n)throw Error(qe(169));r?(t=y5e(t,e,XR),n.__reactInternalMemoizedMergedChildContext=t,aa(Ap),aa(Ud),zi(Ud,t)):aa(Ap),zi(Ap,r)}var $C=null,O7=!1,Kge=!1;function b5e(t){$C===null?$C=[t]:$C.push(t)}function icr(t){O7=!0,b5e(t)}function hT(){if(!Kge&&$C!==null){Kge=!0;var t=0,e=_i;try{var r=$C;for(_i=1;t<r.length;t++){var n=r[t];do n=n(!0);while(n!==null)}$C=null,O7=!1}catch(o){throw $C!==null&&($C=$C.slice(t+1)),z6e(tbe,hT),o}finally{_i=e,Kge=!1}}return null}var RF=[],jF=0,s7=null,u7=0,$h=[],Bh=0,QR=null,BC=1,qC="";function VR(t,e){RF[jF++]=u7,RF[jF++]=s7,s7=t,u7=e}function _5e(t,e,r){$h[Bh++]=BC,$h[Bh++]=qC,$h[Bh++]=QR,QR=t;var n=BC;t=qC;var o=32-Cy(n)-1;n&=~(1<<o),r+=1;var i=32-Cy(e)+o;if(30<i){var a=o-o%5;i=(n&(1<<a)-1).toString(32),n>>=a,o-=a,BC=1<<32-Cy(e)+o|r<<o|n,qC=i+t}else BC=1<<i|r<<o|n,qC=t}function cbe(t){t.return!==null&&(VR(t,1),_5e(t,1,0))}function dbe(t){for(;t===s7;)s7=RF[--jF],RF[jF]=null,u7=RF[--jF],RF[jF]=null;for(;t===QR;)QR=$h[--Bh],$h[Bh]=null,qC=$h[--Bh],$h[Bh]=null,BC=$h[--Bh],$h[Bh]=null}var Om=null,Cm=null,Ca=!1,xy=null;function v5e(t,e){var r=qh(5,null,null,0);r.elementType="DELETED",r.stateNode=e,r.return=t,e=t.deletions,e===null?(t.deletions=[r],t.flags|=16):e.push(r)}function J8e(t,e){switch(t.tag){case 5:var r=t.type;return e=e.nodeType!==1||r.toLowerCase()!==e.nodeName.toLowerCase()?null:e,e!==null?(t.stateNode=e,Om=t,Cm=aT(e.firstChild),!0):!1;case 6:return e=t.pendingProps===""||e.nodeType!==3?null:e,e!==null?(t.stateNode=e,Om=t,Cm=null,!0):!1;case 13:return e=e.nodeType!==8?null:e,e!==null?(r=QR!==null?{id:BC,overflow:qC}:null,t.memoizedState={dehydrated:e,treeContext:r,retryLane:1073741824},r=qh(18,null,null,0),r.stateNode=e,r.return=t,t.child=r,Om=t,Cm=null,!0):!1;default:return!1}}function Aye(t){return(t.mode&1)!==0&&(t.flags&128)===0}function Iye(t){if(Ca){var e=Cm;if(e){var r=e;if(!J8e(t,e)){if(Aye(t))throw Error(qe(418));e=aT(r.nextSibling);var n=Om;e&&J8e(t,e)?v5e(n,r):(t.flags=t.flags&-4097|2,Ca=!1,Om=t)}}else{if(Aye(t))throw Error(qe(418)) Line truncated
`+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{kge=!1,Error.prepareStackTrace=r}return(t=t?t.displayName||t.name:"")?E4(t):""}function Gur(t){switch(t.tag){case 5:return E4(t.type);case 16:return E4("Lazy");case 13:return E4("Suspense");case 19:return E4("SuspenseList");case 0:case 2:case 15:return t=$ge(t.type,!1),t;case 11:return t=$ge(t.type.render,!1),t;case 1:return t=$ge(t.type,!0),t;default:return""}}function lye(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 EF:return"Fragment";case PF:return"Portal";case aye:return"Profiler";case ebe:return"StrictMode";case sye:return"Suspense";case uye:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case A6e:return(t.displayName||"Context")+".Consumer";case T6e:return(t._context.displayName||"Context")+".Provider";case tbe:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case rbe:return e=t.displayName||null,e!==null?e:lye(t.type)||"Memo";case ZE:e=t._payload,t=t._init;try{return lye(t(e))}catch{}}return null}function Jur(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 lye(e);case 8:return e===ebe?"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 dT(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function M6e(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function Yur(t){var e=M6e(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 xJ(t){t._valueTracker||(t._valueTracker=Yur(t))}function R6e(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var r=e.getValue(),n="";return t&&(n=M6e(t)?t.checked?"true":"false":t.value),t=n,t!==r?(e.setValue(t),!0):!1}function ZJ(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 cye(t,e){var r=e.checked;return $a({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??t._wrapperState.initialChecked})}function x8e(t,e){var r=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;r=dT(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 j6e(t,e){e=e.checked,e!=null&&Qye(t,"checked",e,!1)}function dye(t,e){j6e(t,e);var r=dT(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")?fye(t,e.type,r):e.hasOwnProperty("defaultValue")&&fye(t,e.type,dT(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}function C8e(t,e,r){if(e.hasOwnProperty("value")||e.hasOwnProperty("defaultValue")){var n=e.type;if(!(n!=="submit"&&n!=="reset"||e.value!==void 0&&e.value!==null))return;e=""+t._wrapperState.initialValue,r||e===t.value||(t.value=e),t.defaultValue=e}r=t.name,r!==""&&(t.name=""),t.defaultChecked=!!t._wrapperState.initialChecked,r!==""&&(t.name=r)}function fye(t,e,r){(e!=="number"||ZJ(t.ownerDocument)!==t)&&(r==null?t.defaultValue=""+t._wrapperState.initialValue:t.defaultValue!==""+r&&(t.defaultValue=""+r))}var T4=Array.isArray;function kF(t,e,r,n){if(t=t.options,e){e={};for(var o=0;o<r.length;o++)e["$"+r[o]]=!0;for(r=0;r<t.length;r++)o=e.hasOwnProperty("$"+t[r].value),t[r].selected!==o&&(t[r].selected=o),o&&n&&(t[r].defaultSelected=!0)}else{for(r=""+dT(r),e=null,o=0;o<t.length;o++){if(t[o].value===r){t[o].selected=!0,n&&(t[o].defaultSelected=!0);return}e!==null||t[o].disabled||(e=t[o])}e!==null&&(e.sele Line truncated
`).replace(ocr,"")}function DJ(t,e,r){if(e=G8e(e),G8e(t)!==e&&r)throw Error(qe(425))}function i7(){}var Pye=null,Eye=null;function Tye(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 Aye=typeof setTimeout=="function"?setTimeout:void 0,icr=typeof clearTimeout=="function"?clearTimeout:void 0,J8e=typeof Promise=="function"?Promise:void 0,acr=typeof queueMicrotask=="function"?queueMicrotask:typeof J8e<"u"?function(t){return J8e.resolve(null).then(t).catch(scr)}:Aye;function scr(t){setTimeout(function(){throw t})}function Jge(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),V4(e);return}n--}else r!=="$"&&r!=="$?"&&r!=="$!"||n++;r=o}while(r);V4(e)}function aT(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 Y8e(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 XF=Math.random().toString(36).slice(2),s_="__reactFiber$"+XF,Y4="__reactProps$"+XF,VC="__reactContainer$"+XF,Iye="__reactEvents$"+XF,ucr="__reactListeners$"+XF,lcr="__reactHandles$"+XF;function GR(t){var e=t[s_];if(e)return e;for(var r=t.parentNode;r;){if(e=r[VC]||r[s_]){if(r=e.alternate,e.child!==null||r!==null&&r.child!==null)for(t=Y8e(t);t!==null;){if(r=t[s_])return r;t=Y8e(t)}return e}t=r,r=t.parentNode}return null}function i3(t){return t=t[s_]||t[VC],!t||t.tag!==5&&t.tag!==6&&t.tag!==13&&t.tag!==3?null:t}function MF(t){if(t.tag===5||t.tag===6)return t.stateNode;throw Error(qe(33))}function O7(t){return t[Y4]||null}var Mye=[],RF=-1;function mT(t){return{current:t}}function aa(t){0>RF||(t.current=Mye[RF],Mye[RF]=null,RF--)}function zi(t,e){RF++,Mye[RF]=t.current,t.current=e}var fT={},Ud=mT(fT),Ap=mT(!1),QR=fT;function VF(t,e){var r=t.type.contextTypes;if(!r)return fT;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 Ip(t){return t=t.childContextTypes,t!=null}function a7(){aa(Ap),aa(Ud)}function Z8e(t,e,r){if(Ud.current!==fT)throw Error(qe(168));zi(Ud,e),zi(Ap,r)}function w5e(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(qe(108,Jur(t)||"Unknown",o));return $a({},r,n)}function s7(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||fT,QR=Ud.current,zi(Ud,t),zi(Ap,Ap.current),!0}function X8e(t,e,r){var n=t.stateNode;if(!n)throw Error(qe(169));r?(t=w5e(t,e,QR),n.__reactInternalMemoizedMergedChildContext=t,aa(Ap),aa(Ud),zi(Ud,t)):aa(Ap),zi(Ap,r)}var BC=null,P7=!1,Yge=!1;function S5e(t){BC===null?BC=[t]:BC.push(t)}function ccr(t){P7=!0,S5e(t)}function hT(){if(!Yge&&BC!==null){Yge=!0;var t=0,e=_i;try{var r=BC;for(_i=1;t<r.length;t++){var n=r[t];do n=n(!0);while(n!==null)}BC=null,P7=!1}catch(o){throw BC!==null&&(BC=BC.slice(t+1)),K6e(obe,hT),o}finally{_i=e,Yge=!1}}return null}var jF=[],NF=0,u7=null,l7=0,$h=[],Bh=0,e1=null,qC=1,UC="";function WR(t,e){jF[NF++]=l7,jF[NF++]=u7,u7=t,l7=e}function x5e(t,e,r){$h[Bh++]=qC,$h[Bh++]=UC,$h[Bh++]=e1,e1=t;var n=qC;t=UC;var o=32-Cy(n)-1;n&=~(1<<o),r+=1;var i=32-Cy(e)+o;if(30<i){var a=o-o%5;i=(n&(1<<a)-1).toString(32),n>>=a,o-=a,qC=1<<32-Cy(e)+o|r<<o|n,UC=i+t}else qC=1<<i|r<<o|n,UC=t}function pbe(t){t.return!==null&&(WR(t,1),x5e(t,1,0))}function mbe(t){for(;t===u7;)u7=jF[--NF],jF[NF]=null,l7=jF[--NF],jF[NF]=null;for(;t===e1;)e1=$h[--Bh],$h[Bh]=null,UC=$h[--Bh],$h[Bh]=null,qC=$h[--Bh],$h[Bh]=null}var Om=null,Cm=null,Ca=!1,xy=null;function C5e(t,e){var r=qh(5,null,null,0);r.elementType="DELETED",r.stateNode=e,r.return=t,e=t.deletions,e===null?(t.deletions=[r],t.flags|=16):e.push(r)}function Q8e(t,e){switch(t.tag){case 5:var r=t.type;return e=e.nodeType!==1||r.toLowerCase()!==e.nodeName.toLowerCase()?null:e,e!==null?(t.stateNode=e,Om=t,Cm=aT(e.firstChild),!0):!1;case 6:return e=t.pendingProps===""||e.nodeType!==3?null:e,e!==null?(t.stateNode=e,Om=t,Cm=null,!0):!1;case 13:return e=e.nodeType!==8?null:e,e!==null?(r=e1!==null?{id:qC,overflow:UC}:null,t.memoizedState={dehydrated:e,treeContext:r,retryLane:1073741824},r=qh(18,null,null,0),r.stateNode=e,r.return=t,t.child=r,Om=t,Cm=null,!0):!1;default:return!1}}function Rye(t){return(t.mode&1)!==0&&(t.flags&128)===0}function jye(t){if(Ca){var e=Cm;if(e){var r=e;if(!Q8e(t,e)){if(Rye(t))throw Error(qe(418));e=aT(r.nextSibling);var n=Om;e&&Q8e(t,e)?C5e(n,r):(t.flags=t.flags&-4097|2,Ca=!1,Om=t)}}else{if(Rye(t))throw Error(qe(418)) Line truncated
Error generating stack: `+i.message+`
`+i.stack}return{value:t,source:e,stack:o,digest:null}}function Xge(t,e,r){return{value:t,source:null,stack:r??null,digest:e??null}}function Nye(t,e){try{console.error(e.value)}catch(r){setTimeout(function(){throw r})}}var mcr=typeof WeakMap=="function"?WeakMap:Map;function G5e(t,e,r){r=UC(-1,r),r.tag=3,r.payload={element:null};var n=e.value;return r.callback=function(){g7||(g7=!0,Hye=n),Nye(t,e)},r}function J5e(t,e,r){r=UC(-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(){Nye(t,e)}}var i=t.stateNode;return i!==null&&typeof i.componentDidCatch=="function"&&(r.callback=function(){Nye(t,e),typeof n!="function"&&(uT===null?uT=new Set([this]):uT.add(this));var a=e.stack;this.componentDidCatch(e.value,{componentStack:a!==null?a:""})}),r}function o6e(t,e,r){var n=t.pingCache;if(n===null){n=t.pingCache=new mcr;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=Tcr.bind(null,t,e,r),e.then(t,t))}function i6e(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 a6e(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=UC(-1,1),e.tag=2,sT(r,e,1))),r.lanes|=1),t):(t.flags|=65536,t.lanes=o,t)}var hcr=KC.ReactCurrentOwner,Tp=!1;function $f(t,e,r,n){e.child=t===null?E5e(e,null,r,n):WF(e,t.child,r,n)}function s6e(t,e,r,n,o){r=r.render;var i=e.ref;return qF(e,o),n=Sbe(t,e,r,n,i,o),r=xbe(),t!==null&&!Tp?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,WC(t,e,o)):(Ca&&r&&cbe(e),e.flags|=1,$f(t,e,n,o),e.child)}function u6e(t,e,r,n,o){if(t===null){var i=r.type;return typeof i=="function"&&!jbe(i)&&i.defaultProps===void 0&&r.compare===null&&r.defaultProps===void 0?(e.tag=15,e.type=i,Y5e(t,e,i,n,o)):(t=JJ(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:W4,r(a,n)&&t.ref===e.ref)return WC(t,e,o)}return e.flags|=1,t=cT(i,n),t.ref=e.ref,t.return=e,e.child=t}function Y5e(t,e,r,n,o){if(t!==null){var i=t.memoizedProps;if(W4(i,n)&&t.ref===e.ref)if(Tp=!1,e.pendingProps=n=i,(t.lanes&o)!==0)(t.flags&131072)!==0&&(Tp=!0);else return e.lanes=t.lanes,WC(t,e,o)}return Dye(t,e,r,n,o)}function Z5e(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},zi(LF,xm),xm|=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,zi(LF,xm),xm|=t,null;e.memoizedState={baseLanes:0,cachePool:null,transitions:null},n=i!==null?i.baseLanes:r,zi(LF,xm),xm|=n}else i!==null?(n=i.baseLanes|r,e.memoizedState=null):n=r,zi(LF,xm),xm|=n;return $f(t,e,o,r),e.child}function X5e(t,e){var r=e.ref;(t===null&&r!==null||t!==null&&t.ref!==r)&&(e.flags|=512,e.flags|=2097152)}function Dye(t,e,r,n,o){var i=Ip(r)?XR:Ud.current;return i=HF(e,i),qF(e,o),r=Sbe(t,e,r,n,i,o),n=xbe(),t!==null&&!Tp?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,WC(t,e,o)):(Ca&&n&&cbe(e),e.flags|=1,$f(t,e,r,o),e.child)}function l6e(t,e,r,n,o){if(Ip(r)){var i=!0;a7(e)}else i=!1;if(qF(e,o),e.stateNode===null)WJ(t,e),O5e(e,r,n),jye(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=zh(l):(l=Ip(r)?XR:Ud.current,l=HF(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)&&e6e(e,a,n,l),XE=!1;var f=e.memoizedState;a.state=f,d7(e,n,a,o),u=e.memoizedState,s!==n||f!==u||Ap.current||XE?(typeof c=="function"&&(Rye(e,r,c,n),u=e.memoizedState),(s=XE||Q8e(e,r,s,n,f,u,l))?(d||typeof a.UNSAFE_componentWillMount!="function"&&typeof a.componentWillMount!="function"||(typeof a.componentWillMount=="function"&&a.componentWillMount(),typeof a.UNSAFE_componentWillMount=="function"&&a.UNSAFE_componentWillMount()),typeof a.componentDidMount=="function"&&(e.flags|=4194308)):(typeof a.componentDidMount=="function"&&(e.flags|=4194308),e.memoizedProps=n,e.memoizedState=u),a.props=n,a.state=u,a.context=l,n=s):(typeof a.componentDidMount=="function"&&(e.flags|=4194308),n=!1)}else{a=e.stateNode,x5e(t,e),s=e.memoizedProps,l=e.type===e.elementType?s:wy(e.type,s),a.props=l,d=e.pendingProps,f=a.context,u=r.contextType,typeof u=="object"&&u!==null?u=zh(u):(u=Ip(r)?XR:Ud.current,u=HF(e,u));var p=r.getDerivedStateFromProps;(c=typeof p=="function"||typeof a.getSnapshotBeforeUpdate=="function")||typeof a.UNSAFE_componentWillReceiveProps!="function"&&typeof a.componentWillReceiveProps!="function"||(s!==d||f!==u)&&e6e(e,a,n,u),XE=! Line truncated
`)}});var UQe=v(xY=>{"use strict";Object.defineProperty(xY,"__esModule",{value:!0});xY.CohereTimeoutError=void 0;var r_e=class t extends Error{constructor(){super("Timeout"),Object.setPrototypeOf(this,t.prototype)}};xY.CohereTimeoutError=r_e});var As=v(ak=>{"use strict";Object.defineProperty(ak,"__esModule",{value:!0});ak.CohereTimeoutError=ak.CohereError=void 0;var cfr=qQe();Object.defineProperty(ak,"CohereError",{enumerable:!0,get:function(){return cfr.CohereError}});var dfr=UQe();Object.defineProperty(ak,"CohereTimeoutError",{enumerable:!0,get:function(){return dfr.CohereTimeoutError}})});var zQe=v(g_=>{"use strict";var ffr=g_&&g_.__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]}),pfr=g_&&g_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),mfr=g_&&g_.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&ffr(e,t,r);return pfr(e,t),e};Object.defineProperty(g_,"__esModule",{value:!0});g_.BadRequestError=void 0;var hfr=mfr(As()),n_e=class t extends hfr.CohereError{constructor(e){super({message:"BadRequestError",statusCode:400,body:e}),Object.setPrototypeOf(this,t.prototype)}};g_.BadRequestError=n_e});var HQe=v(y_=>{"use strict";var gfr=y_&&y_.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),yfr=y_&&y_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),bfr=y_&&y_.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&gfr(e,t,r);return yfr(e,t),e};Object.defineProperty(y_,"__esModule",{value:!0});y_.UnauthorizedError=void 0;var _fr=bfr(As()),o_e=class t extends _fr.CohereError{constructor(e){super({message:"UnauthorizedError",statusCode:401,body:e}),Object.setPrototypeOf(this,t.prototype)}};y_.UnauthorizedError=o_e});var VQe=v(b_=>{"use strict";var vfr=b_&&b_.__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]}),wfr=b_&&b_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Sfr=b_&&b_.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&vfr(e,t,r);return wfr(e,t),e};Object.defineProperty(b_,"__esModule",{value:!0});b_.ForbiddenError=void 0;var xfr=Sfr(As()),i_e=class t extends xfr.CohereError{constructor(e){super({message:"ForbiddenError",statusCode:403,body:e}),Object.setPrototypeOf(this,t.prototype)}};b_.ForbiddenError=i_e});var WQe=v(__=>{"use strict";var Cfr=__&&__.__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]}),Ofr=__&&__.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Pfr=__&&__.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Cfr(e,t,r);return Ofr(e,t),e};Object.defineProperty(__,"__esModule",{value:!0});__.NotFoundError=void 0;var Efr=Pfr(As()),a_e=class t extends Efr.CohereError{constructor(e){super({message:"NotFoundError",statusCode:404,body:e}),Object.setPrototypeOf(this,t.prototype)}};__.NotFoundError=a_e});var KQe=v(v_=>{"use strict";var Tfr=v_&&v_.__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]}),Afr=v_&&v_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Ifr=v_&&v_.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.has Line truncated
`));return r(o)}});var wot,_mr,vmr,wmr,Smr,xmr,Sot=w(()=>{wot=async t=>{let e=t?.Bucket||"";if(typeof t.Bucket=="string"&&(t.Bucket=e.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),xmr(e)){if(t.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!Smr(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},_mr=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,vmr=/(\d+\.){3}\d+/,wmr=/\.\./,Smr=t=>_mr.test(t)&&!vmr.test(t)&&!wmr.test(t),xmr=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 xot=w(()=>{Sot()});var Cot,Oot=w(()=>{Cot=(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 Pot,Eot=w(()=>{Pot=async t=>{}});function Tot(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 Aot=w(()=>{});var TT,dZ=w(()=>{Aot();TT=t=>{if(typeof t=="string")return TT(new URL(t));let{hostname:e,pathname:r,port:n,protocol:o,search:i}=t,a;return i&&(a=Tot(i)),{hostname:e,port:n?parseInt(n):void 0,protocol:o,path:r,query:a}}});var fZ,pZ=w(()=>{dZ();fZ=t=>typeof t=="object"?"url"in t?TT(t.url):t:TT(t)});var Iot,Cmr,Z_e=w(()=>{xot();Oot();Eot();pZ();Iot=async(t,e,r,n)=>{if(!r.endpoint){let a=await Pot(r.serviceId||"");a&&(r.endpoint=()=>Promise.resolve(fZ(a)))}let o=await Cmr(t,e,r);if(typeof r.endpointProvider!="function")throw new Error("config.endpointProvider is not set.");return r.endpointProvider(o,n)},Cmr=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 Cot(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 wot(n),n}});var Mot=w(()=>{Z_e();pZ()});var Rot,X_e=w(()=>{jy();Z_e();Rot=({config:t,instructions:e})=>(r,n)=>async o=>{let i=await Iot(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=A_(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 jot,Q_e=w(()=>{jot=(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 Not,eve=w(()=>{Not=(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 Nt(t,e,r){return{applyToStack:n=>{n.add(jot(t,r),Omr),n.add(Not(t,e),q3)}}}var Omr,q3,Dot=w(()=>{Q_e();eve();Omr={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},q3={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});var to=w(()=>{Q_e();Dot();eve()});var tve,Dt,Lot=w(()=>{to();X_e();tve={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:q3.name},Dt=(t,e)=>({applyToStack:r=>{r.addRelativeTo(Rot({config:t,instructions:e}),tve)}})});var mZ,Fot=w(()=>{jy();pZ();mZ=t=>{let e=t.tls??!0,{endpoint:r}=t,n=r!=null?async()=>fZ(await zd(r)()):void 0;return{...t,endpoint:n,tls:e,isCustomEndpoint:!!r,useDualstackEndpoint:zd(t.useDualstackEndpoint??!1),useFipsEndpoint:zd(t.useFipsEndpoint??!1)}}});var kot=w(()=>{});var zn=w(()=>{Mot();X_e();Lot();Fot();kot()});var Pmr,hZ,$ot=w(()=>{zn();cZ();Pmr={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:tve.name},hZ=(t,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:r})=>({applyToStack:n=>{n.addRelativeTo(Y_e(t,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:r}),Pmr)}})});var wXn,Bot=w(()=>{to();cZ();wXn={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:q3.name}});var qot=w(()=>{cZ();$ot();Bot()});var Uot=w(()=>{});var zot=w(()=>{Uot()});var Hot=w(()=>{Hs()});var Vot=w(()=>{});var Wot=w(()=>{});function Emr(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return{...e,[r]:Array.isArray(n)?[...n]:n}},{})}var P1,Kot=w(()=>{P1=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=Emr(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 Got=w(()=>{});var Jot=w(()=>{});var Yot=w(()=>{});var U3=w(()=>{zot();Hot();Vot();Wot();Kot();Got();Jot();Yot()});var Tmr,Amr,Zot,rve=w(()=>{U3();Hs();jy();Tmr=t=>e=>{throw e},Amr=(t,e)=>{},Zot=t=>(e,r)=>async n=>{if(!P1.isInstance(n.request))return e(n);let i=A_(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||Tmr)(a));return(u.successHandler||Amr)(l.response,a),l}});var Ny,I_,z3,gZ=w(()=>{(function(t){t.STANDARD="standard",t.ADAPTIVE="adaptive"})(Ny||(Ny={}));I_=3,z3=Ny.STANDARD});var Xot,Qot,eit,tit,rit=w(()=>{Xot=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],Qot=["TimeoutError","RequestTimeout","RequestTimeoutException"],eit=[500,502,503,504],tit=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"]});var Imr,fk,yZ,nit,H3=w(()=>{rit();Imr=t=>t.$metadata?.clockSkewCorrected,fk=t=>t.$metadata?.httpStatusCode===429||Xot.includes(t.name)||t.$retryable?.throttling==!0,yZ=t=>Imr(t)||Qot.includes(t.name)||tit.includes(t?.code||"")||eit.includes(t.$metadata?.httpStatusCode||0),nit=t=>{if(t.$metadata?.httpStatusCode!==void 0){let e=t.$metadata.httpStatusCode;return 500<=e&&e<=599&&!yZ(t)}return!1}});var V3,nve=w(()=>{H3();V3=class{constructor(e){this.currentCapacity=0,this.enabled=!1,this.lastMaxRate=0,this.measuredTxRate=0,this.requestCount=0,this.lastTimestamp=0,this.timeWindow=0,this.beta=e?.beta??.7,this.minCapacity=e?.minCapacity??1,this.minFillRate=e?.minFillRate??.5,this.scaleConstant=e?.scaleConstant??.4,this.smooth=e?.smooth??.8;let r=this.getCurrentTimeInSeconds();this.lastThrottleTime=r,this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}getCurrentTimeInSeconds(){return Date.now()/1e3}async getSendToken(){return Line truncated
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 jT(i);if(o==="hex")return uat(i);if(o===void 0||o==="utf8"||o==="utf-8")return OZ(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(cat);if(e=!0,dat(t))return n(t);if(wve(t))return t;throw new Error(`Cannot transform payload to web stream, got ${t}`)}})},dat=t=>typeof Blob=="function"&&t instanceof Blob});var mat=w(()=>{});var hat=w(()=>{});var xve=w(()=>{bve();zit();pat();mat();hat();Sve()});var DT,gat=w(()=>{xve();DT=async(t=new Uint8Array,e)=>{if(t instanceof Uint8Array)return cO.mutate(t);if(!t)return cO.mutate(new Uint8Array);let r=e.streamCollector(t);return cO.mutate(await r)}});var Ot,Cve,yat=w(()=>{dve();Hs();Ot=class{constructor(){this.middlewareStack=gk()}static classBuilder(){return new Cve}resolveMiddlewareWithContext(e,r,n,{middlewareFn:o,clientName:i,commandName:a,inputFilterSensitiveLog:s,outputFilterSensitiveLog:u,smithyContext:l,additionalContext:c,CommandCtor:d}){for(let b of o.bind(this)(d,e,r,n))this.middlewareStack.use(b);let f=e.concat(this.middlewareStack),{logger:p}=r,m={logger:p,clientName:i,commandName:a,inputFilterSensitiveLog:s,outputFilterSensitiveLog:u,[ck]:{commandInstance:this,...l},...c},{requestHandler:h}=r;return f.resolve(b=>h.handle(b.request,n||{}),m)}},Cve=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 Ot{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 EZ,bat=w(()=>{EZ="***SensitiveInformation***"});var TZ,_at=w(()=>{TZ=(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 R1,Fmr,vat,kmr,wat,Sat,xat,Ove,$mr,_k,ln,Cat,Oat,Bmr,J3,Y3,Pve,Pat,Eat,Tat,Eve=w(()=>{R1=t=>{if(t!=null){if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return String(e)!==String(t)&&Tat.warn(Eat(`Expected number but observed string: ${t}`)),e}if(typeof t=="number")return t;throw new TypeError(`Expected number, got ${typeof t}: ${t}`)}},Fmr=Math.ceil(34028234663852886e22),vat=t=>{let e=R1(t);if(e!==void 0&&!Number.isNaN(e)&&e!==1/0&&e!==-1/0&&Math.abs(e)>Fmr)throw new TypeError(`Expected 32-bit float, got ${t}`);return e},kmr=t=>{if(t!=null){if(Number.isInteger(t)&&!Number.isNaN(t))return t;throw new TypeError(`Expected integer, got ${typeof t}: ${t}`)}},wat=t=>Ove(t,32),Sat=t=>Ove(t,16),xat=t=>Ove(t,8),Ove=(t,e)=>{let r=kmr(t);if(r!==void 0&&$mr(r,e)!==r)throw new TypeError(`Expected ${e}-bit integer, got ${t}`);return r},$mr=(t,e)=>{switch(e){case 32:return Int32Array.of(t)[0];case 16:return Int16Array.of(t)[0];case 8:return Int8Array.of(t)[0]}},_k=(t,e)=>{if(t==null)throw e?new TypeError(`Expected a non-null value for ${e}`):new TypeError("Expected a non-null value");return t},ln=t=>{if(t!=null){if(typeof t=="string")return t;if(["boolean","number","bigint"].includes(typeof t))return Tat.warn(Eat(`Expected string, got ${typeof t}: ${t}`)),String(t);throw new TypeError(`Expected string, got ${typeof t}: ${t}`)}},Cat=t=>R1(typeof t=="string"?J3(t):t),Oat=t=>vat(typeof t=="string"?J3(t):t),Bmr=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,J3=t=>{let e=t.match(Bmr);if(e===null||e[0].length!==t.length)throw new TypeError("Expected real number, got implicit Line truncated
`+i.stack}return{value:t,source:e,stack:o,digest:null}}function tye(t,e,r){return{value:t,source:null,stack:r??null,digest:e??null}}function Fye(t,e){try{console.error(e.value)}catch(r){setTimeout(function(){throw r})}}var _cr=typeof WeakMap=="function"?WeakMap:Map;function X5e(t,e,r){r=zC(-1,r),r.tag=3,r.payload={element:null};var n=e.value;return r.callback=function(){y7||(y7=!0,Kye=n),Fye(t,e)},r}function Q5e(t,e,r){r=zC(-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(){Fye(t,e)}}var i=t.stateNode;return i!==null&&typeof i.componentDidCatch=="function"&&(r.callback=function(){Fye(t,e),typeof n!="function"&&(uT===null?uT=new Set([this]):uT.add(this));var a=e.stack;this.componentDidCatch(e.value,{componentStack:a!==null?a:""})}),r}function u6e(t,e,r){var n=t.pingCache;if(n===null){n=t.pingCache=new _cr;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=jcr.bind(null,t,e,r),e.then(t,t))}function l6e(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 c6e(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=zC(-1,1),e.tag=2,sT(r,e,1))),r.lanes|=1),t):(t.flags|=65536,t.lanes=o,t)}var vcr=GC.ReactCurrentOwner,Tp=!1;function $f(t,e,r,n){e.child=t===null?M5e(e,null,r,n):KF(e,t.child,r,n)}function d6e(t,e,r,n,o){r=r.render;var i=e.ref;return UF(e,o),n=Obe(t,e,r,n,i,o),r=Pbe(),t!==null&&!Tp?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,KC(t,e,o)):(Ca&&r&&pbe(e),e.flags|=1,$f(t,e,n,o),e.child)}function f6e(t,e,r,n,o){if(t===null){var i=r.type;return typeof i=="function"&&!Lbe(i)&&i.defaultProps===void 0&&r.compare===null&&r.defaultProps===void 0?(e.tag=15,e.type=i,eWe(t,e,i,n,o)):(t=YJ(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:K4,r(a,n)&&t.ref===e.ref)return KC(t,e,o)}return e.flags|=1,t=cT(i,n),t.ref=e.ref,t.return=e,e.child=t}function eWe(t,e,r,n,o){if(t!==null){var i=t.memoizedProps;if(K4(i,n)&&t.ref===e.ref)if(Tp=!1,e.pendingProps=n=i,(t.lanes&o)!==0)(t.flags&131072)!==0&&(Tp=!0);else return e.lanes=t.lanes,KC(t,e,o)}return kye(t,e,r,n,o)}function tWe(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},zi(FF,xm),xm|=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,zi(FF,xm),xm|=t,null;e.memoizedState={baseLanes:0,cachePool:null,transitions:null},n=i!==null?i.baseLanes:r,zi(FF,xm),xm|=n}else i!==null?(n=i.baseLanes|r,e.memoizedState=null):n=r,zi(FF,xm),xm|=n;return $f(t,e,o,r),e.child}function rWe(t,e){var r=e.ref;(t===null&&r!==null||t!==null&&t.ref!==r)&&(e.flags|=512,e.flags|=2097152)}function kye(t,e,r,n,o){var i=Ip(r)?QR:Ud.current;return i=VF(e,i),UF(e,o),r=Obe(t,e,r,n,i,o),n=Pbe(),t!==null&&!Tp?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,KC(t,e,o)):(Ca&&n&&pbe(e),e.flags|=1,$f(t,e,r,o),e.child)}function p6e(t,e,r,n,o){if(Ip(r)){var i=!0;s7(e)}else i=!1;if(UF(e,o),e.stateNode===null)KJ(t,e),A5e(e,r,n),Lye(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=zh(l):(l=Ip(r)?QR:Ud.current,l=VF(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)&&o6e(e,a,n,l),XE=!1;var f=e.memoizedState;a.state=f,f7(e,n,a,o),u=e.memoizedState,s!==n||f!==u||Ap.current||XE?(typeof c=="function"&&(Dye(e,r,c,n),u=e.memoizedState),(s=XE||n6e(e,r,s,n,f,u,l))?(d||typeof a.UNSAFE_componentWillMount!="function"&&typeof a.componentWillMount!="function"||(typeof a.componentWillMount=="function"&&a.componentWillMount(),typeof a.UNSAFE_componentWillMount=="function"&&a.UNSAFE_componentWillMount()),typeof a.componentDidMount=="function"&&(e.flags|=4194308)):(typeof a.componentDidMount=="function"&&(e.flags|=4194308),e.memoizedProps=n,e.memoizedState=u),a.props=n,a.state=u,a.context=l,n=s):(typeof a.componentDidMount=="function"&&(e.flags|=4194308),n=!1)}else{a=e.stateNode,E5e(t,e),s=e.memoizedProps,l=e.type===e.elementType?s:wy(e.type,s),a.props=l,d=e.pendingProps,f=a.context,u=r.contextType,typeof u=="object"&&u!==null?u=zh(u):(u=Ip(r)?QR:Ud.current,u=VF(e,u));var p=r.getDerivedStateFromProps;(c=typeof p=="function"||typeof a.getSnapshotBeforeUpdate=="function")||typeof a.UNSAFE_componentWillReceiveProps!="function"&&typeof a.componentWillReceiveProps!="function"||(s!==d||f!==u)&&o6e(e,a,n,u),XE=! Line truncated
`)}});var WQe=v(CY=>{"use strict";Object.defineProperty(CY,"__esModule",{value:!0});CY.CohereTimeoutError=void 0;var i_e=class t extends Error{constructor(){super("Timeout"),Object.setPrototypeOf(this,t.prototype)}};CY.CohereTimeoutError=i_e});var As=v(sk=>{"use strict";Object.defineProperty(sk,"__esModule",{value:!0});sk.CohereTimeoutError=sk.CohereError=void 0;var hfr=VQe();Object.defineProperty(sk,"CohereError",{enumerable:!0,get:function(){return hfr.CohereError}});var gfr=WQe();Object.defineProperty(sk,"CohereTimeoutError",{enumerable:!0,get:function(){return gfr.CohereTimeoutError}})});var KQe=v(g_=>{"use strict";var yfr=g_&&g_.__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]}),bfr=g_&&g_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),_fr=g_&&g_.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&yfr(e,t,r);return bfr(e,t),e};Object.defineProperty(g_,"__esModule",{value:!0});g_.BadRequestError=void 0;var vfr=_fr(As()),a_e=class t extends vfr.CohereError{constructor(e){super({message:"BadRequestError",statusCode:400,body:e}),Object.setPrototypeOf(this,t.prototype)}};g_.BadRequestError=a_e});var GQe=v(y_=>{"use strict";var wfr=y_&&y_.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Sfr=y_&&y_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),xfr=y_&&y_.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&wfr(e,t,r);return Sfr(e,t),e};Object.defineProperty(y_,"__esModule",{value:!0});y_.UnauthorizedError=void 0;var Cfr=xfr(As()),s_e=class t extends Cfr.CohereError{constructor(e){super({message:"UnauthorizedError",statusCode:401,body:e}),Object.setPrototypeOf(this,t.prototype)}};y_.UnauthorizedError=s_e});var JQe=v(b_=>{"use strict";var Ofr=b_&&b_.__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]}),Pfr=b_&&b_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Efr=b_&&b_.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Ofr(e,t,r);return Pfr(e,t),e};Object.defineProperty(b_,"__esModule",{value:!0});b_.ForbiddenError=void 0;var Tfr=Efr(As()),u_e=class t extends Tfr.CohereError{constructor(e){super({message:"ForbiddenError",statusCode:403,body:e}),Object.setPrototypeOf(this,t.prototype)}};b_.ForbiddenError=u_e});var YQe=v(__=>{"use strict";var Afr=__&&__.__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]}),Ifr=__&&__.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Mfr=__&&__.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Afr(e,t,r);return Ifr(e,t),e};Object.defineProperty(__,"__esModule",{value:!0});__.NotFoundError=void 0;var Rfr=Mfr(As()),l_e=class t extends Rfr.CohereError{constructor(e){super({message:"NotFoundError",statusCode:404,body:e}),Object.setPrototypeOf(this,t.prototype)}};__.NotFoundError=l_e});var ZQe=v(v_=>{"use strict";var jfr=v_&&v_.__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]}),Nfr=v_&&v_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Dfr=v_&&v_.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.has Line truncated
`));return r(o)}});var Oot,Cmr,Omr,Pmr,Emr,Tmr,Pot=w(()=>{Oot=async t=>{let e=t?.Bucket||"";if(typeof t.Bucket=="string"&&(t.Bucket=e.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),Tmr(e)){if(t.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!Emr(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},Cmr=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,Omr=/(\d+\.){3}\d+/,Pmr=/\.\./,Emr=t=>Cmr.test(t)&&!Omr.test(t)&&!Pmr.test(t),Tmr=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 Eot=w(()=>{Pot()});var Tot,Aot=w(()=>{Tot=(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 Iot,Mot=w(()=>{Iot=async t=>{}});function Rot(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 jot=w(()=>{});var TT,fZ=w(()=>{jot();TT=t=>{if(typeof t=="string")return TT(new URL(t));let{hostname:e,pathname:r,port:n,protocol:o,search:i}=t,a;return i&&(a=Rot(i)),{hostname:e,port:n?parseInt(n):void 0,protocol:o,path:r,query:a}}});var pZ,mZ=w(()=>{fZ();pZ=t=>typeof t=="object"?"url"in t?TT(t.url):t:TT(t)});var Not,Amr,eve=w(()=>{Eot();Aot();Mot();mZ();Not=async(t,e,r,n)=>{if(!r.endpoint){let a=await Iot(r.serviceId||"");a&&(r.endpoint=()=>Promise.resolve(pZ(a)))}let o=await Amr(t,e,r);if(typeof r.endpointProvider!="function")throw new Error("config.endpointProvider is not set.");return r.endpointProvider(o,n)},Amr=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 Tot(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 Oot(n),n}});var Dot=w(()=>{eve();mZ()});var Lot,tve=w(()=>{jy();eve();Lot=({config:t,instructions:e})=>(r,n)=>async o=>{let i=await Not(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=A_(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 Fot,rve=w(()=>{Fot=(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 kot,nve=w(()=>{kot=(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 Nt(t,e,r){return{applyToStack:n=>{n.add(Fot(t,r),Imr),n.add(kot(t,e),U3)}}}var Imr,U3,$ot=w(()=>{rve();nve();Imr={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},U3={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});var to=w(()=>{rve();$ot();nve()});var ove,Dt,Bot=w(()=>{to();tve();ove={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:U3.name},Dt=(t,e)=>({applyToStack:r=>{r.addRelativeTo(Lot({config:t,instructions:e}),ove)}})});var hZ,qot=w(()=>{jy();mZ();hZ=t=>{let e=t.tls??!0,{endpoint:r}=t,n=r!=null?async()=>pZ(await zd(r)()):void 0;return{...t,endpoint:n,tls:e,isCustomEndpoint:!!r,useDualstackEndpoint:zd(t.useDualstackEndpoint??!1),useFipsEndpoint:zd(t.useFipsEndpoint??!1)}}});var Uot=w(()=>{});var zn=w(()=>{Dot();tve();Bot();qot();Uot()});var Mmr,gZ,zot=w(()=>{zn();dZ();Mmr={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:ove.name},gZ=(t,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:r})=>({applyToStack:n=>{n.addRelativeTo(Q_e(t,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:r}),Mmr)}})});var PXn,Hot=w(()=>{to();dZ();PXn={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:U3.name}});var Vot=w(()=>{dZ();zot();Hot()});var Wot=w(()=>{});var Kot=w(()=>{Wot()});var Got=w(()=>{Hs()});var Jot=w(()=>{});var Yot=w(()=>{});function Rmr(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return{...e,[r]:Array.isArray(n)?[...n]:n}},{})}var E1,Zot=w(()=>{E1=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=Rmr(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 Xot=w(()=>{});var Qot=w(()=>{});var eit=w(()=>{});var z3=w(()=>{Kot();Got();Jot();Yot();Zot();Xot();Qot();eit()});var jmr,Nmr,tit,ive=w(()=>{z3();Hs();jy();jmr=t=>e=>{throw e},Nmr=(t,e)=>{},tit=t=>(e,r)=>async n=>{if(!E1.isInstance(n.request))return e(n);let i=A_(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||jmr)(a));return(u.successHandler||Nmr)(l.response,a),l}});var Ny,I_,H3,yZ=w(()=>{(function(t){t.STANDARD="standard",t.ADAPTIVE="adaptive"})(Ny||(Ny={}));I_=3,H3=Ny.STANDARD});var rit,nit,oit,iit,ait=w(()=>{rit=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],nit=["TimeoutError","RequestTimeout","RequestTimeoutException"],oit=[500,502,503,504],iit=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"]});var Dmr,pk,bZ,sit,V3=w(()=>{ait();Dmr=t=>t.$metadata?.clockSkewCorrected,pk=t=>t.$metadata?.httpStatusCode===429||rit.includes(t.name)||t.$retryable?.throttling==!0,bZ=t=>Dmr(t)||nit.includes(t.name)||iit.includes(t?.code||"")||oit.includes(t.$metadata?.httpStatusCode||0),sit=t=>{if(t.$metadata?.httpStatusCode!==void 0){let e=t.$metadata.httpStatusCode;return 500<=e&&e<=599&&!bZ(t)}return!1}});var W3,ave=w(()=>{V3();W3=class{constructor(e){this.currentCapacity=0,this.enabled=!1,this.lastMaxRate=0,this.measuredTxRate=0,this.requestCount=0,this.lastTimestamp=0,this.timeWindow=0,this.beta=e?.beta??.7,this.minCapacity=e?.minCapacity??1,this.minFillRate=e?.minFillRate??.5,this.scaleConstant=e?.scaleConstant??.4,this.smooth=e?.smooth??.8;let r=this.getCurrentTimeInSeconds();this.lastThrottleTime=r,this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}getCurrentTimeInSeconds(){return Date.now()/1e3}async getSendToken(){return Line truncated
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 jT(i);if(o==="hex")return fat(i);if(o===void 0||o==="utf8"||o==="utf-8")return PZ(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(mat);if(e=!0,hat(t))return n(t);if(Cve(t))return t;throw new Error(`Cannot transform payload to web stream, got ${t}`)}})},hat=t=>typeof Blob=="function"&&t instanceof Blob});var bat=w(()=>{});var _at=w(()=>{});var Pve=w(()=>{wve();Kit();yat();bat();_at();Ove()});var DT,vat=w(()=>{Pve();DT=async(t=new Uint8Array,e)=>{if(t instanceof Uint8Array)return dO.mutate(t);if(!t)return dO.mutate(new Uint8Array);let r=e.streamCollector(t);return dO.mutate(await r)}});var Ot,Eve,wat=w(()=>{mve();Hs();Ot=class{constructor(){this.middlewareStack=yk()}static classBuilder(){return new Eve}resolveMiddlewareWithContext(e,r,n,{middlewareFn:o,clientName:i,commandName:a,inputFilterSensitiveLog:s,outputFilterSensitiveLog:u,smithyContext:l,additionalContext:c,CommandCtor:d}){for(let b of o.bind(this)(d,e,r,n))this.middlewareStack.use(b);let f=e.concat(this.middlewareStack),{logger:p}=r,m={logger:p,clientName:i,commandName:a,inputFilterSensitiveLog:s,outputFilterSensitiveLog:u,[dk]:{commandInstance:this,...l},...c},{requestHandler:h}=r;return f.resolve(b=>h.handle(b.request,n||{}),m)}},Eve=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 Ot{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 TZ,Sat=w(()=>{TZ="***SensitiveInformation***"});var AZ,xat=w(()=>{AZ=(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 j1,Umr,Cat,zmr,Oat,Pat,Eat,Tve,Hmr,vk,ln,Tat,Aat,Vmr,Y3,Z3,Ave,Iat,Mat,Rat,Ive=w(()=>{j1=t=>{if(t!=null){if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return String(e)!==String(t)&&Rat.warn(Mat(`Expected number but observed string: ${t}`)),e}if(typeof t=="number")return t;throw new TypeError(`Expected number, got ${typeof t}: ${t}`)}},Umr=Math.ceil(34028234663852886e22),Cat=t=>{let e=j1(t);if(e!==void 0&&!Number.isNaN(e)&&e!==1/0&&e!==-1/0&&Math.abs(e)>Umr)throw new TypeError(`Expected 32-bit float, got ${t}`);return e},zmr=t=>{if(t!=null){if(Number.isInteger(t)&&!Number.isNaN(t))return t;throw new TypeError(`Expected integer, got ${typeof t}: ${t}`)}},Oat=t=>Tve(t,32),Pat=t=>Tve(t,16),Eat=t=>Tve(t,8),Tve=(t,e)=>{let r=zmr(t);if(r!==void 0&&Hmr(r,e)!==r)throw new TypeError(`Expected ${e}-bit integer, got ${t}`);return r},Hmr=(t,e)=>{switch(e){case 32:return Int32Array.of(t)[0];case 16:return Int16Array.of(t)[0];case 8:return Int8Array.of(t)[0]}},vk=(t,e)=>{if(t==null)throw e?new TypeError(`Expected a non-null value for ${e}`):new TypeError("Expected a non-null value");return t},ln=t=>{if(t!=null){if(typeof t=="string")return t;if(["boolean","number","bigint"].includes(typeof t))return Rat.warn(Mat(`Expected string, got ${typeof t}: ${t}`)),String(t);throw new TypeError(`Expected string, got ${typeof t}: ${t}`)}},Tat=t=>j1(typeof t=="string"?Y3(t):t),Aat=t=>Cat(typeof t=="string"?Y3(t):t),Vmr=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,Y3=t=>{let e=t.match(Vmr);if(e===null||e[0].length!==t.length)throw new TypeError("Expected real number, got implicit Line truncated
`).slice(0,5).filter(e=>!e.includes("stackTraceWarning")).join(`
`),Tat={warn:console.warn}});var qmr,Umr,Aat,zmr,Iat,hro,gro,yro,AZ,Mat,bro,Hmr,Vmr,Wmr,j1,Kmr,Gmr,Tve,Rat=w(()=>{Eve();qmr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Umr=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),Aat=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=Umr.exec(t);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");let[r,n,o,i,a,s,u,l]=e,c=Pve(Tve(n)),d=j1(o,"month",1,12),f=j1(i,"day",1,31);return Mat(c,d,f,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l})},zmr=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),Iat=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=zmr.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=Pve(Tve(n)),f=j1(o,"month",1,12),p=j1(i,"day",1,31),m=Mat(d,f,p,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l});return c.toUpperCase()!="Z"&&m.setTime(m.getTime()-Gmr(c)),m},hro=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$/),gro=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$/),yro=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})$/),AZ=t=>{if(t==null)return;let e;if(typeof t=="number")e=t;else if(typeof t=="string")e=Cat(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))},Mat=(t,e,r,n)=>{let o=e-1;return Vmr(t,o,r),new Date(Date.UTC(t,o,r,j1(n.hours,"hour",0,23),j1(n.minutes,"minute",0,59),j1(n.seconds,"seconds",0,60),Kmr(n.fractionalMilliseconds)))},bro=50*365*24*60*60*1e3,Hmr=[31,28,31,30,31,30,31,31,30,31,30,31],Vmr=(t,e,r)=>{let n=Hmr[e];if(e===1&&Wmr(t)&&(n=29),r>n)throw new TypeError(`Invalid day for ${qmr[e]} in ${t}: ${r}`)},Wmr=t=>t%4===0&&(t%100!==0||t%400===0),j1=(t,e,r,n)=>{let o=Pat(Tve(t));if(o<r||o>n)throw new TypeError(`${e} must be between ${r} and ${n}, inclusive`);return o},Kmr=t=>t==null?0:Oat("0."+t)*1e3,Gmr=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},Tve=t=>{let e=0;for(;e<t.length-1&&t.charAt(e)==="0";)e++;return e===0?t:t.slice(e)}});var vk,qa,Ave=w(()=>{vk=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}},qa=(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 Jmr,IZ,Ymr,jat=w(()=>{Ave();Jmr=({output:t,parsedBody:e,exceptionCtor:r,errorCode:n})=>{let o=Ymr(t),i=o.httpStatusCode?o.httpStatusCode+"":void 0,a=new r({name:e?.code||e?.Code||n||i||"UnknownError",$fault:"client",$metadata:o});throw qa(a,e)},IZ=t=>({output:e,parsedBody:r,errorCode:n})=>{Jmr({output:e,parsedBody:r,exceptionCtor:t,errorCode:n})},Ymr=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 MZ,Nat=w(()=>{MZ=t=>{switch(t){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"mobile":return{retryMode:"standard",connectionTimeout:3e4};default:return{}}}});var Dat=w(()=>{});var Lat,Fat,kat=w(()=>{Hs();Lat=t=>{let e=[];for(let r in lk){let n=lk[r];t[n]!==void 0&&e.push({algorithmId:()=>n,checksumConstructor:()=>t[n]})}return{_checksumAlgorithms:e,addChecksumAlgorithm(r){this._checksumAlgorithms.push(r)},checksumAlgorithms(){return this._checksumAlgorithms}}},Fat=t=>{let e={};return t.checksumAlgorithms().forEach(r=>{e[r.algorithmId()]=r.checksumConstructor()}),e}});var $at,Bat,qat=w(()=>{$at=t=>{let e=t.retryStrategy;return{setRetryStrategy(r){e=r},retryStrategy(){return e}}},Bat=t=>{let e={};return e.retryStrategy=t.retryStrategy(),e}});var RZ,jZ,Uat=w(()=>{kat();qat();RZ=t=>({...Lat(t),...$at(t)}),jZ=t=>({...Fat(t),...Bat(t)})});var zat=w(()=>{Uat()});function NZ(t){return encodeURIComponent(t).replace(/[!'()*]/ Line truncated
`);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}=GZ(r),u=new this.sha256(await this.getSigningKey(i,a,s,o));return u.update(kT(e)),Dy(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=KZ(e),{longDate:c,shortDate:d}=GZ(r),f=HZ(d,u,a??this.service);l.headers[Wve]=c,s.sessionToken&&(l.headers[rut]=s.sessionToken);let p=await oH(l,this.sha256);!yut(nH,l.headers)&&this.applyChecksum&&(l.headers[nH]=p);let m=VZ(l,o,n),h=await this.getSignature(c,f,this.getSigningKey(s,u,d,a),this.createCanonicalRequest(l,m,p));return l.headers[Vve]=`${UZ} Credential=${s.accessKeyId}/${f}, SignedHeaders=${wut(m)}, Signature=${h}`,l}createCanonicalRequest(e,r,n){let o=Object.keys(r).sort();return`${e.method}
`),Rat={warn:console.warn}});var Wmr,Kmr,jat,Gmr,Nat,vro,wro,Sro,IZ,Dat,xro,Jmr,Ymr,Zmr,N1,Xmr,Qmr,Mve,Lat=w(()=>{Ive();Wmr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Kmr=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),jat=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=Kmr.exec(t);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");let[r,n,o,i,a,s,u,l]=e,c=Ave(Mve(n)),d=N1(o,"month",1,12),f=N1(i,"day",1,31);return Dat(c,d,f,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l})},Gmr=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),Nat=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=Gmr.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=Ave(Mve(n)),f=N1(o,"month",1,12),p=N1(i,"day",1,31),m=Dat(d,f,p,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l});return c.toUpperCase()!="Z"&&m.setTime(m.getTime()-Qmr(c)),m},vro=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$/),wro=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$/),Sro=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})$/),IZ=t=>{if(t==null)return;let e;if(typeof t=="number")e=t;else if(typeof t=="string")e=Tat(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))},Dat=(t,e,r,n)=>{let o=e-1;return Ymr(t,o,r),new Date(Date.UTC(t,o,r,N1(n.hours,"hour",0,23),N1(n.minutes,"minute",0,59),N1(n.seconds,"seconds",0,60),Xmr(n.fractionalMilliseconds)))},xro=50*365*24*60*60*1e3,Jmr=[31,28,31,30,31,30,31,31,30,31,30,31],Ymr=(t,e,r)=>{let n=Jmr[e];if(e===1&&Zmr(t)&&(n=29),r>n)throw new TypeError(`Invalid day for ${Wmr[e]} in ${t}: ${r}`)},Zmr=t=>t%4===0&&(t%100!==0||t%400===0),N1=(t,e,r,n)=>{let o=Iat(Mve(t));if(o<r||o>n)throw new TypeError(`${e} must be between ${r} and ${n}, inclusive`);return o},Xmr=t=>t==null?0:Aat("0."+t)*1e3,Qmr=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},Mve=t=>{let e=0;for(;e<t.length-1&&t.charAt(e)==="0";)e++;return e===0?t:t.slice(e)}});var wk,qa,Rve=w(()=>{wk=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}},qa=(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 ehr,MZ,thr,Fat=w(()=>{Rve();ehr=({output:t,parsedBody:e,exceptionCtor:r,errorCode:n})=>{let o=thr(t),i=o.httpStatusCode?o.httpStatusCode+"":void 0,a=new r({name:e?.code||e?.Code||n||i||"UnknownError",$fault:"client",$metadata:o});throw qa(a,e)},MZ=t=>({output:e,parsedBody:r,errorCode:n})=>{ehr({output:e,parsedBody:r,exceptionCtor:t,errorCode:n})},thr=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 RZ,kat=w(()=>{RZ=t=>{switch(t){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"mobile":return{retryMode:"standard",connectionTimeout:3e4};default:return{}}}});var $at=w(()=>{});var Bat,qat,Uat=w(()=>{Hs();Bat=t=>{let e=[];for(let r in ck){let n=ck[r];t[n]!==void 0&&e.push({algorithmId:()=>n,checksumConstructor:()=>t[n]})}return{_checksumAlgorithms:e,addChecksumAlgorithm(r){this._checksumAlgorithms.push(r)},checksumAlgorithms(){return this._checksumAlgorithms}}},qat=t=>{let e={};return t.checksumAlgorithms().forEach(r=>{e[r.algorithmId()]=r.checksumConstructor()}),e}});var zat,Hat,Vat=w(()=>{zat=t=>{let e=t.retryStrategy;return{setRetryStrategy(r){e=r},retryStrategy(){return e}}},Hat=t=>{let e={};return e.retryStrategy=t.retryStrategy(),e}});var jZ,NZ,Wat=w(()=>{Uat();Vat();jZ=t=>({...Bat(t),...zat(t)}),NZ=t=>({...qat(t),...Hat(t)})});var Kat=w(()=>{Wat()});function DZ(t){return encodeURIComponent(t).replace(/[!'()*]/ Line truncated
`);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}=JZ(r),u=new this.sha256(await this.getSigningKey(i,a,s,o));return u.update(kT(e)),Dy(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=GZ(e),{longDate:c,shortDate:d}=JZ(r),f=VZ(d,u,a??this.service);l.headers[Jve]=c,s.sessionToken&&(l.headers[aut]=s.sessionToken);let p=await iH(l,this.sha256);!wut(oH,l.headers)&&this.applyChecksum&&(l.headers[oH]=p);let m=WZ(l,o,n),h=await this.getSignature(c,f,this.getSigningKey(s,u,d,a),this.createCanonicalRequest(l,m,p));return l.headers[Gve]=`${zZ} Credential=${s.accessKeyId}/${f}, SignedHeaders=${Out(m)}, Signature=${h}`,l}createCanonicalRequest(e,r,n){let o=Object.keys(r).sort();return`${e.method}
${this.getCanonicalPath(e)}
${Zve(e)}
${ewe(e)}
${o.map(i=>`${i}:${r[i]}`).join(`
`)}
${o.join(";")}
${n}`}async createStringToSign(e,r,n){let o=new this.sha256;o.update(kT(n));let i=await o.digest();return`${UZ}
${n}`}async createStringToSign(e,r,n){let o=new this.sha256;o.update(kT(n));let i=await o.digest();return`${zZ}
${e}
${r}
${Dy(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 Yh(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(kT(i)),Dy(await a.digest())}getSigningKey(e,r,n,o){return dut(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")}},GZ=t=>{let e=_ut(t).replace(/[\-:]/g,"");return{longDate:e,shortDate:e.slice(0,8)}},wut=t=>Object.keys(t).sort().join(";")});var xut=w(()=>{Sut();Yve();Xve();Qve();rwe();nwe();Jve()});var JZ,Cut=w(()=>{LT();xut();JZ=t=>{let e;t.credentials&&(e=lst(t.credentials,ust,Nve)),e||(t.credentialDefaultProvider?e=xk(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=xk(t.signer):t.regionInfoProvider?i=()=>xk(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||iH;return new d(c)}):i=async a=>{a=Object.assign({},{name:"sigv4",signingName:t.signingName||t.defaultSigningName,signingRegion:await xk(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||iH;return new c(l)},{...t,systemClockOffset:n,signingEscapePath:r,credentials:e,signer:i}}});var Out=w(()=>{Hst();Vst();Cut()});var Put=w(()=>{Out()});var Eut=w(()=>{});var Tut=w(()=>{ar()});var YZ,owe=w(()=>{ar();YZ=(t,e)=>DT(t,e).then(r=>e.utf8Encoder(r))});var Is,Aut,Iut,Mut=w(()=>{owe();Is=(t,e)=>YZ(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{}}),Aut=async(t,e)=>{let r=await Is(t,e);return r.message=r.message??r.Message,r},Iut=(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 ZZ=v(dO=>{"use strict";var Rut=":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",ghr=Rut+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",jut="["+Rut+"]["+ghr+"]*",yhr=new RegExp("^"+jut+"$"),bhr=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},_hr=function(t){let e=yhr.exec(t);return!(e===null||typeof e>"u")};dO.isExist=function(t){return typeof t<"u"};dO.isEmptyObject=function(t){return Object.keys(t).length===0};dO.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]]}};dO.getValue=function(t){return dO.isExist(t)?t:""};dO.isName=_hr;dO.getAllMatches=bhr;dO.nameRegexp=jut});var awe=v(kut=>{"use strict";var iwe=ZZ(),vhr={allowBooleanAttributes:!1,unpairedTags:[]};kut.validate=function(t,e){e=Object.assign({},vhr,e);let r=[],n=!1,o=!1;t[0]==="\uFEFF"&&(t=t.substr(1));for(let i=0;i<t.length;i++)if(t[i]==="<"&&t[i+1]==="?"){if(i+=2,i=Dut(t,i),i.err)return i}else if(t[i]==="<"){let a=i;if(i++,t[i]==="!"){i=Lut(t,i);continue}else{let s=!1;t[i]==="/"&&(s=!0,i++);let u="";for(;i<t.length&&t[i]!==">"&&t[i]!==" "&&t[i]!==" "&&t[i]!==`
`&&t[i]!=="\r";i++)u+=t[i];if(u=u.trim(),u[u.length-1]==="/"&&(u=u.substring(0,u.length-1),i--),!Thr(u)){let d;return u.trim().length===0?d="Invalid space after '<'.":d="Tag '"+u+"' is an invalid name.",Ms("InvalidTag",d,zf(t,i))}let l=xhr(t,i);if(l===!1)return Ms("InvalidAttr","Attributes for '"+u+"' have open quote.",zf(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=Fut(c,e);if(f===!0)n=!0;else return Ms(f.err.code,f.err.msg,zf(t,d+f.err.line))}else if(s)if(l.tagClosed){if(c.trim().length>0)return Ms("InvalidTag","Closing tag '"+u+"' can't have attributes or invalid starting.",zf(t,a));if(r.length===0)return Ms("InvalidTag","Closing tag '"+u+"' has not been opened.",zf(t,a));{let d=r.pop();if(u!==d.tagName){let f=zf(t,d.tagStartPos);return Ms("InvalidTag","Expected closing tag '"+d.tagName+"' (opened in line "+f.line+", col "+f.col+") instead of closing tag '"+u+"'.",zf(t,a))}r.length==0&&(o=!0)}}else return Ms("InvalidTag","Closing tag '"+u+"' doesn't have proper closing.",zf(t,i));else{let d=Fut(c,e);if(d!==!0)return Ms(d.err.code,d.err.msg,zf(t,i-c.length+d.err.line));if(o===!0)return Ms("InvalidXml","Multiple possible root nodes found.",zf(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=Lut(t,i);continue}else if(t[i+1]==="?"){if(i=Dut(t,++i),i.err)return i}else break;else if(t[i]==="&"){let d=Phr(t,i);if(d==-1)return Ms("InvalidChar","char '&' is not expected.",zf(t,i));i=d}else if(o===!0&&!Nut(t[i]))return Ms("InvalidXml","Extra text at the end",zf(t,i));t[i]==="<"&&i--}}else{if(Nut(t[i]))continue;return Ms("InvalidChar","char '"+t[i]+"' is not expected.",zf(t,i))}if(n){if(r.length==1)return Ms("InvalidTag","Unclosed tag '"+r[0].tagName+"'.",zf(t,r[0].tagStartPos));if(r.length>0)return Ms("InvalidXml","Invalid '"+JSON.stringify(r.map(i=>i.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return Ms("InvalidXml","Start tag expected.",1);return!0};function Nut(t){return t===" "||t===" "||t===`
`||t==="\r"}function Dut(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 Ms("InvalidXml","XML declaration allowed only at the start of the document.",zf(t,e));if(t[e]=="?"&&t[e+1]==">"){e++;break}else continue}return e}function Lut(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 whr='"',Shr="'";function xhr(t,e){let r="",n="",o=!1;for(;e<t.length;e++){if(t[e]===whr||t[e]===Shr)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 Chr=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function Fut(t,e){let r=iwe.getAllMatches(t,Chr),n={};for(let o=0;o<r.length;o++){if(r[o][1].length===0)return Ms("InvalidAttr","Attribute '"+r[o][2]+"' has no space in starting.",aH(r[o]));if(r[o][3]!==void 0&&r[o][4]===void 0)return Ms("InvalidAttr","Attribute '"+r[o][2]+"' is without value.",aH(r[o]));if(r[o][3]===void 0&&!e.allowBooleanAttributes)return Ms("InvalidAttr","boolean attribute '"+r[o][2]+"' is not allowed.",aH(r[o]));let i=r[o][2];if(!Ehr(i))return Ms("InvalidAttr","Attribute '"+i+"' is an invalid name.",aH(r[o]));if(!n.hasOwnProperty(i))n[i]=1;else return Ms("InvalidAttr","Attribute '"+i+"' is repeated.",aH(r[o]))}return!0}function Ohr(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 Phr(t,e){if(e++,t[e]===";")return-1;if(t[e]==="#")return e++,Ohr(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 Ms(t,e,r){return{err:{code:t,msg:e,line:r.line||r,col:r.col}}}function Ehr(t){return iwe.isName(t)}function Thr(t){return iwe.isName(t)}function zf(t,e){let r=t.substring(0,e).split(/\r?\n/);return{line:r.length,col:r[r.length-1].length+1}}function aH(t){return t.startIndex+t[1].length}});var But=v(swe=>{var $ut={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}},Ahr=function(t){return Object.assign({},$ut,t)};swe.buildOptions=Ahr;swe.defaultOptions=$ut});var Uut=v((Uao,qut)=>{"use strict";var uwe=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})}};qut.exports=uwe});var Hut=v((zao,zut)=>{var Ihr=ZZ();function Mhr(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&&Nhr(t,e))e+=7,[entityName,val,e]=Rhr(t,e+1),val.indexOf("&")===-1&&(r[khr(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(o&&Dhr(t,e))e+=8;else if(o&&Lhr(t,e))e+=8;else if(o&&Fhr(t,e))e+=9;else if(jhr)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===0)break}else t[e]==="["?o=!0:a+=t[e];if(n!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:r,i:e}}function Rhr(t,e){let r="";for(;e<t.length&&t[e]!=="'"&&t[e]!=='"';e++)r+=t[e];if(r=r.trim(),r.indexOf(" ")!==-1)throw new Error("External entites are not supported");let n=t[e++],o="";for(;e<t.length&&t[e]!==n;e++)o+=t[e];return[r,o,e]}function jhr(t,e){return t[e+1]==="!"&&t[e+2]==="-"&&t[e+3]==="-"}function Nhr(t,e){return t[e+1]==="!"&&t[e+2]==="E"&&t[e+3]==="N"&&t[e+4]==="T"&&t[e+5]==="I"&&t[e+6]==="T"&&t[e+7]==="Y"}function Dhr(t,e){return t[e+1]==="!"&&t[e+2]==="E"&&t[e+3]==="L"&&t[e+4]==="E"&&t[e+5]==="M"&&t[e+6]==="E"&&t[e+7]==="N"&&t[e+8]==="T"}function Lhr(t,e){return t[e+1]==="!"&&t[e+2]==="A"&&t[e+3]==="T"&&t[e+4]==="T"&&t[e+5]==="L"&&t[e+6]==="I"&&t[e+7]==="S"&&t[e+8]==="T"}function Fhr(t,e){return t[e+1]==="!"&&t[e+2]==="N"&&Line truncated
`);let e=new sH("!xml"),r=e,n="",o="";for(let i=0;i<t.length;i++)if(t[i]==="<")if(t[i+1]==="/"){let s=L1(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=cwe(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 sH(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=L1(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=Hhr(t,i);this.docTypeEntities=s.entities,i=s.i}else if(t.substr(i+1,2)==="!["){let s=L1(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=cwe(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 b=this.readStopNodeData(t,l,f+1);if(!b)throw new Error(`Unexpected end of ${l}`);i=b.i,m=b.tagContent}let h=new sH(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 sH(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 sH(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 Xhr(t,e,r){let n=this.options.updateTag(e.tagname,r,e[":@"]);n===!1||(typeof n=="string"&&(e.tagname=n),t.addChild(e))}var Qhr=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 egr(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 tgr(t,e,r){let n="*."+r;for(let o in t){let i=t[o];if(n===i||e===i)return!0}return!1}function rgr(t,e,r=">"){let n,o="";for(let i=e;i<t.length;i++){let a=t[i];if(n)a===n&&(n="");else if(a==='"'||a==="'")n=a;else if(a===r[0])if(r[1]){if(t[i+1]===r[1])return{data:o,index:i}}else return{data:o,index:i};else a===" "&&(a=" ");o+=a}}function L1(t,e,r,n){let o=t.indexOf(e,r);if(o===-1)throw new Error(n);return o+e.length-1}function cwe(t,e,r,n=">"){let o=rgr(t,e+1,n);if(!o)return;let i=o.data,a=o.index,s=i.search(/\s/),u=i,l=!0;s!==-1&&(u=i.substring(0,s),i=i.substring(s+1).trimStart());let c=u;if(r){let d=u.indexOf(":");d!==-1&&(u=u.substr(d+1),l=u!==o.data.substr(d+1))}return{tagName:u,tagExp:i,closeIndex:a,attrExpPresent:l,rawTagName:c}}function ngr(t,e,r){let n=r,o=1;for(;r<t.length;r++)if(t[r]==="<")if(t[r+1]==="/"){let i=L1(t,">",r,`${e} is not closed`);if(t.substring(r+2,i).trim()===e&&(o--,o===0))return{tagCoLine truncated
`;function pgr(t,e){let r="";return e.format&&e.indentBy.length>0&&(r=fgr),rlt(t,e,"",r)}function rlt(t,e,r,n){let o="",i=!1;for(let a=0;a<t.length;a++){let s=t[a],u=mgr(s);if(u===void 0)continue;let l="";if(r.length===0?l=u:l=`${r}.${u}`,u===e.textNodeName){let m=s[u];hgr(l,e)||(m=e.tagValueProcessor(u,m),m=nlt(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=tlt(s[":@"],e),h=u==="?xml"?"":n,b=s[u][0][e.textNodeName];b=b.length!==0?" "+b:"",o+=h+`<${u}${b}${m}?>`,i=!0;continue}let c=n;c!==""&&(c+=e.indentBy);let d=tlt(s[":@"],e),f=n+`<${u}${d}`,p=rlt(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 mgr(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 tlt(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=nlt(o,e),o===!0&&e.suppressBooleanAttributes?r+=` ${n.substr(e.attributeNamePrefix.length)}`:r+=` ${n.substr(e.attributeNamePrefix.length)}="${o}"`}return r}function hgr(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 nlt(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}olt.exports=pgr});var slt=v((Jao,alt)=>{"use strict";var ggr=ilt(),ygr={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 $T(t){this.options=Object.assign({},ygr,t),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=vgr),this.processTextOrObjNode=bgr,this.options.format?(this.indentate=_gr,this.tagEndChar=`>
${Dy(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 Yh(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(kT(i)),Dy(await a.digest())}getSigningKey(e,r,n,o){return hut(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")}},JZ=t=>{let e=xut(t).replace(/[\-:]/g,"");return{longDate:e,shortDate:e.slice(0,8)}},Out=t=>Object.keys(t).sort().join(";")});var Eut=w(()=>{Put();Qve();twe();rwe();iwe();awe();Xve()});var YZ,Tut=w(()=>{LT();Eut();YZ=t=>{let e;t.credentials&&(e=pst(t.credentials,fst,Fve)),e||(t.credentialDefaultProvider?e=Ck(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=Ck(t.signer):t.regionInfoProvider?i=()=>Ck(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||aH;return new d(c)}):i=async a=>{a=Object.assign({},{name:"sigv4",signingName:t.signingName||t.defaultSigningName,signingRegion:await Ck(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||aH;return new c(l)},{...t,systemClockOffset:n,signingEscapePath:r,credentials:e,signer:i}}});var Aut=w(()=>{Gst();Jst();Tut()});var Iut=w(()=>{Aut()});var Mut=w(()=>{});var Rut=w(()=>{ar()});var ZZ,swe=w(()=>{ar();ZZ=(t,e)=>DT(t,e).then(r=>e.utf8Encoder(r))});var Is,jut,Nut,Dut=w(()=>{swe();Is=(t,e)=>ZZ(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{}}),jut=async(t,e)=>{let r=await Is(t,e);return r.message=r.message??r.Message,r},Nut=(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 XZ=v(fO=>{"use strict";var Lut=":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",whr=Lut+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",Fut="["+Lut+"]["+whr+"]*",Shr=new RegExp("^"+Fut+"$"),xhr=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},Chr=function(t){let e=Shr.exec(t);return!(e===null||typeof e>"u")};fO.isExist=function(t){return typeof t<"u"};fO.isEmptyObject=function(t){return Object.keys(t).length===0};fO.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]]}};fO.getValue=function(t){return fO.isExist(t)?t:""};fO.isName=Chr;fO.getAllMatches=xhr;fO.nameRegexp=Fut});var lwe=v(Uut=>{"use strict";var uwe=XZ(),Ohr={allowBooleanAttributes:!1,unpairedTags:[]};Uut.validate=function(t,e){e=Object.assign({},Ohr,e);let r=[],n=!1,o=!1;t[0]==="\uFEFF"&&(t=t.substr(1));for(let i=0;i<t.length;i++)if(t[i]==="<"&&t[i+1]==="?"){if(i+=2,i=$ut(t,i),i.err)return i}else if(t[i]==="<"){let a=i;if(i++,t[i]==="!"){i=But(t,i);continue}else{let s=!1;t[i]==="/"&&(s=!0,i++);let u="";for(;i<t.length&&t[i]!==">"&&t[i]!==" "&&t[i]!==" "&&t[i]!==`
`&&t[i]!=="\r";i++)u+=t[i];if(u=u.trim(),u[u.length-1]==="/"&&(u=u.substring(0,u.length-1),i--),!jhr(u)){let d;return u.trim().length===0?d="Invalid space after '<'.":d="Tag '"+u+"' is an invalid name.",Ms("InvalidTag",d,zf(t,i))}let l=Thr(t,i);if(l===!1)return Ms("InvalidAttr","Attributes for '"+u+"' have open quote.",zf(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=qut(c,e);if(f===!0)n=!0;else return Ms(f.err.code,f.err.msg,zf(t,d+f.err.line))}else if(s)if(l.tagClosed){if(c.trim().length>0)return Ms("InvalidTag","Closing tag '"+u+"' can't have attributes or invalid starting.",zf(t,a));if(r.length===0)return Ms("InvalidTag","Closing tag '"+u+"' has not been opened.",zf(t,a));{let d=r.pop();if(u!==d.tagName){let f=zf(t,d.tagStartPos);return Ms("InvalidTag","Expected closing tag '"+d.tagName+"' (opened in line "+f.line+", col "+f.col+") instead of closing tag '"+u+"'.",zf(t,a))}r.length==0&&(o=!0)}}else return Ms("InvalidTag","Closing tag '"+u+"' doesn't have proper closing.",zf(t,i));else{let d=qut(c,e);if(d!==!0)return Ms(d.err.code,d.err.msg,zf(t,i-c.length+d.err.line));if(o===!0)return Ms("InvalidXml","Multiple possible root nodes found.",zf(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=But(t,i);continue}else if(t[i+1]==="?"){if(i=$ut(t,++i),i.err)return i}else break;else if(t[i]==="&"){let d=Mhr(t,i);if(d==-1)return Ms("InvalidChar","char '&' is not expected.",zf(t,i));i=d}else if(o===!0&&!kut(t[i]))return Ms("InvalidXml","Extra text at the end",zf(t,i));t[i]==="<"&&i--}}else{if(kut(t[i]))continue;return Ms("InvalidChar","char '"+t[i]+"' is not expected.",zf(t,i))}if(n){if(r.length==1)return Ms("InvalidTag","Unclosed tag '"+r[0].tagName+"'.",zf(t,r[0].tagStartPos));if(r.length>0)return Ms("InvalidXml","Invalid '"+JSON.stringify(r.map(i=>i.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return Ms("InvalidXml","Start tag expected.",1);return!0};function kut(t){return t===" "||t===" "||t===`
`||t==="\r"}function $ut(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 Ms("InvalidXml","XML declaration allowed only at the start of the document.",zf(t,e));if(t[e]=="?"&&t[e+1]==">"){e++;break}else continue}return e}function But(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 Phr='"',Ehr="'";function Thr(t,e){let r="",n="",o=!1;for(;e<t.length;e++){if(t[e]===Phr||t[e]===Ehr)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 Ahr=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function qut(t,e){let r=uwe.getAllMatches(t,Ahr),n={};for(let o=0;o<r.length;o++){if(r[o][1].length===0)return Ms("InvalidAttr","Attribute '"+r[o][2]+"' has no space in starting.",sH(r[o]));if(r[o][3]!==void 0&&r[o][4]===void 0)return Ms("InvalidAttr","Attribute '"+r[o][2]+"' is without value.",sH(r[o]));if(r[o][3]===void 0&&!e.allowBooleanAttributes)return Ms("InvalidAttr","boolean attribute '"+r[o][2]+"' is not allowed.",sH(r[o]));let i=r[o][2];if(!Rhr(i))return Ms("InvalidAttr","Attribute '"+i+"' is an invalid name.",sH(r[o]));if(!n.hasOwnProperty(i))n[i]=1;else return Ms("InvalidAttr","Attribute '"+i+"' is repeated.",sH(r[o]))}return!0}function Ihr(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 Mhr(t,e){if(e++,t[e]===";")return-1;if(t[e]==="#")return e++,Ihr(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 Ms(t,e,r){return{err:{code:t,msg:e,line:r.line||r,col:r.col}}}function Rhr(t){return uwe.isName(t)}function jhr(t){return uwe.isName(t)}function zf(t,e){let r=t.substring(0,e).split(/\r?\n/);return{line:r.length,col:r[r.length-1].length+1}}function sH(t){return t.startIndex+t[1].length}});var Hut=v(cwe=>{var zut={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}},Nhr=function(t){return Object.assign({},zut,t)};cwe.buildOptions=Nhr;cwe.defaultOptions=zut});var Wut=v((Kao,Vut)=>{"use strict";var dwe=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})}};Vut.exports=dwe});var Gut=v((Gao,Kut)=>{var Dhr=XZ();function Lhr(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&&$hr(t,e))e+=7,[entityName,val,e]=Fhr(t,e+1),val.indexOf("&")===-1&&(r[zhr(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(o&&Bhr(t,e))e+=8;else if(o&&qhr(t,e))e+=8;else if(o&&Uhr(t,e))e+=9;else if(khr)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===0)break}else t[e]==="["?o=!0:a+=t[e];if(n!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:r,i:e}}function Fhr(t,e){let r="";for(;e<t.length&&t[e]!=="'"&&t[e]!=='"';e++)r+=t[e];if(r=r.trim(),r.indexOf(" ")!==-1)throw new Error("External entites are not supported");let n=t[e++],o="";for(;e<t.length&&t[e]!==n;e++)o+=t[e];return[r,o,e]}function khr(t,e){return t[e+1]==="!"&&t[e+2]==="-"&&t[e+3]==="-"}function $hr(t,e){return t[e+1]==="!"&&t[e+2]==="E"&&t[e+3]==="N"&&t[e+4]==="T"&&t[e+5]==="I"&&t[e+6]==="T"&&t[e+7]==="Y"}function Bhr(t,e){return t[e+1]==="!"&&t[e+2]==="E"&&t[e+3]==="L"&&t[e+4]==="E"&&t[e+5]==="M"&&t[e+6]==="E"&&t[e+7]==="N"&&t[e+8]==="T"}function qhr(t,e){return t[e+1]==="!"&&t[e+2]==="A"&&t[e+3]==="T"&&t[e+4]==="T"&&t[e+5]==="L"&&t[e+6]==="I"&&t[e+7]==="S"&&t[e+8]==="T"}function Uhr(t,e){return t[e+1]==="!"&&t[e+2]==="N"&&Line truncated
`);let e=new uH("!xml"),r=e,n="",o="";for(let i=0;i<t.length;i++)if(t[i]==="<")if(t[i+1]==="/"){let s=F1(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=pwe(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 uH(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=F1(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=Jhr(t,i);this.docTypeEntities=s.entities,i=s.i}else if(t.substr(i+1,2)==="!["){let s=F1(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=pwe(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 b=this.readStopNodeData(t,l,f+1);if(!b)throw new Error(`Unexpected end of ${l}`);i=b.i,m=b.tagContent}let h=new uH(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 uH(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 uH(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 ngr(t,e,r){let n=this.options.updateTag(e.tagname,r,e[":@"]);n===!1||(typeof n=="string"&&(e.tagname=n),t.addChild(e))}var ogr=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 igr(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 agr(t,e,r){let n="*."+r;for(let o in t){let i=t[o];if(n===i||e===i)return!0}return!1}function sgr(t,e,r=">"){let n,o="";for(let i=e;i<t.length;i++){let a=t[i];if(n)a===n&&(n="");else if(a==='"'||a==="'")n=a;else if(a===r[0])if(r[1]){if(t[i+1]===r[1])return{data:o,index:i}}else return{data:o,index:i};else a===" "&&(a=" ");o+=a}}function F1(t,e,r,n){let o=t.indexOf(e,r);if(o===-1)throw new Error(n);return o+e.length-1}function pwe(t,e,r,n=">"){let o=sgr(t,e+1,n);if(!o)return;let i=o.data,a=o.index,s=i.search(/\s/),u=i,l=!0;s!==-1&&(u=i.substring(0,s),i=i.substring(s+1).trimStart());let c=u;if(r){let d=u.indexOf(":");d!==-1&&(u=u.substr(d+1),l=u!==o.data.substr(d+1))}return{tagName:u,tagExp:i,closeIndex:a,attrExpPresent:l,rawTagName:c}}function ugr(t,e,r){let n=r,o=1;for(;r<t.length;r++)if(t[r]==="<")if(t[r+1]==="/"){let i=F1(t,">",r,`${e} is not closed`);if(t.substring(r+2,i).trim()===e&&(o--,o===0))return{tagCoLine truncated
`;function bgr(t,e){let r="";return e.format&&e.indentBy.length>0&&(r=ygr),alt(t,e,"",r)}function alt(t,e,r,n){let o="",i=!1;for(let a=0;a<t.length;a++){let s=t[a],u=_gr(s);if(u===void 0)continue;let l="";if(r.length===0?l=u:l=`${r}.${u}`,u===e.textNodeName){let m=s[u];vgr(l,e)||(m=e.tagValueProcessor(u,m),m=slt(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=ilt(s[":@"],e),h=u==="?xml"?"":n,b=s[u][0][e.textNodeName];b=b.length!==0?" "+b:"",o+=h+`<${u}${b}${m}?>`,i=!0;continue}let c=n;c!==""&&(c+=e.indentBy);let d=ilt(s[":@"],e),f=n+`<${u}${d}`,p=alt(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 _gr(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 ilt(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=slt(o,e),o===!0&&e.suppressBooleanAttributes?r+=` ${n.substr(e.attributeNamePrefix.length)}`:r+=` ${n.substr(e.attributeNamePrefix.length)}="${o}"`}return r}function vgr(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 slt(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}ult.exports=bgr});var dlt=v((eso,clt)=>{"use strict";var wgr=llt(),Sgr={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 $T(t){this.options=Object.assign({},Sgr,t),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=Ogr),this.processTextOrObjNode=xgr,this.options.format?(this.indentate=Cgr,this.tagEndChar=`>
`,this.newLine=`
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}$T.prototype.build=function(t){return this.options.preserveOrder?ggr(t,this.options):(Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t}),this.j2x(t,0).val)};$T.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}};$T.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 bgr(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)}$T.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}};$T.prototype.closeTag=function(t){let e="";return this.options.unpairedTags.indexOf(t)!==-1?this.options.suppressUnpairedNode||(e="/"):this.options.suppressEmptyNode?e="/":e=`></${t}`,e};$T.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}};$T.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 _gr(t){return this.options.indentBy.repeat(t)}function vgr(t){return t.startsWith(this.options.attributeNamePrefix)&&t!==this.options.textNodeName?t.substr(this.attrPrefixLen):!1}alt.exports=$T});var llt=v((Yao,ult)=>{"use strict";var wgr=awe(),Sgr=elt(),xgr=slt();ult.exports={XMLParser:Sgr,XMLValidator:wgr,XMLBuilder:xgr}});var clt,R_,dlt,flt=w(()=>{ar();clt=F(llt());owe();R_=(t,e)=>YZ(t,e).then(r=>{if(r.length){let n=new clt.XMLParser({attributeNamePrefix:"",htmlEntities:!0,ignoreAttributes:!1,ignoreDeclaration:!0,parseTagValue:!1,trimValues:!1,tagValueProcessor:(u,l)=>l.trim()===""&&l.includes(`
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}$T.prototype.build=function(t){return this.options.preserveOrder?wgr(t,this.options):(Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t}),this.j2x(t,0).val)};$T.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}};$T.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 xgr(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)}$T.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}};$T.prototype.closeTag=function(t){let e="";return this.options.unpairedTags.indexOf(t)!==-1?this.options.suppressUnpairedNode||(e="/"):this.options.suppressEmptyNode?e="/":e=`></${t}`,e};$T.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}};$T.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 Cgr(t){return this.options.indentBy.repeat(t)}function Ogr(t){return t.startsWith(this.options.attributeNamePrefix)&&t!==this.options.textNodeName?t.substr(this.attrPrefixLen):!1}clt.exports=$T});var plt=v((tso,flt)=>{"use strict";var Pgr=lwe(),Egr=olt(),Tgr=dlt();flt.exports={XMLParser:Egr,XMLValidator:Pgr,XMLBuilder:Tgr}});var mlt,R_,hlt,glt=w(()=>{ar();mlt=F(plt());swe();R_=(t,e)=>ZZ(t,e).then(r=>{if(r.length){let n=new mlt.XMLParser({attributeNamePrefix:"",htmlEntities:!0,ignoreAttributes:!1,ignoreDeclaration:!0,parseTagValue:!1,trimValues:!1,tagValueProcessor:(u,l)=>l.trim()===""&&l.includes(`
`)?"":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]),Mve(s)}return{}}),dlt=async(t,e)=>{let r=await R_(t,e);return r.Error&&(r.Error.message=r.Error.message??r.Error.Message),r}});var plt=w(()=>{Eut();Tut();Mut();flt()});var F1=w(()=>{Tst();Put();plt()});function Cgr(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"cognito-identity",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function XZ(t){return{schemeId:"smithy.api#noAuth"}}var mlt,hlt,glt,pwe=w(()=>{F1();jy();mlt=async(t,e,r)=>({operation:A_(e).operation,region:await zd(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});hlt=t=>{let e=[];switch(t.operation){case"GetCredentialsForIdentity":{e.push(XZ(t));break}case"GetId":{e.push(XZ(t));break}case"GetOpenIdToken":{e.push(XZ(t));break}case"UnlinkIdentity":{e.push(XZ(t));break}default:e.push(Cgr(t))}return e},glt=t=>({...JZ(t)})});var ylt,Cr,ua=w(()=>{ylt=t=>({...t,useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"cognito-identity"}),Cr={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}});var _lt,blt=w(()=>{_lt={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","downlevel-dts":"0.10.1",rimraf:"3.0.2",typescript:"~4.9.5"},engines:{node:">=16.0.0"},typesVersions:{"<4.0":{"dist-types/*":["dist-types/ts3.4/*"]}},files:["dist-*/**"],author:{name:"AWS SDK for JavaScript Team",url:"https://aws.amazon.com/javascript/"},license:"Apache-2.0",browser:{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.browser"},"react-native":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.native"},homepage:"https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-cognito-identity",repository:{type:"git",url:"https://github.com/aws/aws-sdk-js-v3.git",directory:"clients/client-cognito-identity"}}});var mwe,hwe,vlt,wlt=w(()=>{mwe={name:"SHA-256"},hwe={name:"HMAC",hash:mwe},vlt=new Uint8Array([227,176,196,66,152,252,28,20,154,251,244,200,153,111,185,36,39,174,65,228,100,155,147,76,164,149,153,27,120,82,184,85])});function Ck(){return typeof window<"u"?window:typeof self<"u"?self:Pg Line truncated
`);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]),Nve(s)}return{}}),hlt=async(t,e)=>{let r=await R_(t,e);return r.Error&&(r.Error.message=r.Error.message??r.Error.Message),r}});var ylt=w(()=>{Mut();Rut();Dut();glt()});var k1=w(()=>{Rst();Iut();ylt()});function Agr(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"cognito-identity",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function QZ(t){return{schemeId:"smithy.api#noAuth"}}var blt,_lt,vlt,gwe=w(()=>{k1();jy();blt=async(t,e,r)=>({operation:A_(e).operation,region:await zd(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});_lt=t=>{let e=[];switch(t.operation){case"GetCredentialsForIdentity":{e.push(QZ(t));break}case"GetId":{e.push(QZ(t));break}case"GetOpenIdToken":{e.push(QZ(t));break}case"UnlinkIdentity":{e.push(QZ(t));break}default:e.push(Agr(t))}return e},vlt=t=>({...YZ(t)})});var wlt,Cr,ua=w(()=>{wlt=t=>({...t,useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"cognito-identity"}),Cr={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}});var xlt,Slt=w(()=>{xlt={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","downlevel-dts":"0.10.1",rimraf:"3.0.2",typescript:"~4.9.5"},engines:{node:">=16.0.0"},typesVersions:{"<4.0":{"dist-types/*":["dist-types/ts3.4/*"]}},files:["dist-*/**"],author:{name:"AWS SDK for JavaScript Team",url:"https://aws.amazon.com/javascript/"},license:"Apache-2.0",browser:{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.browser"},"react-native":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.native"},homepage:"https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-cognito-identity",repository:{type:"git",url:"https://github.com/aws/aws-sdk-js-v3.git",directory:"clients/client-cognito-identity"}}});var ywe,bwe,Clt,Olt=w(()=>{ywe={name:"SHA-256"},bwe={name:"HMAC",hash:ywe},Clt=new Uint8Array([227,176,196,66,152,252,28,20,154,251,244,200,153,111,185,36,39,174,65,228,100,155,147,76,164,149,153,27,120,82,184,85])});function Ok(){return typeof window<"u"?window:typeof self<"u"?self:Mg Line truncated
- 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 kdt=w(()=>{});var $dt=w(()=>{kdt()});var Bdt=w(()=>{Hs()});var qdt=w(()=>{});var Udt=w(()=>{});function uyr(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return{...e,[r]:Array.isArray(n)?[...n]:n}},{})}var HX,zdt=w(()=>{HX=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=uyr(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 Hdt=w(()=>{});var Vdt=w(()=>{});var Wdt=w(()=>{});var Kdt=w(()=>{$dt();Bdt();qdt();Udt();zdt();Hdt();Vdt();Wdt()});function Gdt(t){return new HX({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 Jdt(t,e){let n=await fat(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 Tl("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:Aat(o.Expiration)}}if(t.statusCode>=400&&t.statusCode<500){let o={};try{o=JSON.parse(n)}catch{}throw Object.assign(new Tl(`Server responded with status: ${t.statusCode}`,{logger:e}),{Code:o.Code,Message:o.Message})}throw new Tl(`Server responded with status: ${t.statusCode}`,{logger:e})}var Ydt=w(()=>{aO();Kdt();ar();xve()});var Zdt,Xdt=w(()=>{Zdt=(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 u0e,Qdt=w(()=>{G3();aO();Fdt();Ydt();Xdt();u0e=(t={})=>{t.logger?.debug("@aws-sdk/credential-provider-http - fromHttp");let e,r=t.credentialsFullUri;if(r)e=r;else throw new Tl("No HTTP credential provider host provided.",{logger:t.logger});let n=new URL(e);Ldt(n,t.logger);let o=new NT;return Zdt(async()=>{let i=Gdt(n);t.authorizationToken&&(i.headers.Authorization=t.authorizationToken);let a=await o.handle(i);return Jdt(a.response)},t.maxRetries??3,t.timeout??1e3)}});var eft=w(()=>{Qdt()});function lyr(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sts",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function tft(t){return{schemeId:"smithy.api#noAuth"}}var rft,nft,cyr,oft,l0e=w(()=>{F1();jy();dH();rft=async(t,e,r)=>({operation:A_(e).operation,region:await zd(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});nft=t=>{let e=[];switch(t.operation){case"AssumeRoleWithSAML":{e.push(tft(t));break}case"AssumeRoleWithWebIdentity":{e.push(tft(t));break}default:e.push(lyr(t))}return e},cyr=t=>({...t,stsClientCtor:Zh}),oft=t=>{let e=cyr(t);return{...JZ(e)}}});var ift,Vd,L_=w(()=>{ift=t=>({...t,useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,useGlobalEndpoint:t.useGlobalEndpoint??!1,defaultSigningName:"sts"}),Vd={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 sft,aft=w(()=>{sft={name:"@aws-sdk/client-sts",description:"AWS SDK for JavaScript Sts 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-sts","build:es":"tsc -p tsconfig.es.json","build:include:deps":"lerna run --scope $npm_package_name --include-dependencies build","build:types":"rimraf ./dist-types tsconfig.types.tsbuildinfo && 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 sts",test:"yarn test:unit","test:unit":"jest"},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 Line truncated
`);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.headerMarshaller.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}=UQ(r),u=new this.sha256(await this.getSigningKey(i,a,s,o));return u.update((0,DH.toUint8Array)(e)),(0,BQ.toHex)(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=(0,iyt.prepareRequest)(e),{longDate:c,shortDate:d}=UQ(r),f=(0,qQ.createScope)(d,u,a??this.service);l.headers[Bc.AMZ_DATE_HEADER]=c,s.sessionToken&&(l.headers[Bc.TOKEN_HEADER]=s.sessionToken);let p=await(0,GSe.getPayloadHash)(l,this.sha256);!(0,Tvr.hasHeader)(Bc.SHA256_HEADER,l.headers)&&this.applyChecksum&&(l.headers[Bc.SHA256_HEADER]=p);let m=(0,oyt.getCanonicalHeaders)(l,o,n),h=await this.getSignature(c,f,this.getSigningKey(s,u,d,a),this.createCanonicalRequest(l,m,p));return l.headers[Bc.AUTH_HEADER]=`${Bc.ALGORITHM_IDENTIFIER} Credential=${s.accessKeyId}/${f}, SignedHeaders=${ayt(m)}, Signature=${h}`,l}createCanonicalRequest(e,r,n){let o=Object.keys(r).sort();return`${e.method}
- EKS container host 169.254.170.23 or [fd00:ec2::23]`,{logger:e})}}});var Udt=w(()=>{});var zdt=w(()=>{Udt()});var Hdt=w(()=>{Hs()});var Vdt=w(()=>{});var Wdt=w(()=>{});function pyr(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return{...e,[r]:Array.isArray(n)?[...n]:n}},{})}var VX,Kdt=w(()=>{VX=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=pyr(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 Gdt=w(()=>{});var Jdt=w(()=>{});var Ydt=w(()=>{});var Zdt=w(()=>{zdt();Hdt();Vdt();Wdt();Kdt();Gdt();Jdt();Ydt()});function Xdt(t){return new VX({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 Qdt(t,e){let n=await gat(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 Tl("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:jat(o.Expiration)}}if(t.statusCode>=400&&t.statusCode<500){let o={};try{o=JSON.parse(n)}catch{}throw Object.assign(new Tl(`Server responded with status: ${t.statusCode}`,{logger:e}),{Code:o.Code,Message:o.Message})}throw new Tl(`Server responded with status: ${t.statusCode}`,{logger:e})}var eft=w(()=>{sO();Zdt();ar();Pve()});var tft,rft=w(()=>{tft=(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 d0e,nft=w(()=>{J3();sO();qdt();eft();rft();d0e=(t={})=>{t.logger?.debug("@aws-sdk/credential-provider-http - fromHttp");let e,r=t.credentialsFullUri;if(r)e=r;else throw new Tl("No HTTP credential provider host provided.",{logger:t.logger});let n=new URL(e);Bdt(n,t.logger);let o=new NT;return tft(async()=>{let i=Xdt(n);t.authorizationToken&&(i.headers.Authorization=t.authorizationToken);let a=await o.handle(i);return Qdt(a.response)},t.maxRetries??3,t.timeout??1e3)}});var oft=w(()=>{nft()});function myr(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sts",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function ift(t){return{schemeId:"smithy.api#noAuth"}}var aft,sft,hyr,uft,f0e=w(()=>{k1();jy();fH();aft=async(t,e,r)=>({operation:A_(e).operation,region:await zd(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});sft=t=>{let e=[];switch(t.operation){case"AssumeRoleWithSAML":{e.push(ift(t));break}case"AssumeRoleWithWebIdentity":{e.push(ift(t));break}default:e.push(myr(t))}return e},hyr=t=>({...t,stsClientCtor:Zh}),uft=t=>{let e=hyr(t);return{...YZ(e)}}});var lft,Vd,L_=w(()=>{lft=t=>({...t,useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,useGlobalEndpoint:t.useGlobalEndpoint??!1,defaultSigningName:"sts"}),Vd={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 dft,cft=w(()=>{dft={name:"@aws-sdk/client-sts",description:"AWS SDK for JavaScript Sts 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-sts","build:es":"tsc -p tsconfig.es.json","build:include:deps":"lerna run --scope $npm_package_name --include-dependencies build","build:types":"rimraf ./dist-types tsconfig.types.tsbuildinfo && 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 sts",test:"yarn test:unit","test:unit":"jest"},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 Line truncated
`);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.headerMarshaller.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}=zQ(r),u=new this.sha256(await this.getSigningKey(i,a,s,o));return u.update((0,LH.toUint8Array)(e)),(0,qQ.toHex)(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=(0,lyt.prepareRequest)(e),{longDate:c,shortDate:d}=zQ(r),f=(0,UQ.createScope)(d,u,a??this.service);l.headers[Bc.AMZ_DATE_HEADER]=c,s.sessionToken&&(l.headers[Bc.TOKEN_HEADER]=s.sessionToken);let p=await(0,ZSe.getPayloadHash)(l,this.sha256);!(0,jvr.hasHeader)(Bc.SHA256_HEADER,l.headers)&&this.applyChecksum&&(l.headers[Bc.SHA256_HEADER]=p);let m=(0,uyt.getCanonicalHeaders)(l,o,n),h=await this.getSignature(c,f,this.getSigningKey(s,u,d,a),this.createCanonicalRequest(l,m,p));return l.headers[Bc.AUTH_HEADER]=`${Bc.ALGORITHM_IDENTIFIER} Credential=${s.accessKeyId}/${f}, SignedHeaders=${cyt(m)}, Signature=${h}`,l}createCanonicalRequest(e,r,n){let o=Object.keys(r).sort();return`${e.method}
${this.getCanonicalPath(e)}
${(0,Evr.getCanonicalQuery)(e)}
${(0,Rvr.getCanonicalQuery)(e)}
${o.map(i=>`${i}:${r[i]}`).join(`
`)}
${o.join(";")}
${n}`}async createStringToSign(e,r,n){let o=new this.sha256;o.update((0,DH.toUint8Array)(n));let i=await o.digest();return`${Bc.ALGORITHM_IDENTIFIER}
${n}`}async createStringToSign(e,r,n){let o=new this.sha256;o.update((0,LH.toUint8Array)(n));let i=await o.digest();return`${Bc.ALGORITHM_IDENTIFIER}
${e}
${r}
${(0,BQ.toHex)(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 encodeURIComponent(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((0,DH.toUint8Array)(i)),(0,BQ.toHex)(await a.digest())}getSigningKey(e,r,n,o){return(0,qQ.getSigningKey)(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")}};zQ.SignatureV4=JSe;var UQ=t=>{let e=(0,Ivr.iso8601)(t).replace(/[\-:]/g,"");return{longDate:e,shortDate:e.slice(0,8)}},ayt=t=>Object.keys(t).sort().join(";")});var lyt=v(jp=>{"use strict";Object.defineProperty(jp,"__esModule",{value:!0});jp.prepareRequest=jp.moveHeadersToQuery=jp.getPayloadHash=jp.getCanonicalQuery=jp.getCanonicalHeaders=void 0;var uyt=(H1(),zl(z1));uyt.__exportStar(syt(),jp);var Mvr=qSe();Object.defineProperty(jp,"getCanonicalHeaders",{enumerable:!0,get:function(){return Mvr.getCanonicalHeaders}});var Rvr=zSe();Object.defineProperty(jp,"getCanonicalQuery",{enumerable:!0,get:function(){return Rvr.getCanonicalQuery}});var jvr=HSe();Object.defineProperty(jp,"getPayloadHash",{enumerable:!0,get:function(){return jvr.getPayloadHash}});var Nvr=WSe();Object.defineProperty(jp,"moveHeadersToQuery",{enumerable:!0,get:function(){return Nvr.moveHeadersToQuery}});var Dvr=KSe();Object.defineProperty(jp,"prepareRequest",{enumerable:!0,get:function(){return Dvr.prepareRequest}});uyt.__exportStar($Se(),jp)});var cyt=v(YSe=>{"use strict";Object.defineProperty(YSe,"__esModule",{value:!0});var Lvr=(H1(),zl(z1));Lvr.__exportStar(lyt(),YSe)});var Va=v((W_o,dyt)=>{"use strict";dyt.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)},StringPrototypeToLowerCase(t){return t.toLowerCase()},StringPrototypeToUpperCase(t){return t.toUpperCase()},StringPrototypeTrim(t){return t.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(t,e,r){return t.set(e,r)},Boolean,Uint8Array}});var Yk=v((K_o,HQ)=>{"use strict";var{AbortController:fyt,AbortSignal:Fvr}=typeof self<"u"?self:typeof window<"u"?window:void 0;HQ.exports=fyt;HQ.exports.AbortSignal=Fvr;HQ.exports.default=fyt});var LH=v((G_o,ZSe)=>{"use strict";var Zk=typeof Reflect=="object"?Reflect:null,pyt=Zk&&typeof Zk.apply=="function"?Zk.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},VQ;Zk&&typeof Zk.ownKeys=="function"?VQ=Zk.ownKeys:Object.getOwnPropertySymbols?VQ=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:VQ=function(e){return Object.getOwnPropertyNames(e)};function kvr(t){console&&console.warn&&console.warn(t)}var hyt=Number.isNaN||function(e){return e!==e};function Ei(){Ei.init.call(this)}ZSe.exports=Ei;ZSe.exports.once=Uvr;Ei.EventEmitter=Ei;Ei.prototype._events=void 0;Ei.prototype._eventsCount=0;Ei.prototype._maxListeners=void 0;var myt=10;function WQ(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(Ei,"defaultMaxListeners",{enumerable:!0,get:function(){return myt},set:function(t){if(typeof t!="number"||t<0||hyt(t))throw new RangeError('The value of "defaultM Line truncated
`;super(r),this.name="AggregateError",this.errors=e}};QSe.exports={AggregateError:XSe,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 Jvr},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:Yvr,deprecate(t,e){return t},addAbortListener:LH().addAbortListener||function(e,r){if(e===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);Cyt(e,"signal"),Zvr(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[Vvr]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[Wvr](){var o;(o=n)===null||o===void 0||o()}}},AbortSignalAny:Kvr.any||function(e){if(e.length===1)return e[0];let r=new Gvr,n=()=>r.abort();return e.forEach(o=>{Cyt(o,"signals"),o.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{e.forEach(o=>o.removeEventListener("abort",n))},{once:!0}),r.signal}};QSe.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var Kf=v((Y_o,Eyt)=>{"use strict";var{format:Xvr,inspect:KQ,AggregateError:Qvr}=Gd(),ewr=globalThis.AggregateError||Qvr,twr=Symbol("kIsNodeError"),rwr=["string","function","number","object","Function","Object","boolean","bigint","symbol"],nwr=/^([A-Z][a-z0-9]*)+$/,owr="__node_internal_",GQ={};function J1(t,e){if(!t)throw new GQ.ERR_INTERNAL_ASSERTION(e)}function Oyt(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 iwr(t,e,r){if(typeof e=="function")return J1(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 J1(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:Xvr(e,...r)}function qc(t,e,r){r||(r=Error);class n extends r{constructor(...i){super(iwr(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[twr]=!0,GQ[t]=n}function Pyt(t){let e=owr+t.name;return Object.defineProperty(t,"name",{value:e}),t}function awr(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new ewr([e,t],e.message);return r.code=e.code,r}return t||e}var exe=class extends Error{constructor(e="The operation was aborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new GQ.ERR_INVALID_ARG_TYPE("options","Object",r);super(e,r),this.code="ABORT_ERR",this.name="AbortError"}};qc("ERR_ASSERTION","%s",Error);qc("ERR_INVALID_ARG_TYPE",(t,e,r)=>{J1(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)J1(typeof u=="string","All expected entries have to be of type string"),rwr.includes(u)?o.push(u.toLowerCase()):nwr.test(u)?i.push(u):(J1(u!=="object",'The value "object" should be written as "Object"'),a.push(u));if(i.length>0){let u=o.indexOf("object");u!==-1&&(o.splice(o,u,1),i.push("Object"))}if(o.length>0){switch(o.length){case 1:n+=`of type ${o[0]}`;break;case 2:n+=`one of type ${o[0]} or ${o[1]}`;break;default:{let u=o.pop();n+=`one of type ${o.join(", ")}, or ${u}`}}(i.length>0||a.length>0)&&(n+=" or ")}if(i.length>0){switch(i.length){case 1:n+=`an instance of ${i[0]}`;break;case 2:n+=`an instance of ${i[0]} or ${i[1]}`;break;default:{let u=i.pop();n+=`an instance of ${i.join(", ")}, or ${u}`}}a.length>0&&(n+=" or ")}switch(a.length){case 0:break;case 1:a[0].toLowerCase()!==a[0]&&(n+="an "),n+=`${a[0]}`;break;case 2:n+=`one of ${a[0]} or ${a[1]}`;break;default:{let u=a.pop();n+=`one of ${a.join(", ")}, or ${u}`}}if(r==null)n+=`. Received ${r}`;else if(typeof r=="function"&&r.name)n+=`. Received function ${r.name}`;else if(typeof r=="object"){var s;if((s=r.constructor)!==null&&s!==void 0&&s.name)n+=`. Received a Line truncated
`)>=0)return!1;return!0}function NOr(t,e){var r;if(t.indent===" ")r=" ";else if(typeof t.indent=="number"&&t.indent>0)r=G_.call(Array(t.indent+1)," ");else return null;return{base:r,prev:G_.call(Array(e+1),r)}}function _Ce(t,e){if(t.length===0)return"";var r=`
${(0,qQ.toHex)(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 encodeURIComponent(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((0,LH.toUint8Array)(i)),(0,qQ.toHex)(await a.digest())}getSigningKey(e,r,n,o){return(0,UQ.getSigningKey)(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")}};HQ.SignatureV4=XSe;var zQ=t=>{let e=(0,Dvr.iso8601)(t).replace(/[\-:]/g,"");return{longDate:e,shortDate:e.slice(0,8)}},cyt=t=>Object.keys(t).sort().join(";")});var pyt=v(jp=>{"use strict";Object.defineProperty(jp,"__esModule",{value:!0});jp.prepareRequest=jp.moveHeadersToQuery=jp.getPayloadHash=jp.getCanonicalQuery=jp.getCanonicalHeaders=void 0;var fyt=(V1(),zl(H1));fyt.__exportStar(dyt(),jp);var Lvr=HSe();Object.defineProperty(jp,"getCanonicalHeaders",{enumerable:!0,get:function(){return Lvr.getCanonicalHeaders}});var Fvr=WSe();Object.defineProperty(jp,"getCanonicalQuery",{enumerable:!0,get:function(){return Fvr.getCanonicalQuery}});var kvr=KSe();Object.defineProperty(jp,"getPayloadHash",{enumerable:!0,get:function(){return kvr.getPayloadHash}});var $vr=JSe();Object.defineProperty(jp,"moveHeadersToQuery",{enumerable:!0,get:function(){return $vr.moveHeadersToQuery}});var Bvr=YSe();Object.defineProperty(jp,"prepareRequest",{enumerable:!0,get:function(){return Bvr.prepareRequest}});fyt.__exportStar(USe(),jp)});var myt=v(QSe=>{"use strict";Object.defineProperty(QSe,"__esModule",{value:!0});var qvr=(V1(),zl(H1));qvr.__exportStar(pyt(),QSe)});var Va=v((Z_o,hyt)=>{"use strict";hyt.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)},StringPrototypeToLowerCase(t){return t.toLowerCase()},StringPrototypeToUpperCase(t){return t.toUpperCase()},StringPrototypeTrim(t){return t.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(t,e,r){return t.set(e,r)},Boolean,Uint8Array}});var Zk=v((X_o,VQ)=>{"use strict";var{AbortController:gyt,AbortSignal:Uvr}=typeof self<"u"?self:typeof window<"u"?window:void 0;VQ.exports=gyt;VQ.exports.AbortSignal=Uvr;VQ.exports.default=gyt});var FH=v((Q_o,exe)=>{"use strict";var Xk=typeof Reflect=="object"?Reflect:null,yyt=Xk&&typeof Xk.apply=="function"?Xk.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},WQ;Xk&&typeof Xk.ownKeys=="function"?WQ=Xk.ownKeys:Object.getOwnPropertySymbols?WQ=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:WQ=function(e){return Object.getOwnPropertyNames(e)};function zvr(t){console&&console.warn&&console.warn(t)}var _yt=Number.isNaN||function(e){return e!==e};function Ei(){Ei.init.call(this)}exe.exports=Ei;exe.exports.once=Kvr;Ei.EventEmitter=Ei;Ei.prototype._events=void 0;Ei.prototype._eventsCount=0;Ei.prototype._maxListeners=void 0;var byt=10;function KQ(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(Ei,"defaultMaxListeners",{enumerable:!0,get:function(){return byt},set:function(t){if(typeof t!="number"||t<0||_yt(t))throw new RangeError('The value of "defaultM Line truncated
`;super(r),this.name="AggregateError",this.errors=e}};rxe.exports={AggregateError:txe,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 ewr},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:twr,deprecate(t,e){return t},addAbortListener:FH().addAbortListener||function(e,r){if(e===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);Tyt(e,"signal"),rwr(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[Yvr]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[Zvr](){var o;(o=n)===null||o===void 0||o()}}},AbortSignalAny:Xvr.any||function(e){if(e.length===1)return e[0];let r=new Qvr,n=()=>r.abort();return e.forEach(o=>{Tyt(o,"signals"),o.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{e.forEach(o=>o.removeEventListener("abort",n))},{once:!0}),r.signal}};rxe.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var Kf=v((tvo,Myt)=>{"use strict";var{format:nwr,inspect:GQ,AggregateError:owr}=Gd(),iwr=globalThis.AggregateError||owr,awr=Symbol("kIsNodeError"),swr=["string","function","number","object","Function","Object","boolean","bigint","symbol"],uwr=/^([A-Z][a-z0-9]*)+$/,lwr="__node_internal_",JQ={};function Y1(t,e){if(!t)throw new JQ.ERR_INTERNAL_ASSERTION(e)}function Ayt(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 cwr(t,e,r){if(typeof e=="function")return Y1(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 Y1(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:nwr(e,...r)}function qc(t,e,r){r||(r=Error);class n extends r{constructor(...i){super(cwr(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[awr]=!0,JQ[t]=n}function Iyt(t){let e=lwr+t.name;return Object.defineProperty(t,"name",{value:e}),t}function dwr(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new iwr([e,t],e.message);return r.code=e.code,r}return t||e}var nxe=class extends Error{constructor(e="The operation was aborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new JQ.ERR_INVALID_ARG_TYPE("options","Object",r);super(e,r),this.code="ABORT_ERR",this.name="AbortError"}};qc("ERR_ASSERTION","%s",Error);qc("ERR_INVALID_ARG_TYPE",(t,e,r)=>{Y1(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)Y1(typeof u=="string","All expected entries have to be of type string"),swr.includes(u)?o.push(u.toLowerCase()):uwr.test(u)?i.push(u):(Y1(u!=="object",'The value "object" should be written as "Object"'),a.push(u));if(i.length>0){let u=o.indexOf("object");u!==-1&&(o.splice(o,u,1),i.push("Object"))}if(o.length>0){switch(o.length){case 1:n+=`of type ${o[0]}`;break;case 2:n+=`one of type ${o[0]} or ${o[1]}`;break;default:{let u=o.pop();n+=`one of type ${o.join(", ")}, or ${u}`}}(i.length>0||a.length>0)&&(n+=" or ")}if(i.length>0){switch(i.length){case 1:n+=`an instance of ${i[0]}`;break;case 2:n+=`an instance of ${i[0]} or ${i[1]}`;break;default:{let u=i.pop();n+=`an instance of ${i.join(", ")}, or ${u}`}}a.length>0&&(n+=" or ")}switch(a.length){case 0:break;case 1:a[0].toLowerCase()!==a[0]&&(n+="an "),n+=`${a[0]}`;break;case 2:n+=`one of ${a[0]} or ${a[1]}`;break;default:{let u=a.pop();n+=`one of ${a.join(", ")}, or ${u}`}}if(r==null)n+=`. Received ${r}`;else if(typeof r=="function"&&r.name)n+=`. Received function ${r.name}`;else if(typeof r=="object"){var s;if((s=r.constructor)!==null&&s!==void 0&&s.name)n+=`. Received a Line truncated
`)>=0)return!1;return!0}function $Or(t,e){var r;if(t.indent===" ")r=" ";else if(typeof t.indent=="number"&&t.indent>0)r=G_.call(Array(t.indent+1)," ");else return null;return{base:r,prev:G_.call(Array(e+1),r)}}function SCe(t,e){if(t.length===0)return"";var r=`
`+e.prev+e.base;return r+G_.call(t,","+r)+`
`+e.prev}function Cee(t,e){var r=bCe(t),n=[];if(r){n.length=t.length;for(var o=0;o<t.length;o++)n[o]=OO(t,o)?e(t[o],t):""}var i=typeof pCe=="function"?pCe(t):[],a;if(d$){a={};for(var s=0;s<i.length;s++)a["$"+i[s]]=i[s]}for(var u in t)OO(t,u)&&(r&&String(Number(u))===u&&u<t.length||d$&&a["$"+u]instanceof Symbol||(jvt.call(/[^\w$]/,u)?n.push(e(u,t)+": "+e(t[u],t)):n.push(u+": "+e(t[u],t))));if(typeof pCe=="function")for(var l=0;l<i.length;l++)Nvt.call(t,i[l])&&n.push("["+e(i[l])+"]: "+e(t[i[l]],t));return n}});var Uvt=v((Ovo,qvt)=>{"use strict";var DOr=QH(),LOr=sj(),Eee=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},FOr=function(t,e){if(t){var r=Eee(t,e);return r&&r.value}},kOr=function(t,e,r){var n=Eee(t,e);n?n.value=r:t.next={key:e,next:t.next,value:r}},$Or=function(t,e){return t?!!Eee(t,e):!1},BOr=function(t,e){if(t)return Eee(t,e,!0)};qvt.exports=function(){var e,r={assert:function(n){if(!r.has(n))throw new LOr("Side channel does not contain "+DOr(n))},delete:function(n){var o=e&&e.next,i=BOr(e,n);return i&&o&&o===i&&(e=void 0),!!i},get:function(n){return FOr(e,n)},has:function(n){return $Or(e,n)},set:function(n,o){e||(e={next:void 0}),kOr(e,n,o)}};return r}});var xCe=v((Pvo,zvt)=>{"use strict";zvt.exports=Object});var Vvt=v((Evo,Hvt)=>{"use strict";Hvt.exports=Error});var Kvt=v((Tvo,Wvt)=>{"use strict";Wvt.exports=EvalError});var Jvt=v((Avo,Gvt)=>{"use strict";Gvt.exports=RangeError});var Zvt=v((Ivo,Yvt)=>{"use strict";Yvt.exports=ReferenceError});var Qvt=v((Mvo,Xvt)=>{"use strict";Xvt.exports=SyntaxError});var twt=v((Rvo,ewt)=>{"use strict";ewt.exports=URIError});var nwt=v((jvo,rwt)=>{"use strict";rwt.exports=Math.abs});var iwt=v((Nvo,owt)=>{"use strict";owt.exports=Math.floor});var swt=v((Dvo,awt)=>{"use strict";awt.exports=Math.max});var lwt=v((Lvo,uwt)=>{"use strict";uwt.exports=Math.min});var dwt=v((Fvo,cwt)=>{"use strict";cwt.exports=Math.pow});var pwt=v((kvo,fwt)=>{"use strict";fwt.exports=Math.round});var hwt=v(($vo,mwt)=>{"use strict";mwt.exports=Number.isNaN||function(e){return e!==e}});var ywt=v((Bvo,gwt)=>{"use strict";var qOr=hwt();gwt.exports=function(e){return qOr(e)||e===0?e:e<0?-1:1}});var _wt=v((qvo,bwt)=>{"use strict";bwt.exports=Object.getOwnPropertyDescriptor});var CCe=v((Uvo,vwt)=>{"use strict";var Tee=_wt();if(Tee)try{Tee([],"length")}catch{Tee=null}vwt.exports=Tee});var Swt=v((zvo,wwt)=>{"use strict";var Aee=Object.defineProperty||!1;if(Aee)try{Aee({},"a",{value:1})}catch{Aee=!1}wwt.exports=Aee});var Cwt=v((Hvo,xwt)=>{"use strict";xwt.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 Ewt=v((Vvo,Pwt)=>{"use strict";var Owt=typeof Symbol<"u"&&Symbol,UOr=Cwt();Pwt.exports=function(){return typeof Owt!="function"||typeof Symbol!="function"||typeof Owt("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:UOr()}});var OCe=v((Wvo,Twt)=>{"use strict";Twt.exports=typeof Reflect<"u"&&Reflect.getPrototypeOf||null});var PCe=v((Kvo,Awt)=>{"use strict";var zOr=xCe();Awt.exports=zOr.getPrototypeOf||null});var Rwt=v((Gvo,Mwt)=>{"use strict";var HOr="Function.prototype.bind called on incompatible ",VOr=Object.prototype.toString,WOr=Math.max,KOr="[object Function]",Iwt=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},GOr=function(e,r){for(var n=[],o=r||0,i=0;o<e.length;o+=1,i+=1)n[i]=e[o];return n},JOr=function(t,e){for(var r="",n=0;n<t.length;n+=1)r+=t[n],n+1<t.length&&(r+=e);return r};Mwt.exports=function(e){var r=this;if(typeof r!="function"||VOr.apply(r)!==KOr)throw new TypeError(HOr+r);for(var n=GOr(arguments,1),o,i=function(){if(this instanceof o){var c=r.apply(this,Iwt(n,arguments));return Object(c)===c?c:this}return r.apply(e,Iwt(n,arguments))},a=WOr(0,r.length-n.length),s=[],u=0;u<a;u++)s[u]="$"+u;if(o=Function("binder","return function ("+JOr(s,",")+"){ return binder.apply(this,arguments); }")(i),r.prototype){var l=function(){};l.prototype=r.prototype,o.prototype=new l,l.prototype=null}return o}});var eV=v((Jvo,jwt)=>{"use strict";var YOr=Rwt();jwt.exports=Function.prototype.bind||YOr});var Iee=v((Yvo,Nwt)=>{"use strict";Nwt.exports=Function.prototype.call});var ECe=v((Zvo,Dwt)=>{"use strict";Dwt.exports=Function Line truncated
`,this.streamTerminator=n.streamTerminator):this.messageTerminator=n.messageTerminator,o?.addEventListener("abort",()=>this.controller.abort())}iterMessages(){return iSt(this,arguments,function*(){var r,n;this.controller.signal;let o=aSt(this.stream),i="",a=!1;try{for(var s=oSt(o),u;u=yield $y(s.next()),!u.done;){let l=u.value;i+=this.decodeChunk(l);let c;for(;(c=i.indexOf(this.messageTerminator))>=0;){let d=i.slice(0,c+1);if(i=i.slice(c+1),d.length===0)continue;if(!a&&this.prefix!=null){let p=d.indexOf(this.prefix);if(p===-1)continue;a=!0,d=d.slice(p+this.prefix.length)}if(this.streamTerminator!=null&&d.includes(this.streamTerminator))return yield $y(void 0);let f=yield $y(this.parse(JSON.parse(d)));yield yield $y(f),a=!1}}}catch(l){r={error:l}}finally{try{u&&!u.done&&(n=s.return)&&(yield $y(n.call(s)))}finally{if(r)throw r.error}}})}[Symbol.asyncIterator](){return iSt(this,arguments,function*(){var r,n;try{for(var o=oSt(this.iterMessages()),i;i=yield $y(o.next()),!i.done;){let a=i.value;yield yield $y(a)}}catch(a){r={error:a}}finally{try{i&&!i.done&&(n=o.return)&&(yield $y(n.call(o)))}finally{if(r)throw r.error}}})}decodeChunk(e){let r="";if(typeof TextDecoder<"u"){let n=new TextDecoder("utf8");r+=n.decode(e)}else ATr.RUNTIME.type==="node"&&typeof e<"u"&&(r+=Buffer.isBuffer(e)?e:Buffer.from(e));return r}};Np.Stream=ZCe;function aSt(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{next(){return nSt(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 nSt(this,void 0,void 0,function*(){let r=e.cancel();return e.releaseLock(),yield r,{done:!0,value:void 0}})},[Symbol.asyncIterator](){return this}}}Np.readableStreamAsyncIterable=aSt});var sSt=v(Wee=>{"use strict";Object.defineProperty(Wee,"__esModule",{value:!0});Wee.Stream=void 0;var MTr=XCe();Object.defineProperty(Wee,"Stream",{enumerable:!0,get:function(){return MTr.Stream}})});var cSt=v((Lwo,lSt)=>{"use strict";var QCe=Object.defineProperty,RTr=Object.getOwnPropertyDescriptor,jTr=Object.getOwnPropertyNames,NTr=Object.prototype.hasOwnProperty,DTr=(t,e)=>{for(var r in e)QCe(t,r,{get:e[r],enumerable:!0})},LTr=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of jTr(e))!NTr.call(t,o)&&o!==r&&QCe(t,o,{get:()=>e[o],enumerable:!(n=RTr(e,o))||n.enumerable});return t},FTr=t=>LTr(QCe({},"__esModule",{value:!0}),t),uSt={};DTr(uSt,{Blob:()=>BTr,File:()=>qTr,FormData:()=>$Tr});lSt.exports=FTr(uSt);var kTr=function(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:window}(),{FormData:$Tr,Blob:BTr,File:qTr}=kTr});var xSt=v((Fwo,SSt)=>{"use strict";var rOe=Object.defineProperty,UTr=Object.getOwnPropertyDescriptor,zTr=Object.getOwnPropertyNames,HTr=Object.prototype.hasOwnProperty,VTr=(t,e)=>{for(var r in e)rOe(t,r,{get:e[r],enumerable:!0})},WTr=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of zTr(e))!HTr.call(t,o)&&o!==r&&rOe(t,o,{get:()=>e[o],enumerable:!(n=UTr(e,o))||n.enumerable});return t},KTr=t=>WTr(rOe({},"__esModule",{value:!0}),t),nOe=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},fs=(t,e,r)=>(nOe(t,e,"read from private field"),r?r.call(t):e.get(t)),Y_=(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)},sV=(t,e,r,n)=>(nOe(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),eOe=(t,e,r)=>(nOe(t,e,"access private method"),r),ySt={};VTr(ySt,{FormDataEncoder:()=>tAr,isFile:()=>fj,isFormData:()=>vSt});SSt.exports=KTr(ySt);var EO=t=>typeof t=="function",GTr=t=>EO(t[Symbol.asyncIterator]),dSt=65536;function*bSt(t){if(t.byteLength<=dSt){yield t;return}let e=0;for(;e<t.byteLength;){let r=Math.min(t.byteLength-e,dSt),n=t.buffer.slice(e,e+r);e+=n.byteLength,yield new Uint8Array(n)}}async function*JTr(t){let e=t.getReader();for(;;){let{done:r,value:n}=await e.read();if(r)break;yield n}}async function*fSt(t){for await(let e of t)yield*bSt(e)}var YTr=t=>{if(GTr(t))return fSt(t);if(EO(t.getReader))return fSt(JTr(t));throw new TypeError("Unsupported data source: Expected either ReadableStream or async iterable.")},pSt="abcdefghijklmnopqrstuvwxyz0123456789";function ZTr(){let t=16,e="";for(;t--;)e+=pSt[Math.random()*pSt.length<<0];return e}var _St=t=>String(t).replace(/\r|\n/g,(e,r,n)=>e==="\r"&&n[r+1]!==`
`+e.prev}function Oee(t,e){var r=wCe(t),n=[];if(r){n.length=t.length;for(var o=0;o<t.length;o++)n[o]=PO(t,o)?e(t[o],t):""}var i=typeof gCe=="function"?gCe(t):[],a;if(f$){a={};for(var s=0;s<i.length;s++)a["$"+i[s]]=i[s]}for(var u in t)PO(t,u)&&(r&&String(Number(u))===u&&u<t.length||f$&&a["$"+u]instanceof Symbol||(Fvt.call(/[^\w$]/,u)?n.push(e(u,t)+": "+e(t[u],t)):n.push(u+": "+e(t[u],t))));if(typeof gCe=="function")for(var l=0;l<i.length;l++)kvt.call(t,i[l])&&n.push("["+e(i[l])+"]: "+e(t[i[l]],t));return n}});var Wvt=v((Ivo,Vvt)=>{"use strict";var BOr=eV(),qOr=uj(),Tee=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},UOr=function(t,e){if(t){var r=Tee(t,e);return r&&r.value}},zOr=function(t,e,r){var n=Tee(t,e);n?n.value=r:t.next={key:e,next:t.next,value:r}},HOr=function(t,e){return t?!!Tee(t,e):!1},VOr=function(t,e){if(t)return Tee(t,e,!0)};Vvt.exports=function(){var e,r={assert:function(n){if(!r.has(n))throw new qOr("Side channel does not contain "+BOr(n))},delete:function(n){var o=e&&e.next,i=VOr(e,n);return i&&o&&o===i&&(e=void 0),!!i},get:function(n){return UOr(e,n)},has:function(n){return HOr(e,n)},set:function(n,o){e||(e={next:void 0}),zOr(e,n,o)}};return r}});var PCe=v((Mvo,Kvt)=>{"use strict";Kvt.exports=Object});var Jvt=v((Rvo,Gvt)=>{"use strict";Gvt.exports=Error});var Zvt=v((jvo,Yvt)=>{"use strict";Yvt.exports=EvalError});var Qvt=v((Nvo,Xvt)=>{"use strict";Xvt.exports=RangeError});var twt=v((Dvo,ewt)=>{"use strict";ewt.exports=ReferenceError});var nwt=v((Lvo,rwt)=>{"use strict";rwt.exports=SyntaxError});var iwt=v((Fvo,owt)=>{"use strict";owt.exports=URIError});var swt=v((kvo,awt)=>{"use strict";awt.exports=Math.abs});var lwt=v(($vo,uwt)=>{"use strict";uwt.exports=Math.floor});var dwt=v((Bvo,cwt)=>{"use strict";cwt.exports=Math.max});var pwt=v((qvo,fwt)=>{"use strict";fwt.exports=Math.min});var hwt=v((Uvo,mwt)=>{"use strict";mwt.exports=Math.pow});var ywt=v((zvo,gwt)=>{"use strict";gwt.exports=Math.round});var _wt=v((Hvo,bwt)=>{"use strict";bwt.exports=Number.isNaN||function(e){return e!==e}});var wwt=v((Vvo,vwt)=>{"use strict";var WOr=_wt();vwt.exports=function(e){return WOr(e)||e===0?e:e<0?-1:1}});var xwt=v((Wvo,Swt)=>{"use strict";Swt.exports=Object.getOwnPropertyDescriptor});var ECe=v((Kvo,Cwt)=>{"use strict";var Aee=xwt();if(Aee)try{Aee([],"length")}catch{Aee=null}Cwt.exports=Aee});var Pwt=v((Gvo,Owt)=>{"use strict";var Iee=Object.defineProperty||!1;if(Iee)try{Iee({},"a",{value:1})}catch{Iee=!1}Owt.exports=Iee});var Twt=v((Jvo,Ewt)=>{"use strict";Ewt.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 Mwt=v((Yvo,Iwt)=>{"use strict";var Awt=typeof Symbol<"u"&&Symbol,KOr=Twt();Iwt.exports=function(){return typeof Awt!="function"||typeof Symbol!="function"||typeof Awt("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:KOr()}});var TCe=v((Zvo,Rwt)=>{"use strict";Rwt.exports=typeof Reflect<"u"&&Reflect.getPrototypeOf||null});var ACe=v((Xvo,jwt)=>{"use strict";var GOr=PCe();jwt.exports=GOr.getPrototypeOf||null});var Lwt=v((Qvo,Dwt)=>{"use strict";var JOr="Function.prototype.bind called on incompatible ",YOr=Object.prototype.toString,ZOr=Math.max,XOr="[object Function]",Nwt=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},QOr=function(e,r){for(var n=[],o=r||0,i=0;o<e.length;o+=1,i+=1)n[i]=e[o];return n},ePr=function(t,e){for(var r="",n=0;n<t.length;n+=1)r+=t[n],n+1<t.length&&(r+=e);return r};Dwt.exports=function(e){var r=this;if(typeof r!="function"||YOr.apply(r)!==XOr)throw new TypeError(JOr+r);for(var n=QOr(arguments,1),o,i=function(){if(this instanceof o){var c=r.apply(this,Nwt(n,arguments));return Object(c)===c?c:this}return r.apply(e,Nwt(n,arguments))},a=ZOr(0,r.length-n.length),s=[],u=0;u<a;u++)s[u]="$"+u;if(o=Function("binder","return function ("+ePr(s,",")+"){ return binder.apply(this,arguments); }")(i),r.prototype){var l=function(){};l.prototype=r.prototype,o.prototype=new l,l.prototype=null}return o}});var tV=v((ewo,Fwt)=>{"use strict";var tPr=Lwt();Fwt.exports=Function.prototype.bind||tPr});var Mee=v((two,kwt)=>{"use strict";kwt.exports=Function.prototype.call});var ICe=v((rwo,$wt)=>{"use strict";$wt.exports=Function Line truncated
`,this.streamTerminator=n.streamTerminator):this.messageTerminator=n.messageTerminator,o?.addEventListener("abort",()=>this.controller.abort())}iterMessages(){return lSt(this,arguments,function*(){var r,n;this.controller.signal;let o=cSt(this.stream),i="",a=!1;try{for(var s=uSt(o),u;u=yield $y(s.next()),!u.done;){let l=u.value;i+=this.decodeChunk(l);let c;for(;(c=i.indexOf(this.messageTerminator))>=0;){let d=i.slice(0,c+1);if(i=i.slice(c+1),d.length===0)continue;if(!a&&this.prefix!=null){let p=d.indexOf(this.prefix);if(p===-1)continue;a=!0,d=d.slice(p+this.prefix.length)}if(this.streamTerminator!=null&&d.includes(this.streamTerminator))return yield $y(void 0);let f=yield $y(this.parse(JSON.parse(d)));yield yield $y(f),a=!1}}}catch(l){r={error:l}}finally{try{u&&!u.done&&(n=s.return)&&(yield $y(n.call(s)))}finally{if(r)throw r.error}}})}[Symbol.asyncIterator](){return lSt(this,arguments,function*(){var r,n;try{for(var o=uSt(this.iterMessages()),i;i=yield $y(o.next()),!i.done;){let a=i.value;yield yield $y(a)}}catch(a){r={error:a}}finally{try{i&&!i.done&&(n=o.return)&&(yield $y(n.call(o)))}finally{if(r)throw r.error}}})}decodeChunk(e){let r="";if(typeof TextDecoder<"u"){let n=new TextDecoder("utf8");r+=n.decode(e)}else NTr.RUNTIME.type==="node"&&typeof e<"u"&&(r+=Buffer.isBuffer(e)?e:Buffer.from(e));return r}};Np.Stream=eOe;function cSt(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{next(){return sSt(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 sSt(this,void 0,void 0,function*(){let r=e.cancel();return e.releaseLock(),yield r,{done:!0,value:void 0}})},[Symbol.asyncIterator](){return this}}}Np.readableStreamAsyncIterable=cSt});var dSt=v(Kee=>{"use strict";Object.defineProperty(Kee,"__esModule",{value:!0});Kee.Stream=void 0;var LTr=tOe();Object.defineProperty(Kee,"Stream",{enumerable:!0,get:function(){return LTr.Stream}})});var mSt=v((qwo,pSt)=>{"use strict";var rOe=Object.defineProperty,FTr=Object.getOwnPropertyDescriptor,kTr=Object.getOwnPropertyNames,$Tr=Object.prototype.hasOwnProperty,BTr=(t,e)=>{for(var r in e)rOe(t,r,{get:e[r],enumerable:!0})},qTr=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of kTr(e))!$Tr.call(t,o)&&o!==r&&rOe(t,o,{get:()=>e[o],enumerable:!(n=FTr(e,o))||n.enumerable});return t},UTr=t=>qTr(rOe({},"__esModule",{value:!0}),t),fSt={};BTr(fSt,{Blob:()=>VTr,File:()=>WTr,FormData:()=>HTr});pSt.exports=UTr(fSt);var zTr=function(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:window}(),{FormData:HTr,Blob:VTr,File:WTr}=zTr});var ESt=v((Uwo,PSt)=>{"use strict";var iOe=Object.defineProperty,KTr=Object.getOwnPropertyDescriptor,GTr=Object.getOwnPropertyNames,JTr=Object.prototype.hasOwnProperty,YTr=(t,e)=>{for(var r in e)iOe(t,r,{get:e[r],enumerable:!0})},ZTr=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of GTr(e))!JTr.call(t,o)&&o!==r&&iOe(t,o,{get:()=>e[o],enumerable:!(n=KTr(e,o))||n.enumerable});return t},XTr=t=>ZTr(iOe({},"__esModule",{value:!0}),t),aOe=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},fs=(t,e,r)=>(aOe(t,e,"read from private field"),r?r.call(t):e.get(t)),Y_=(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)},uV=(t,e,r,n)=>(aOe(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),nOe=(t,e,r)=>(aOe(t,e,"access private method"),r),wSt={};YTr(wSt,{FormDataEncoder:()=>aAr,isFile:()=>pj,isFormData:()=>CSt});PSt.exports=XTr(wSt);var TO=t=>typeof t=="function",QTr=t=>TO(t[Symbol.asyncIterator]),hSt=65536;function*SSt(t){if(t.byteLength<=hSt){yield t;return}let e=0;for(;e<t.byteLength;){let r=Math.min(t.byteLength-e,hSt),n=t.buffer.slice(e,e+r);e+=n.byteLength,yield new Uint8Array(n)}}async function*eAr(t){let e=t.getReader();for(;;){let{done:r,value:n}=await e.read();if(r)break;yield n}}async function*gSt(t){for await(let e of t)yield*SSt(e)}var tAr=t=>{if(QTr(t))return gSt(t);if(TO(t.getReader))return gSt(eAr(t));throw new TypeError("Unsupported data source: Expected either ReadableStream or async iterable.")},ySt="abcdefghijklmnopqrstuvwxyz0123456789";function rAr(){let t=16,e="";for(;t--;)e+=ySt[Math.random()*ySt.length<<0];return e}var xSt=t=>String(t).replace(/\r|\n/g,(e,r,n)=>e==="\r"&&n[r+1]!==`
`||e===`
`&&n[r-1]!=="\r"?`\r
`:e),XTr=t=>Object.prototype.toString.call(t).slice(8,-1).toLowerCase();function mSt(t){if(XTr(t)!=="object")return!1;let e=Object.getPrototypeOf(t);return e==null?!0:(e.constructor&&e.constructor.toString())===Object.toString()}function hSt(t,e){if(typeof e=="string"){for(let[r,n]of Object.entries(t))if(e.toLowerCase()===r.toLowerCase())return n}}var QTr=t=>new Proxy(t,{get:(e,r)=>hSt(e,r),has:(e,r)=>hSt(e,r)!==void 0}),vSt=t=>!!(t&&EO(t.constructor)&&t[Symbol.toStringTag]==="FormData"&&EO(t.append)&&EO(t.getAll)&&EO(t.entries)&&EO(t[Symbol.iterator])),gSt=t=>String(t).replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/"/g,"%22"),fj=t=>!!(t&&typeof t=="object"&&EO(t.constructor)&&t[Symbol.toStringTag]==="File"&&EO(t.stream)&&t.name!=null),eAr={enableAdditionalHeaders:!1},Kee={writable:!1,configurable:!1},dA,uV,Gee,lV,dj,cV,dV,Jee,Yee,oOe,tOe,wSt,tAr=class{constructor(t,e,r){if(Y_(this,Yee),Y_(this,tOe),Y_(this,dA,`\r
`),Y_(this,uV,void 0),Y_(this,Gee,void 0),Y_(this,lV,"-".repeat(2)),Y_(this,dj,new TextEncoder),Y_(this,cV,void 0),Y_(this,dV,void 0),Y_(this,Jee,void 0),!vSt(t))throw new TypeError("Expected first argument to be a FormData instance.");let n;if(mSt(e)?r=e:n=e,n||(n=ZTr()),typeof n!="string")throw new TypeError("Expected boundary argument to be a string.");if(r&&!mSt(r))throw new TypeError("Expected options argument to be an object.");sV(this,dV,Array.from(t.entries())),sV(this,Jee,{...eAr,...r}),sV(this,uV,fs(this,dj).encode(fs(this,dA))),sV(this,Gee,fs(this,uV).byteLength),this.boundary=`form-data-boundary-${n}`,this.contentType=`multipart/form-data; boundary=${this.boundary}`,sV(this,cV,fs(this,dj).encode(`${fs(this,lV)}${this.boundary}${fs(this,lV)}${fs(this,dA).repeat(2)}`));let o={"Content-Type":this.contentType},i=eOe(this,tOe,wSt).call(this);i&&(this.contentLength=i,o["Content-Length"]=i),this.headers=QTr(Object.freeze(o)),Object.defineProperties(this,{boundary:Kee,contentType:Kee,contentLength:Kee,headers:Kee})}*values(){for(let[t,e]of fs(this,dV)){let r=fj(e)?e:fs(this,dj).encode(_St(e));yield eOe(this,Yee,oOe).call(this,t,r),yield r,yield fs(this,uV)}yield fs(this,cV)}async*encode(){for(let t of this.values())fj(t)?yield*YTr(t.stream()):yield*bSt(t)}[Symbol.iterator](){return this.values()}[Symbol.asyncIterator](){return this.encode()}};dA=new WeakMap;uV=new WeakMap;Gee=new WeakMap;lV=new WeakMap;dj=new WeakMap;cV=new WeakMap;dV=new WeakMap;Jee=new WeakMap;Yee=new WeakSet;oOe=function(t,e){let r="";if(r+=`${fs(this,lV)}${this.boundary}${fs(this,dA)}`,r+=`Content-Disposition: form-data; name="${gSt(t)}"`,fj(e)&&(r+=`; filename="${gSt(e.name)}"${fs(this,dA)}`,r+=`Content-Type: ${e.type||"application/octet-stream"}`),fs(this,Jee).enableAdditionalHeaders===!0){let n=fj(e)?e.size:e.byteLength;n!=null&&!isNaN(n)&&(r+=`${fs(this,dA)}Content-Length: ${n}`)}return fs(this,dj).encode(`${r}${fs(this,dA).repeat(2)}`)};tOe=new WeakSet;wSt=function(){let t=0;for(let[e,r]of fs(this,dV)){let n=fj(r)?r:fs(this,dj).encode(_St(r)),o=fj(n)?n.size:n.byteLength;if(o==null||isNaN(o))return;t+=eOe(this,Yee,oOe).call(this,e,n).byteLength,t+=o,t+=fs(this,Gee)}return String(t+fs(this,cV).byteLength)}});var OSt=v(($wo,CSt)=>{CSt.exports=typeof self=="object"?self.FormData:window.FormData});var PSt=v(Ql=>{"use strict";var rAr=Ql&&Ql.__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]}),nAr=Ql&&Ql.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),I$=Ql&&Ql.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&rAr(e,t,r);return nAr(e,t),e},fA=Ql&&Ql.__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(Ql,"__esModule",{value:!0});Ql.WebFormData=Ql.Node16FormData=Ql.Node18FormData=Ql.newFormData=void 0;var Zee=_$();function iOe(t){return typeof t=="object"&&t!=null&&"name"in t}function oAr(){return fA(this,void 0,void 0,function*(){let t;return Zee.RUNTIME.type==="node"&&Zee.RUNTIME.parsedVersion!=null&&Zee.RUNTIME.parsedVersion>=18?t=new Xee:Zee.RUNTIME.type==="node"?t=new Qee:t=new ete,yield t.setup(),t})}Ql.newFormData=oAr;var Xee=class{setup(){return fA(this,void 0,void 0,function*(){this.fd=new(yield Promise.resolve().then(()=>I$(cSt()))).FormData})}append(e,r){var n;(n=this.fd)===null||n===void 0||n.append(e,r)}appendFile(e,r,n){var o,i;return fA(this,void 0,void 0,function*(){n==null&&iOe(r)&&(n=r.name),r instanceof(yield Promise.resolve().then(()=>I$(JH()))).Readable?(o=this.fd)===null||o===void 0||o.append(e,{type:void 0,name:n,[Symbol.toStringTag]:"File",stream(){return r}}):(i=this.fd)===null||i===void 0||i.append(e,r,n)})}getRequest(){return fA(this,void 0,void 0,function*(){let e=new(yield Promise.resolve().then(()=>I$(xSt()))).FormDataEncoder(this.fd);return{body:yield(yield Promise.resolve().then(()=>I$(JH()))).Readable.from(e),headers:e.headers,duplex:"half"}})}};Ql.Node18FormData=Xee;var Qee=class{setup(){return fA(this,void 0,void 0,function*(){this.fd=new(yield Promise.resolve().then(()=>I$(OSt()))).default})}append(e,r){var n;(n=this.fd)===null||n===void 0||n.append(e,r)}appendFile(e,r,n){var o,i;return fA(this,void 0,void 0,function*(){n==null&&iOe(r)&&(n=r.name);let a;r instanceof(yield Promise.resolve().then(()=>I$(JH()))).Readable?a=r:a=Buffer.from(yield r.arrayBuffer()),n==null?(o=this.fd)===null||o===void 0||o.a Line truncated
`)),{ok:!0,value:e}):n}}});var aOe=v(ote=>{"use strict";Object.defineProperty(ote,"__esModule",{value:!0});ote.stringifyValidationError=void 0;function cAr(t){return t.path.length===0?t.message:`${t.path.join(" -> ")}: ${t.message}`}ote.stringifyValidationError=cAr});var uOe=v(ite=>{"use strict";Object.defineProperty(ite,"__esModule",{value:!0});ite.JsonError=void 0;var dAr=aOe(),sOe=class t extends Error{constructor(e){super(e.map(dAr.stringifyValidationError).join("; ")),this.errors=e,Object.setPrototypeOf(this,t.prototype)}};ite.JsonError=sOe});var cOe=v(ate=>{"use strict";Object.defineProperty(ate,"__esModule",{value:!0});ate.ParseError=void 0;var fAr=aOe(),lOe=class t extends Error{constructor(e){super(e.map(fAr.stringifyValidationError).join("; ")),this.errors=e,Object.setPrototypeOf(this,t.prototype)}};ate.ParseError=lOe});var MSt=v(pA=>{"use strict";Object.defineProperty(pA,"__esModule",{value:!0});pA.transform=pA.optional=pA.getSchemaUtils=void 0;var pAr=Uc(),mAr=uOe(),hAr=cOe();function dOe(t){return{optional:()=>ASt(t),transform:e=>ISt(t,e),parseOrThrow:(e,r)=>{let n=t.parse(e,r);if(n.ok)return n.value;throw new hAr.ParseError(n.errors)},jsonOrThrow:(e,r)=>{let n=t.json(e,r);if(n.ok)return n.value;throw new mAr.JsonError(n.errors)}}}pA.getSchemaUtils=dOe;function ASt(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:()=>pAr.SchemaType.OPTIONAL};return Object.assign(Object.assign({},e),dOe(e))}pA.optional=ASt;function ISt(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),dOe(r))}pA.transform=ISt});var Lm=v(ag=>{"use strict";Object.defineProperty(ag,"__esModule",{value:!0});ag.ParseError=ag.JsonError=ag.transform=ag.optional=ag.getSchemaUtils=void 0;var fOe=MSt();Object.defineProperty(ag,"getSchemaUtils",{enumerable:!0,get:function(){return fOe.getSchemaUtils}});Object.defineProperty(ag,"optional",{enumerable:!0,get:function(){return fOe.optional}});Object.defineProperty(ag,"transform",{enumerable:!0,get:function(){return fOe.transform}});var gAr=uOe();Object.defineProperty(ag,"JsonError",{enumerable:!0,get:function(){return gAr.JsonError}});var yAr=cOe();Object.defineProperty(ag,"ParseError",{enumerable:!0,get:function(){return yAr.ParseError}})});var RSt=v(ste=>{"use strict";Object.defineProperty(ste,"__esModule",{value:!0});ste.date=void 0;var bAr=Uc(),pOe=Dp(),_Ar=TO(),vAr=Lm(),wAr=/^([+-]?\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])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function SAr(){let t={parse:(e,{breadcrumbsPrefix:r=[]}={})=>typeof e!="string"?{ok:!1,errors:[{path:r,message:(0,pOe.getErrorMessageForIncorrectType)(e,"string")}]}:wAr.test(e)?{ok:!0,value:new Date(e)}:{ok:!1,errors:[{path:r,message:(0,pOe.getErrorMessageForIncorrectType)(e,"ISO 8601 date string")}]},json:(e,{breadcrumbsPrefix:r=[]}={})=>e instanceof Date?{ok:!0,value:e.toISOString()}:{ok:!1,errors:[{path:r,message:(0,pOe.getErrorMessageForIncorrectType)(e,"Date object")}]},getType:()=>bAr.SchemaType.DATE};return Object.assign(Object.assign({},(0,_Ar.maybeSkipValidation)(t)),(0,vAr.getSchemaUtils)(t))}ste.date=SAr});var jSt=v(ute=>{"use strict";Object.defineProperty(ute,"__esModule",{value:!0});ute.date=void 0;var xAr=RSt();Object.defineProperty(ute,"date",{enumerable:!0,get:function(){return xAr.date}})});var AO=v(lte=>{"use strict";Object.defineProperty(lte,"__esModule",{value:!0});lte.createIdentitySchemaCreator=void 0;var CAr=Lm(),OAr=TO();function PAr(t,e){return()=>{let r={parse:e,json:e,getType:()=>t};return Object.assign(Object.assign({},(0,OAr.maybeSkipValidation)(r)),(0,CAr.getSchemaUtils)(r))}}lte.createIdentitySchemaCreator=PAr});var DSt=v(cte=>{"use strict";Object.defineProperty(cte,"__esModule",{value:!0});cte.enum_=void 0;var EAr=Uc(),TAr=AO(),NSt=Dp();function AAr(t){let e=new Set(t);return(0,TAr.createIdentitySchemaCreator)(EAr.SchemaType.ENUM,(n,{allowUnrecognizedEnumValues:o,breadcrumbsPrefix:i=[]}={})=>typeof n!="string"?{ok:!1,errors:[{path:i,message:(0,NSt.getErrorMessageForIncorrectType)(n,"string")}]}:!e.has(n)&&!o?{ok:!1,errors:[{path:i,message:(0,NSt.getErrorMessageForIncorrectType)(n,"enum")}]}:{ok:!0,value:n})()}cte.enum_=AAr});var mOe=v(dte=>{"use strict";Object.defineProperty(dte,"__esModule",{value:!0});dte.enum_=void 0;var IAr=DSt();Object.defineProperty(dte,"enum_",{enumerable:!0,get:function(){return IAr.enum_}})});var hOe=v(mA=>{"use strict";Object.defineProperty(mA,"__esModule",{value:!0});mA.getMemoizedSchema=mA.constructLazyBaseSchema=mA.lazy=void 0;var MAr=Lm();function RAr(t){let e=LSt(t);return Object.assign(Obje Line truncated
`);o.enqueue(s)}catch(i){o.error(i)}})},cancel(){var o;return yV(this,void 0,void 0,function*(){yield(o=r.return)===null||o===void 0?void 0:o.call(r)})}})}};Vs.StreamUtils=POe;function Ext(t,e){return _V(this,arguments,function*(){var n,o;if(!t.body)throw e?.abort(),new $$.CohereError({message:"Attempted to iterate over a response with no body"});let i=new EOe,a=new hA,s=TOe(t.body);try{for(var u=bV(SMr(s)),l;l=yield Ta(u.next()),!l.done;){let c=l.value;for(let d of a.decode(c)){let f=i.decode(d);f&&(yield yield Ta(f))}}}catch(c){n={error:c}}finally{try{l&&!l.done&&(o=u.return)&&(yield Ta(o.call(u)))}finally{if(n)throw n.error}}for(let c of a.flush()){let d=i.decode(c);d&&(yield yield Ta(d))}})}Vs._iterSSEMessages=Ext;function SMr(t){return _V(this,arguments,function*(){var r,n;let o=new Uint8Array;try{for(var i=bV(t),a;a=yield Ta(i.next()),!a.done;){let s=a.value;if(s==null)continue;let u=s instanceof ArrayBuffer?new Uint8Array(s):typeof s=="string"?new TextEncoder().encode(s):s,l=new Uint8Array(o.length+u.length);l.set(o),l.set(u,o.length),o=l;let c;for(;(c=xMr(o))!==-1;)yield yield Ta(o.slice(0,c)),o=o.slice(c)}}catch(s){r={error:s}}finally{try{a&&!a.done&&(n=i.return)&&(yield Ta(n.call(i)))}finally{if(r)throw r.error}}o.length>0&&(yield yield Ta(o))})}function xMr(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 EOe=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]=OMr(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},hA=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 $$.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 $$.CohereError({message:`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`})}throw new $$.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}};Vs.LineDecoder=hA;hA.NEWLINE_CHARS=new Set([`
`,"\r"]);hA.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function CMr(t){let e=new hA,r=[];for(let n of t)r.push(...e.decode(n));return r}Vs._decodeChunks=CMr;function OMr(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}function TOe(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{next(){return yV(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 yV(this,void 0,void 0,function*(){let r=e.cancel();return e.releaseLock(),yield r,{done:!0,value:void 0}})},[Symbol.asyncIterator](){return this}}}Vs.readableStreamAsyncIterable=TOe});var AOe=v(Z_=>{"use strict";var PMr=Z_&&Z_.__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]}),EMr=Z_&&Z_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),TMr=Z_&&Z_.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&PMr(e,t,r);return EMr(e,t),e};Object.defineProperty(Z_,"__esModule",{value:!0});Z_.V2ChatStreamRequestCitationMode=void 0;var AMr=TMr(G());Z_.V2ChatStreamRequestCitationMode=AMr.serialization.enum_(["FAST","ACCURATE","OFF"])});var IOe=v(X_=>{"use strict";var IMr=X_&&X_.__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]}),MMr=X_&&X_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),RMr=X_&&X_.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&IMr(e,t,r);return MMr(e,t),e};Object.defineProperty(X_,"__esModule",{value:!0});X_.V2ChatRequestCitationMode=void 0;var jMr=RMr(G());X_.V2ChatRequestCitationMode=jMr.serialization.enum_(["FAST","ACCURATE","OFF"])});var B$=v(Q_=>{"use strict";var NMr=Q_&&Q_.__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]}),DMr=Q_&&Q_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),LMr=Q_&&Q_.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&NMr(e,t,r);return DMr(e,t),e};Object.defineProperty(Q_,"__esModule",{value:!0});Q_.TextContent=void 0;var Axt=LMr(G());Q_.TextContent=Axt.serialization.object({text:Axt.serialization.string()})});var MOe=v(ev=>{"use strict";var FMr=ev&&ev.__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]}),kMr=ev&&ev.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),$Mr=ev&&ev.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&FMr(e,t,r);return kMr(e,t),e};Object.defineProperty(ev,"__esModule",{value:!0});ev.Content=void 0;var BMr=$Mr(G()),qMr=B$();ev.Content=BMr.serialization.union("type",{text:qMr.TextContent}).transform({transform:t=>t,untransform:t=>t})});var jOe=v(tv=>{"use strict";var UMr=tv&&tv.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),zMr=tv&&tv.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),HMr=tv&&tv.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&UMr(e,t,r);return zMr(e,t),e};Object.defineProperty(tv,"__esModule",{value:!0});tv.UserMessageContent=void 0;var ROe=HMr(G()),VMr=MOe();tv.UserMessageContent=ROe.serialization.undiscriminatedUnion([ROe.serialization.string Line truncated
`:e),nAr=t=>Object.prototype.toString.call(t).slice(8,-1).toLowerCase();function bSt(t){if(nAr(t)!=="object")return!1;let e=Object.getPrototypeOf(t);return e==null?!0:(e.constructor&&e.constructor.toString())===Object.toString()}function _St(t,e){if(typeof e=="string"){for(let[r,n]of Object.entries(t))if(e.toLowerCase()===r.toLowerCase())return n}}var oAr=t=>new Proxy(t,{get:(e,r)=>_St(e,r),has:(e,r)=>_St(e,r)!==void 0}),CSt=t=>!!(t&&TO(t.constructor)&&t[Symbol.toStringTag]==="FormData"&&TO(t.append)&&TO(t.getAll)&&TO(t.entries)&&TO(t[Symbol.iterator])),vSt=t=>String(t).replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/"/g,"%22"),pj=t=>!!(t&&typeof t=="object"&&TO(t.constructor)&&t[Symbol.toStringTag]==="File"&&TO(t.stream)&&t.name!=null),iAr={enableAdditionalHeaders:!1},Gee={writable:!1,configurable:!1},dA,lV,Jee,cV,fj,dV,fV,Yee,Zee,sOe,oOe,OSt,aAr=class{constructor(t,e,r){if(Y_(this,Zee),Y_(this,oOe),Y_(this,dA,`\r
`),Y_(this,lV,void 0),Y_(this,Jee,void 0),Y_(this,cV,"-".repeat(2)),Y_(this,fj,new TextEncoder),Y_(this,dV,void 0),Y_(this,fV,void 0),Y_(this,Yee,void 0),!CSt(t))throw new TypeError("Expected first argument to be a FormData instance.");let n;if(bSt(e)?r=e:n=e,n||(n=rAr()),typeof n!="string")throw new TypeError("Expected boundary argument to be a string.");if(r&&!bSt(r))throw new TypeError("Expected options argument to be an object.");uV(this,fV,Array.from(t.entries())),uV(this,Yee,{...iAr,...r}),uV(this,lV,fs(this,fj).encode(fs(this,dA))),uV(this,Jee,fs(this,lV).byteLength),this.boundary=`form-data-boundary-${n}`,this.contentType=`multipart/form-data; boundary=${this.boundary}`,uV(this,dV,fs(this,fj).encode(`${fs(this,cV)}${this.boundary}${fs(this,cV)}${fs(this,dA).repeat(2)}`));let o={"Content-Type":this.contentType},i=nOe(this,oOe,OSt).call(this);i&&(this.contentLength=i,o["Content-Length"]=i),this.headers=oAr(Object.freeze(o)),Object.defineProperties(this,{boundary:Gee,contentType:Gee,contentLength:Gee,headers:Gee})}*values(){for(let[t,e]of fs(this,fV)){let r=pj(e)?e:fs(this,fj).encode(xSt(e));yield nOe(this,Zee,sOe).call(this,t,r),yield r,yield fs(this,lV)}yield fs(this,dV)}async*encode(){for(let t of this.values())pj(t)?yield*tAr(t.stream()):yield*SSt(t)}[Symbol.iterator](){return this.values()}[Symbol.asyncIterator](){return this.encode()}};dA=new WeakMap;lV=new WeakMap;Jee=new WeakMap;cV=new WeakMap;fj=new WeakMap;dV=new WeakMap;fV=new WeakMap;Yee=new WeakMap;Zee=new WeakSet;sOe=function(t,e){let r="";if(r+=`${fs(this,cV)}${this.boundary}${fs(this,dA)}`,r+=`Content-Disposition: form-data; name="${vSt(t)}"`,pj(e)&&(r+=`; filename="${vSt(e.name)}"${fs(this,dA)}`,r+=`Content-Type: ${e.type||"application/octet-stream"}`),fs(this,Yee).enableAdditionalHeaders===!0){let n=pj(e)?e.size:e.byteLength;n!=null&&!isNaN(n)&&(r+=`${fs(this,dA)}Content-Length: ${n}`)}return fs(this,fj).encode(`${r}${fs(this,dA).repeat(2)}`)};oOe=new WeakSet;OSt=function(){let t=0;for(let[e,r]of fs(this,fV)){let n=pj(r)?r:fs(this,fj).encode(xSt(r)),o=pj(n)?n.size:n.byteLength;if(o==null||isNaN(o))return;t+=nOe(this,Zee,sOe).call(this,e,n).byteLength,t+=o,t+=fs(this,Jee)}return String(t+fs(this,dV).byteLength)}});var ASt=v((Hwo,TSt)=>{TSt.exports=typeof self=="object"?self.FormData:window.FormData});var ISt=v(Ql=>{"use strict";var sAr=Ql&&Ql.__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]}),uAr=Ql&&Ql.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),M$=Ql&&Ql.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&sAr(e,t,r);return uAr(e,t),e},fA=Ql&&Ql.__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(Ql,"__esModule",{value:!0});Ql.WebFormData=Ql.Node16FormData=Ql.Node18FormData=Ql.newFormData=void 0;var Xee=v$();function uOe(t){return typeof t=="object"&&t!=null&&"name"in t}function lAr(){return fA(this,void 0,void 0,function*(){let t;return Xee.RUNTIME.type==="node"&&Xee.RUNTIME.parsedVersion!=null&&Xee.RUNTIME.parsedVersion>=18?t=new Qee:Xee.RUNTIME.type==="node"?t=new ete:t=new tte,yield t.setup(),t})}Ql.newFormData=lAr;var Qee=class{setup(){return fA(this,void 0,void 0,function*(){this.fd=new(yield Promise.resolve().then(()=>M$(mSt()))).FormData})}append(e,r){var n;(n=this.fd)===null||n===void 0||n.append(e,r)}appendFile(e,r,n){var o,i;return fA(this,void 0,void 0,function*(){n==null&&uOe(r)&&(n=r.name),r instanceof(yield Promise.resolve().then(()=>M$(YH()))).Readable?(o=this.fd)===null||o===void 0||o.append(e,{type:void 0,name:n,[Symbol.toStringTag]:"File",stream(){return r}}):(i=this.fd)===null||i===void 0||i.append(e,r,n)})}getRequest(){return fA(this,void 0,void 0,function*(){let e=new(yield Promise.resolve().then(()=>M$(ESt()))).FormDataEncoder(this.fd);return{body:yield(yield Promise.resolve().then(()=>M$(YH()))).Readable.from(e),headers:e.headers,duplex:"half"}})}};Ql.Node18FormData=Qee;var ete=class{setup(){return fA(this,void 0,void 0,function*(){this.fd=new(yield Promise.resolve().then(()=>M$(ASt()))).default})}append(e,r){var n;(n=this.fd)===null||n===void 0||n.append(e,r)}appendFile(e,r,n){var o,i;return fA(this,void 0,void 0,function*(){n==null&&uOe(r)&&(n=r.name);let a;r instanceof(yield Promise.resolve().then(()=>M$(YH()))).Readable?a=r:a=Buffer.from(yield r.arrayBuffer()),n==null?(o=this.fd)===null||o===void 0||o.a Line truncated
`)),{ok:!0,value:e}):n}}});var lOe=v(ite=>{"use strict";Object.defineProperty(ite,"__esModule",{value:!0});ite.stringifyValidationError=void 0;function hAr(t){return t.path.length===0?t.message:`${t.path.join(" -> ")}: ${t.message}`}ite.stringifyValidationError=hAr});var dOe=v(ate=>{"use strict";Object.defineProperty(ate,"__esModule",{value:!0});ate.JsonError=void 0;var gAr=lOe(),cOe=class t extends Error{constructor(e){super(e.map(gAr.stringifyValidationError).join("; ")),this.errors=e,Object.setPrototypeOf(this,t.prototype)}};ate.JsonError=cOe});var pOe=v(ste=>{"use strict";Object.defineProperty(ste,"__esModule",{value:!0});ste.ParseError=void 0;var yAr=lOe(),fOe=class t extends Error{constructor(e){super(e.map(yAr.stringifyValidationError).join("; ")),this.errors=e,Object.setPrototypeOf(this,t.prototype)}};ste.ParseError=fOe});var DSt=v(pA=>{"use strict";Object.defineProperty(pA,"__esModule",{value:!0});pA.transform=pA.optional=pA.getSchemaUtils=void 0;var bAr=Uc(),_Ar=dOe(),vAr=pOe();function mOe(t){return{optional:()=>jSt(t),transform:e=>NSt(t,e),parseOrThrow:(e,r)=>{let n=t.parse(e,r);if(n.ok)return n.value;throw new vAr.ParseError(n.errors)},jsonOrThrow:(e,r)=>{let n=t.json(e,r);if(n.ok)return n.value;throw new _Ar.JsonError(n.errors)}}}pA.getSchemaUtils=mOe;function jSt(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:()=>bAr.SchemaType.OPTIONAL};return Object.assign(Object.assign({},e),mOe(e))}pA.optional=jSt;function NSt(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),mOe(r))}pA.transform=NSt});var Lm=v(ag=>{"use strict";Object.defineProperty(ag,"__esModule",{value:!0});ag.ParseError=ag.JsonError=ag.transform=ag.optional=ag.getSchemaUtils=void 0;var hOe=DSt();Object.defineProperty(ag,"getSchemaUtils",{enumerable:!0,get:function(){return hOe.getSchemaUtils}});Object.defineProperty(ag,"optional",{enumerable:!0,get:function(){return hOe.optional}});Object.defineProperty(ag,"transform",{enumerable:!0,get:function(){return hOe.transform}});var wAr=dOe();Object.defineProperty(ag,"JsonError",{enumerable:!0,get:function(){return wAr.JsonError}});var SAr=pOe();Object.defineProperty(ag,"ParseError",{enumerable:!0,get:function(){return SAr.ParseError}})});var LSt=v(ute=>{"use strict";Object.defineProperty(ute,"__esModule",{value:!0});ute.date=void 0;var xAr=Uc(),gOe=Dp(),CAr=AO(),OAr=Lm(),PAr=/^([+-]?\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])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function EAr(){let t={parse:(e,{breadcrumbsPrefix:r=[]}={})=>typeof e!="string"?{ok:!1,errors:[{path:r,message:(0,gOe.getErrorMessageForIncorrectType)(e,"string")}]}:PAr.test(e)?{ok:!0,value:new Date(e)}:{ok:!1,errors:[{path:r,message:(0,gOe.getErrorMessageForIncorrectType)(e,"ISO 8601 date string")}]},json:(e,{breadcrumbsPrefix:r=[]}={})=>e instanceof Date?{ok:!0,value:e.toISOString()}:{ok:!1,errors:[{path:r,message:(0,gOe.getErrorMessageForIncorrectType)(e,"Date object")}]},getType:()=>xAr.SchemaType.DATE};return Object.assign(Object.assign({},(0,CAr.maybeSkipValidation)(t)),(0,OAr.getSchemaUtils)(t))}ute.date=EAr});var FSt=v(lte=>{"use strict";Object.defineProperty(lte,"__esModule",{value:!0});lte.date=void 0;var TAr=LSt();Object.defineProperty(lte,"date",{enumerable:!0,get:function(){return TAr.date}})});var IO=v(cte=>{"use strict";Object.defineProperty(cte,"__esModule",{value:!0});cte.createIdentitySchemaCreator=void 0;var AAr=Lm(),IAr=AO();function MAr(t,e){return()=>{let r={parse:e,json:e,getType:()=>t};return Object.assign(Object.assign({},(0,IAr.maybeSkipValidation)(r)),(0,AAr.getSchemaUtils)(r))}}cte.createIdentitySchemaCreator=MAr});var $St=v(dte=>{"use strict";Object.defineProperty(dte,"__esModule",{value:!0});dte.enum_=void 0;var RAr=Uc(),jAr=IO(),kSt=Dp();function NAr(t){let e=new Set(t);return(0,jAr.createIdentitySchemaCreator)(RAr.SchemaType.ENUM,(n,{allowUnrecognizedEnumValues:o,breadcrumbsPrefix:i=[]}={})=>typeof n!="string"?{ok:!1,errors:[{path:i,message:(0,kSt.getErrorMessageForIncorrectType)(n,"string")}]}:!e.has(n)&&!o?{ok:!1,errors:[{path:i,message:(0,kSt.getErrorMessageForIncorrectType)(n,"enum")}]}:{ok:!0,value:n})()}dte.enum_=NAr});var yOe=v(fte=>{"use strict";Object.defineProperty(fte,"__esModule",{value:!0});fte.enum_=void 0;var DAr=$St();Object.defineProperty(fte,"enum_",{enumerable:!0,get:function(){return DAr.enum_}})});var bOe=v(mA=>{"use strict";Object.defineProperty(mA,"__esModule",{value:!0});mA.getMemoizedSchema=mA.constructLazyBaseSchema=mA.lazy=void 0;var LAr=Lm();function FAr(t){let e=BSt(t);return Object.assign(Obje Line truncated
`);o.enqueue(s)}catch(i){o.error(i)}})},cancel(){var o;return bV(this,void 0,void 0,function*(){yield(o=r.return)===null||o===void 0?void 0:o.call(r)})}})}};Vs.StreamUtils=AOe;function Mxt(t,e){return vV(this,arguments,function*(){var n,o;if(!t.body)throw e?.abort(),new B$.CohereError({message:"Attempted to iterate over a response with no body"});let i=new IOe,a=new hA,s=MOe(t.body);try{for(var u=_V(EMr(s)),l;l=yield Ta(u.next()),!l.done;){let c=l.value;for(let d of a.decode(c)){let f=i.decode(d);f&&(yield yield Ta(f))}}}catch(c){n={error:c}}finally{try{l&&!l.done&&(o=u.return)&&(yield Ta(o.call(u)))}finally{if(n)throw n.error}}for(let c of a.flush()){let d=i.decode(c);d&&(yield yield Ta(d))}})}Vs._iterSSEMessages=Mxt;function EMr(t){return vV(this,arguments,function*(){var r,n;let o=new Uint8Array;try{for(var i=_V(t),a;a=yield Ta(i.next()),!a.done;){let s=a.value;if(s==null)continue;let u=s instanceof ArrayBuffer?new Uint8Array(s):typeof s=="string"?new TextEncoder().encode(s):s,l=new Uint8Array(o.length+u.length);l.set(o),l.set(u,o.length),o=l;let c;for(;(c=TMr(o))!==-1;)yield yield Ta(o.slice(0,c)),o=o.slice(c)}}catch(s){r={error:s}}finally{try{a&&!a.done&&(n=i.return)&&(yield Ta(n.call(i)))}finally{if(r)throw r.error}}o.length>0&&(yield yield Ta(o))})}function TMr(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 IOe=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]=IMr(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},hA=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 B$.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 B$.CohereError({message:`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`})}throw new B$.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}};Vs.LineDecoder=hA;hA.NEWLINE_CHARS=new Set([`
`,"\r"]);hA.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function AMr(t){let e=new hA,r=[];for(let n of t)r.push(...e.decode(n));return r}Vs._decodeChunks=AMr;function IMr(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}function MOe(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{next(){return bV(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 bV(this,void 0,void 0,function*(){let r=e.cancel();return e.releaseLock(),yield r,{done:!0,value:void 0}})},[Symbol.asyncIterator](){return this}}}Vs.readableStreamAsyncIterable=MOe});var ROe=v(Z_=>{"use strict";var MMr=Z_&&Z_.__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]}),RMr=Z_&&Z_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),jMr=Z_&&Z_.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&MMr(e,t,r);return RMr(e,t),e};Object.defineProperty(Z_,"__esModule",{value:!0});Z_.V2ChatStreamRequestCitationMode=void 0;var NMr=jMr(G());Z_.V2ChatStreamRequestCitationMode=NMr.serialization.enum_(["FAST","ACCURATE","OFF"])});var jOe=v(X_=>{"use strict";var DMr=X_&&X_.__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]}),LMr=X_&&X_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),FMr=X_&&X_.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&DMr(e,t,r);return LMr(e,t),e};Object.defineProperty(X_,"__esModule",{value:!0});X_.V2ChatRequestCitationMode=void 0;var kMr=FMr(G());X_.V2ChatRequestCitationMode=kMr.serialization.enum_(["FAST","ACCURATE","OFF"])});var q$=v(Q_=>{"use strict";var $Mr=Q_&&Q_.__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]}),BMr=Q_&&Q_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),qMr=Q_&&Q_.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&$Mr(e,t,r);return BMr(e,t),e};Object.defineProperty(Q_,"__esModule",{value:!0});Q_.TextContent=void 0;var jxt=qMr(G());Q_.TextContent=jxt.serialization.object({text:jxt.serialization.string()})});var NOe=v(ev=>{"use strict";var UMr=ev&&ev.__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]}),zMr=ev&&ev.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),HMr=ev&&ev.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&UMr(e,t,r);return zMr(e,t),e};Object.defineProperty(ev,"__esModule",{value:!0});ev.Content=void 0;var VMr=HMr(G()),WMr=q$();ev.Content=VMr.serialization.union("type",{text:WMr.TextContent}).transform({transform:t=>t,untransform:t=>t})});var LOe=v(tv=>{"use strict";var KMr=tv&&tv.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),GMr=tv&&tv.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),JMr=tv&&tv.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&KMr(e,t,r);return GMr(e,t),e};Object.defineProperty(tv,"__esModule",{value:!0});tv.UserMessageContent=void 0;var DOe=JMr(G()),YMr=NOe();tv.UserMessageContent=DOe.serialization.undiscriminatedUnion([DOe.serialization.string Line truncated
`)}}}}catch(S){a={error:S}}finally{try{h&&!h.done&&(s=m.return)&&(yield s.call(m))}finally{if(a)throw a.error}}for(let S of g.flush()){let x=(0,ni.parseAWSEvent)(S);if(x){let O=yield(0,ni.mapResponseFromBedrock)(c,u,x);y.push(JSON.stringify(O)+`
`)}}return y.end(),{ok:!0,body:y}}else{let b=yield p.body;return{ok:!0,body:yield(0,ni.mapResponseFromBedrock)(c,u,b)}}}catch(b){throw b}});ni.fetchOverride=B8r});var DO=v(vre=>{"use strict";Object.defineProperty(vre,"__esModule",{value:!0});vre.CohereEnvironment=void 0;vre.CohereEnvironment={Production:"https://api.cohere.com"}});var PA=v((XOt,wre)=>{(function(t,e,r){typeof wre<"u"&&wre.exports?wre.exports=r():typeof define=="function"&&define.amd?define(r):e[t]=r()})("urljoin",XOt,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 $Te=v($p=>{"use strict";var q8r=$p&&$p.__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]}),U8r=$p&&$p.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),HV=$p&&$p.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&q8r(e,t,r);return U8r(e,t),e},Sre=$p&&$p.__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())})},z8r=$p&&$p.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty($p,"__esModule",{value:!0});$p.V2=void 0;var QOt=HV(DO()),Fp=HV(G()),ms=HV(iO()),kp=HV(NO()),ePt=z8r(PA()),LO=HV(As()),kTe=class{constructor(e={}){this._options=e}chatStream(e,r){var n,o;return Sre(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:Fp.fetcher)({url:(0,ePt.default)((o=yield Fp.Supplier.get(this._options.environment))!==null&&o!==void 0?o:QOt.CohereEnvironment.Production,"v2/chat"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield Fp.Supplier.get(this._options.clientName))!=null?yield Fp.Supplier.get(this._options.clientName):void 0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.13.0","User-Agent":"cohere-ai/7.13.0","X-Fern-Runtime":Fp.RUNTIME.type,"X-Fern-Runtime-Version":Fp.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},kp.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(i.ok)return new Fp.Stream({stream:i.body,parse:a=>Sre(this,void 0,void 0,function*(){return kp.StreamedChatResponse2.parseOrThrow(a,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]})}),signal:r?.abortSignal,eventShape:{type:"sse",streamTerminator:"[DONE]"}});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new ms.BadRequestError(i.error.body);case 401:throw new ms.UnauthorizedError(i.error.body);case 403:throw new ms.ForbiddenError(i.error.body);case 404:throw new ms.NotFoundError(i.error.body);case 422:throw new ms.UnprocessableEntityError(kp.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new ms.TooManyRequestsError(kp.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new ms.ClientClosedRequestError(kp.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["respo Line truncated
`)}}return y.end(),{ok:!0,body:y}}else{let b=yield p.body;return{ok:!0,body:yield(0,ni.mapResponseFromBedrock)(c,u,b)}}}catch(b){throw b}});ni.fetchOverride=V8r});var LO=v(wre=>{"use strict";Object.defineProperty(wre,"__esModule",{value:!0});wre.CohereEnvironment=void 0;wre.CohereEnvironment={Production:"https://api.cohere.com"}});var PA=v((rPt,Sre)=>{(function(t,e,r){typeof Sre<"u"&&Sre.exports?Sre.exports=r():typeof define=="function"&&define.amd?define(r):e[t]=r()})("urljoin",rPt,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 UTe=v($p=>{"use strict";var W8r=$p&&$p.__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]}),K8r=$p&&$p.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),VV=$p&&$p.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&W8r(e,t,r);return K8r(e,t),e},xre=$p&&$p.__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())})},G8r=$p&&$p.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty($p,"__esModule",{value:!0});$p.V2=void 0;var nPt=VV(LO()),Fp=VV(G()),ms=VV(aO()),kp=VV(DO()),oPt=G8r(PA()),FO=VV(As()),qTe=class{constructor(e={}){this._options=e}chatStream(e,r){var n,o;return xre(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:Fp.fetcher)({url:(0,oPt.default)((o=yield Fp.Supplier.get(this._options.environment))!==null&&o!==void 0?o:nPt.CohereEnvironment.Production,"v2/chat"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield Fp.Supplier.get(this._options.clientName))!=null?yield Fp.Supplier.get(this._options.clientName):void 0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.13.0","User-Agent":"cohere-ai/7.13.0","X-Fern-Runtime":Fp.RUNTIME.type,"X-Fern-Runtime-Version":Fp.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},kp.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(i.ok)return new Fp.Stream({stream:i.body,parse:a=>xre(this,void 0,void 0,function*(){return kp.StreamedChatResponse2.parseOrThrow(a,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]})}),signal:r?.abortSignal,eventShape:{type:"sse",streamTerminator:"[DONE]"}});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new ms.BadRequestError(i.error.body);case 401:throw new ms.UnauthorizedError(i.error.body);case 403:throw new ms.ForbiddenError(i.error.body);case 404:throw new ms.NotFoundError(i.error.body);case 422:throw new ms.UnprocessableEntityError(kp.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new ms.TooManyRequestsError(kp.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new ms.ClientClosedRequestError(kp.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["respo Line truncated
`}});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new Ee.BadRequestError(i.error.body);case 401:throw new Ee.UnauthorizedError(i.error.body);case 403:throw new Ee.ForbiddenError(i.error.body);case 404:throw new Ee.NotFoundError(i.error.body);case 422:throw new Ee.UnprocessableEntityError(st.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new Ee.TooManyRequestsError(st.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new Ee.ClientClosedRequestError(st.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 500:throw new Ee.InternalServerError(i.error.body);case 501:throw new Ee.NotImplementedError(st.NotImplementedErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 503:throw new Ee.ServiceUnavailableError(i.error.body);case 504:throw new Ee.GatewayTimeoutError(st.GatewayTimeoutErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));default:throw new jr.CohereError({statusCode:i.error.statusCode,body:i.error.body})}switch(i.error.reason){case"non-json":throw new jr.CohereError({statusCode:i.error.statusCode,body:i.error.rawBody});case"timeout":throw new jr.CohereTimeoutError;case"unknown":throw new jr.CohereError({message:i.error.errorMessage})}})}chat(e,r){var n,o;return Vp(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:_t.fetcher)({url:(0,Hy.default)((o=yield _t.Supplier.get(this._options.environment))!==null&&o!==void 0?o:zy.CohereEnvironment.Production,"v1/chat"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield _t.Supplier.get(this._options.clientName))!=null?yield _t.Supplier.get(this._options.clientName):void 0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.13.0","User-Agent":"cohere-ai/7.13.0","X-Fern-Runtime":_t.RUNTIME.type,"X-Fern-Runtime-Version":_t.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},st.ChatRequest.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(i.ok)return st.NonStreamedChatResponse.parseOrThrow(i.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new Ee.BadRequestError(i.error.body);case 401:throw new Ee.UnauthorizedError(i.error.body);case 403:throw new Ee.ForbiddenError(i.error.body);case 404:throw new Ee.NotFoundError(i.error.body);case 422:throw new Ee.UnprocessableEntityError(st.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new Ee.TooManyRequestsError(st.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new Ee.ClientClosedRequestError(st.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 500:throw new Ee.InternalServerError(i.error.body);case 501:throw new Ee.NotImplementedError(st.NotImplementedErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 503:throw new Ee.ServiceUnavailableError(i.error.body);case 504:throw new Ee.GatewayTimeoutError(st.GatewayTimeoutErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));default:throw new jr.CohereError({statusCode:i.error.statusCode,body:i.error.body})}switch(i.error.reason){case"non-json":throw new jr.Co Line truncated
`}});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new Ee.BadRequestError(i.error.body);case 401:throw new Ee.UnauthorizedError(i.error.body);case 403:throw new Ee.ForbiddenError(i.error.body);case 404:throw new Ee.NotFoundError(i.error.body);case 422:throw new Ee.UnprocessableEntityError(st.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new Ee.TooManyRequestsError(st.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new Ee.ClientClosedRequestError(st.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 500:throw new Ee.InternalServerError(i.error.body);case 501:throw new Ee.NotImplementedError(st.NotImplementedErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 503:throw new Ee.ServiceUnavailableError(i.error.body);case 504:throw new Ee.GatewayTimeoutError(st.GatewayTimeoutErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));default:throw new jr.CohereError({statusCode:i.error.statusCode,body:i.error.body})}switch(i.error.reason){case"non-json":throw new jr.CohereError({statusCode:i.error.statusCode,body:i.error.rawBody});case"timeout":throw new jr.CohereTimeoutError;case"unknown":throw new jr.CohereError({message:i.error.errorMessage})}})}generate(e,r){var n,o;return Vp(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:_t.fetcher)({url:(0,Hy.default)((o=yield _t.Supplier.get(this._options.environment))!==null&&o!==void 0?o:zy.CohereEnvironment.Production,"v1/generate"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield _t.Supplier.get(this._options.clientName))!=null?yield _t.Supplier.get(this._options.clientName):void 0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.13.0","User-Agent":"cohere-ai/7.13.0","X-Fern-Runtime":_t.RUNTIME.type,"X-Fern-Runtime-Version":_t.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},st.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(i.ok)return st.Generation.parseOrThrow(i.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new Ee.BadRequestError(i.error.body);case 401:throw new Ee.UnauthorizedError(i.error.body);case 403:throw new Ee.ForbiddenError(i.error.body);case 404:throw new Ee.NotFoundError(i.error.body);case 422:throw new Ee.UnprocessableEntityError(st.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new Ee.TooManyRequestsError(st.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new Ee.ClientClosedRequestError(st.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 500:throw new Ee.InternalServerError(i.error.body);case 501:throw new Ee.NotImplementedError(st.NotImplementedErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 503:throw new Ee.ServiceUnavailableError(i.error.body);case 504:throw new Ee.GatewayTimeoutError(st.GatewayTimeoutErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));default:throw new jr.CohereError({statusCode:i.error.statusCode,body:i.error.body})}switch(i.error.reason){case"non-json":throw new jr.Coh Line truncated
`).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=yPt.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=tAe.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=tAe.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(...F6r(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)}},Rre=tAe;D6r(Rre,"specialTokenRegex",t=>new RegExp(t.map(e=>k6r(e)).join("|"),"g"))});var _Pt=w(()=>{bPt()});async function vPt(t){return t in jre||(jre[t]=$6r.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>new Rre(e)).catch(e=>{throw delete jre[t],e})),await jre[t]}async function wPt(t){return vPt(rAe(t))}var jre,$6r,nAe=w(()=>{_Pt();XL();jre={},$6r=new _m({})});function Wc(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 B6r,q6r,cB,dB,t8=w(()=>{gPt();W2();NE();XL();nAe();Df();B6r=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;q6r=()=>!1,cB=class extends xn{get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.verbose=e.verbose??q6r(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}},dB=class extends cB{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}constructor({callbacks:e,callbackManager:r,...n}){let{cache:o,...i}=n;super({callbacks:e??r,...i}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_encoding",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof o=="object"?this.cache=o:o?this.cache=Mre.global():this.cache=void 0,this.caller=new _m(n??{})}async getNumTokens(e){if(typeof e!="string")return 0;let r=Math.ceil(e.length/4);if(!this._encoding)try{this._encoding=await wPt("modelName"in this?B6r(this.modelName):"gpt2")}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}if(this._encoding)try{r=this._encoding.encode(e).length}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}return r}static _convertInputToPromptValue(e){return typeof e=="string"?new tF(e):Array.isArray(e)?new rF(e.map(fy)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...r}){let n={...this._identifyingParams(),...r,_type:this._llmType(),_model:this._modelType()};return Object.entries(n).filter(([a,s])=>s!==void 0).map(([a,s])=>`${a}:${JSON.stringify(s)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}}});var Wm=w(()=>{t8()});function Gs(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return e._def||Object.values(Wr.ZodFirstPartyTypeKind).includes(e.constructor?.name??"NOT_INCLUDED")?!0:typeof e.parse=="function"&&typeof e.parseAsync=="function"&&typeof e.safeParse=="function"&&typeof e.safeParseAsync=="function"}var fB=w(()=>{Td()});function oAe(t){return t!==void 0&&Array.isArray(t.lc_namespace)}function iAe(t){return t!==void 0&&xn.isRunnable(t)&&"lc_name"in t.constructor&&typ Line truncated
`+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&i.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function tEt(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 Bre(t){return!!t.finishReason&&u5r.includes(t.finishReason)}function IA(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];Bre(i)&&(o+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(o+=`: ${i.finishMessage}`))}return o}function o8(t){return this instanceof o8?(this.v=t,this):new o8(t)}function l5r(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 o8?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 c5r(t){let e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),r=p5r(e),[n,o]=r.tee();return{stream:f5r(n),response:d5r(o)}}async function d5r(t){let e=[],r=t.getReader();for(;;){let{done:n,value:o}=await r.read();if(n)return hAe(m5r(e));e.push(o)}}function f5r(t){return l5r(this,arguments,function*(){let r=t.getReader();for(;;){let{value:n,done:o}=yield o8(r.read());if(o)break;yield yield o8(hAe(n))}})}function p5r(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 ef("Failed to parse stream"));return}n.close();return}o+=a;let u=o.match(rEt),l;for(;u;){try{l=JSON.parse(u[1])}catch{n.error(new ef(`Error parsing JSON response: "${u[1]}"`));return}n.enqueue(l),o=o.substring(u[0].length),u=o.match(rEt)}return i()})}}})}function m5r(t){let e=t[t.length-1],r={promptFeedback:e?.promptFeedback};for(let n of t){if(n.candidates)for(let o of n.candidates){let i=o.index;if(r.candidates||(r.candidates=[]),r.candidates[i]||(r.candidates[i]={index:o.index}),r.candidates[i].citationMetadata=o.citationMetadata,r.candidates[i].groundingMetadata=o.groundingMetadata,r.candidates[i].finishReason=o.finishReason,r.candidates[i].finishMessage=o.finishMessage,r.candidates[i].safetyRatings=o.safetyRatings,o.content&&o.content.parts){r.candidates[i].content||(r.candidates[i].content={role:o.content.role||"user",parts:[]});let a={};for(let s of o.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[i].content.parts.push(a)}}n.usageMetadata&&(r.usageMetadata=n.usageMetadata)}return r}async function aEt(t,e,r,n){let o=await a8(e,Fj.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(r),n);return c5r(o)}async function sEt(t,e,r,n){let i=await(await a8(e,Fj.GENERATE_CONTENT,t,!1,JSON.stringify(r),n)).json();return{response:hAe(i)}}function uEt(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:"system",parts:t.parts}}}function i8(t){let e=[];if(typeof t=="string")e=[{text:t}];else for(let r of t)typeof r=="string"?e.push({text:r}):e.push(r);return h5r(e)}function h5r(t){let e={role:"user",parts:[]},r={role:"function",parts:[]},n=!1,o=!1;for(let i of t)"functionResponse"in i?(r.parts.push(i),o=!0):(e.parts.push(i),n=!0);if(n&&o)throw new ef("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");if(!n&&!o)throw new ef("No content is provided for sending chat message.");return n?e:r}function g5r(t,e){var r;let n={model:e?.model,generationConfig:e?.generationConfig,safetySettings:e?.safetySettings,tools:e?.tools,toolConfig:e?.toolConfig,systemInstruction:e?.systemInstruction,cachedContent:(r=e?.cachedContent)===null||r===void 0?void 0:r.name,contents:[]},o=t.generateContentRequest!=null;if(t.contents){if(o)throw new px("CountTokensRequest must have one of contents or generateContentRequest, not both.");n.contents=t.contents}else if(o)n=Object.assign(Object.assign({},n),t.geneLine truncated
`)===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 mx(t,e){if(!(this instanceof mx))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 jl(e.headers),this.url=e.url||"",this._initBody(t)}function CEt(t,e){return new Promise(function(r,n){var o=new Bj(t,e);if(o.signal&&o.signal.aborted)return n(new $j("Aborted","AbortError"));var i=new XMLHttpRequest;function a(){i.abort()}i.onload=function(){var l={statusText:i.statusText,headers:F5r(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 mx(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 $j("Aborted","AbortError"))},0)};function s(l){try{return l===""&&Gc.location.href?Gc.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&&(Zf.blob?i.responseType="blob":Zf.arrayBuffer&&(i.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof jl||Gc.Headers&&e.headers instanceof Gc.Headers)){var u=[];Object.getOwnPropertyNames(e.headers).forEach(function(l){u.push(hB(l)),i.setRequestHeader(l,wAe(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 Gc,Zf,_Et,wEt,N5r,k5r,$j,OEt=w(()=>{Gc=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof window<"u"&&window||{},Zf={searchParams:"URLSearchParams"in Gc,iterable:"Symbol"in Gc&&"iterator"in Symbol,blob:"FileReader"in Gc&&"Blob"in Gc&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in Gc,arrayBuffer:"ArrayBuffer"in Gc};Zf.arrayBuffer&&(_Et=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],wEt=ArrayBuffer.isView||function(t){return t&&_Et.indexOf(Object.prototype.toString.call(t))>-1});jl.prototype.append=function(t,e){t=hB(t),e=wAe(e);var r=this.map[t];this.map[t]=r?r+", "+e:e};jl.prototype.delete=function(t){delete this.map[hB(t)]};jl.prototype.get=function(t){return t=hB(t),this.has(t)?this.map[t]:null};jl.prototype.has=function(t){return this.map.hasOwnProperty(hB(t))};jl.prototype.set=function(t,e){this.map[hB(t)]=wAe(e)};jl.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)};jl.prototype.keys=function(){var t=[];return this.forEach(function(e,r){t.push(r)}),SAe(t)};jl.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),SAe(t)};jl.prototype.entries=function(){var t=[];return this.forEach(function(e,r){t.push([r,e])}),SAe(t)};Zf.iterable&&(jl.prototype[Symbol.iterator]=jl.prototype.entries);N5r=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];Bj.prototype.clone=function(){return new Bj(this,{body:this._bodyInit})};xEt.call(Bj.prototype);xEt.call(mx.prototype);mx.prototype.clone=function(){return new mx(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new jl(this.headers),url:this.url})};mx.error=function(){var t=new mx(null,{status:200,statusText:""});return t.ok=!1,t.status=0,t.type="error",t};k5r=[301,302,303,307,308];mx.redirect=function(t,e){if(k5r.indexOf(e)===-1)throw new RangeError("Invalid status code");return new mx(null,{status:e,headers:{location:t}})};$j=Gc.DOMException;try{new $j}catch{$j=function(e,r){this.message=e,this.name=r;var n=Error(e);this.stack=n.stack},$j.prototype=Object.create(Error.prototype),$j.prototype.constructor=$j}CEt.polyfill=!0;Gc.fetch||(Gc.fetch=CEt,Gc.Headers=jl,Gc.Request=Bj,Gc.Response=mx)});function U5r(){if(typeof window<"u"&&window.navigator){let t=navigator;return"userAgentData"in t&&t.userAgentData?.platform?`${t.userAgentData.platform.toLowerCase()} Browser/${navigator.useLine truncated
`}});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new Ee.BadRequestError(i.error.body);case 401:throw new Ee.UnauthorizedError(i.error.body);case 403:throw new Ee.ForbiddenError(i.error.body);case 404:throw new Ee.NotFoundError(i.error.body);case 422:throw new Ee.UnprocessableEntityError(st.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new Ee.TooManyRequestsError(st.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new Ee.ClientClosedRequestError(st.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 500:throw new Ee.InternalServerError(i.error.body);case 501:throw new Ee.NotImplementedError(st.NotImplementedErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 503:throw new Ee.ServiceUnavailableError(i.error.body);case 504:throw new Ee.GatewayTimeoutError(st.GatewayTimeoutErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));default:throw new jr.CohereError({statusCode:i.error.statusCode,body:i.error.body})}switch(i.error.reason){case"non-json":throw new jr.CohereError({statusCode:i.error.statusCode,body:i.error.rawBody});case"timeout":throw new jr.CohereTimeoutError;case"unknown":throw new jr.CohereError({message:i.error.errorMessage})}})}generate(e,r){var n,o;return Vp(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:_t.fetcher)({url:(0,Hy.default)((o=yield _t.Supplier.get(this._options.environment))!==null&&o!==void 0?o:zy.CohereEnvironment.Production,"v1/generate"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield _t.Supplier.get(this._options.clientName))!=null?yield _t.Supplier.get(this._options.clientName):void 0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.13.0","User-Agent":"cohere-ai/7.13.0","X-Fern-Runtime":_t.RUNTIME.type,"X-Fern-Runtime-Version":_t.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},st.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(i.ok)return st.Generation.parseOrThrow(i.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new Ee.BadRequestError(i.error.body);case 401:throw new Ee.UnauthorizedError(i.error.body);case 403:throw new Ee.ForbiddenError(i.error.body);case 404:throw new Ee.NotFoundError(i.error.body);case 422:throw new Ee.UnprocessableEntityError(st.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new Ee.TooManyRequestsError(st.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new Ee.ClientClosedRequestError(st.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 500:throw new Ee.InternalServerError(i.error.body);case 501:throw new Ee.NotImplementedError(st.NotImplementedErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 503:throw new Ee.ServiceUnavailableError(i.error.body);case 504:throw new Ee.GatewayTimeoutError(st.GatewayTimeoutErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));default:throw new jr.CohereError({statusCode:i.error.statusCode,body:i.error.body})}switch(i.error.reason){case"non-json":throw new jr.Coh Line truncated
`).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=wPt.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=oAe.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=oAe.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(...U6r(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)}},jre=oAe;B6r(jre,"specialTokenRegex",t=>new RegExp(t.map(e=>z6r(e)).join("|"),"g"))});var xPt=w(()=>{SPt()});async function CPt(t){return t in Nre||(Nre[t]=H6r.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>new jre(e)).catch(e=>{throw delete Nre[t],e})),await Nre[t]}async function OPt(t){return CPt(iAe(t))}var Nre,H6r,aAe=w(()=>{xPt();QL();Nre={},H6r=new _m({})});function Wc(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 V6r,W6r,dB,fB,r8=w(()=>{vPt();K2();NE();QL();aAe();Df();V6r=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;W6r=()=>!1,dB=class extends Cn{get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.verbose=e.verbose??W6r(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}},fB=class extends dB{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}constructor({callbacks:e,callbackManager:r,...n}){let{cache:o,...i}=n;super({callbacks:e??r,...i}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_encoding",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof o=="object"?this.cache=o:o?this.cache=Rre.global():this.cache=void 0,this.caller=new _m(n??{})}async getNumTokens(e){if(typeof e!="string")return 0;let r=Math.ceil(e.length/4);if(!this._encoding)try{this._encoding=await OPt("modelName"in this?V6r(this.modelName):"gpt2")}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}if(this._encoding)try{r=this._encoding.encode(e).length}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}return r}static _convertInputToPromptValue(e){return typeof e=="string"?new rF(e):Array.isArray(e)?new nF(e.map(fy)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...r}){let n={...this._identifyingParams(),...r,_type:this._llmType(),_model:this._modelType()};return Object.entries(n).filter(([a,s])=>s!==void 0).map(([a,s])=>`${a}:${JSON.stringify(s)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}}});var Wm=w(()=>{r8()});function Gs(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return e._def||Object.values(Wr.ZodFirstPartyTypeKind).includes(e.constructor?.name??"NOT_INCLUDED")?!0:typeof e.parse=="function"&&typeof e.parseAsync=="function"&&typeof e.safeParse=="function"&&typeof e.safeParseAsync=="function"}var pB=w(()=>{Td()});function sAe(t){return t!==void 0&&Array.isArray(t.lc_namespace)}function uAe(t){return t!==void 0&&Cn.isRunnable(t)&&"lc_name"in t.constructor&&typ Line truncated
`+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&i.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function iEt(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 qre(t){return!!t.finishReason&&p5r.includes(t.finishReason)}function IA(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];qre(i)&&(o+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(o+=`: ${i.finishMessage}`))}return o}function i8(t){return this instanceof i8?(this.v=t,this):new i8(t)}function m5r(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 i8?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 h5r(t){let e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),r=b5r(e),[n,o]=r.tee();return{stream:y5r(n),response:g5r(o)}}async function g5r(t){let e=[],r=t.getReader();for(;;){let{done:n,value:o}=await r.read();if(n)return bAe(_5r(e));e.push(o)}}function y5r(t){return m5r(this,arguments,function*(){let r=t.getReader();for(;;){let{value:n,done:o}=yield i8(r.read());if(o)break;yield yield i8(bAe(n))}})}function b5r(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 ef("Failed to parse stream"));return}n.close();return}o+=a;let u=o.match(aEt),l;for(;u;){try{l=JSON.parse(u[1])}catch{n.error(new ef(`Error parsing JSON response: "${u[1]}"`));return}n.enqueue(l),o=o.substring(u[0].length),u=o.match(aEt)}return i()})}}})}function _5r(t){let e=t[t.length-1],r={promptFeedback:e?.promptFeedback};for(let n of t){if(n.candidates)for(let o of n.candidates){let i=o.index;if(r.candidates||(r.candidates=[]),r.candidates[i]||(r.candidates[i]={index:o.index}),r.candidates[i].citationMetadata=o.citationMetadata,r.candidates[i].groundingMetadata=o.groundingMetadata,r.candidates[i].finishReason=o.finishReason,r.candidates[i].finishMessage=o.finishMessage,r.candidates[i].safetyRatings=o.safetyRatings,o.content&&o.content.parts){r.candidates[i].content||(r.candidates[i].content={role:o.content.role||"user",parts:[]});let a={};for(let s of o.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[i].content.parts.push(a)}}n.usageMetadata&&(r.usageMetadata=n.usageMetadata)}return r}async function cEt(t,e,r,n){let o=await s8(e,kj.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(r),n);return h5r(o)}async function dEt(t,e,r,n){let i=await(await s8(e,kj.GENERATE_CONTENT,t,!1,JSON.stringify(r),n)).json();return{response:bAe(i)}}function fEt(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:"system",parts:t.parts}}}function a8(t){let e=[];if(typeof t=="string")e=[{text:t}];else for(let r of t)typeof r=="string"?e.push({text:r}):e.push(r);return v5r(e)}function v5r(t){let e={role:"user",parts:[]},r={role:"function",parts:[]},n=!1,o=!1;for(let i of t)"functionResponse"in i?(r.parts.push(i),o=!0):(e.parts.push(i),n=!0);if(n&&o)throw new ef("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");if(!n&&!o)throw new ef("No content is provided for sending chat message.");return n?e:r}function w5r(t,e){var r;let n={model:e?.model,generationConfig:e?.generationConfig,safetySettings:e?.safetySettings,tools:e?.tools,toolConfig:e?.toolConfig,systemInstruction:e?.systemInstruction,cachedContent:(r=e?.cachedContent)===null||r===void 0?void 0:r.name,contents:[]},o=t.generateContentRequest!=null;if(t.contents){if(o)throw new px("CountTokensRequest must have one of contents or generateContentRequest, not both.");n.contents=t.contents}else if(o)n=Object.assign(Object.assign({},n),t.geneLine truncated
`)===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 mx(t,e){if(!(this instanceof mx))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 jl(e.headers),this.url=e.url||"",this._initBody(t)}function TEt(t,e){return new Promise(function(r,n){var o=new qj(t,e);if(o.signal&&o.signal.aborted)return n(new Bj("Aborted","AbortError"));var i=new XMLHttpRequest;function a(){i.abort()}i.onload=function(){var l={statusText:i.statusText,headers:U5r(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 mx(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 Bj("Aborted","AbortError"))},0)};function s(l){try{return l===""&&Gc.location.href?Gc.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&&(Zf.blob?i.responseType="blob":Zf.arrayBuffer&&(i.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof jl||Gc.Headers&&e.headers instanceof Gc.Headers)){var u=[];Object.getOwnPropertyNames(e.headers).forEach(function(l){u.push(gB(l)),i.setRequestHeader(l,CAe(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 Gc,Zf,xEt,OEt,$5r,z5r,Bj,AEt=w(()=>{Gc=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof window<"u"&&window||{},Zf={searchParams:"URLSearchParams"in Gc,iterable:"Symbol"in Gc&&"iterator"in Symbol,blob:"FileReader"in Gc&&"Blob"in Gc&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in Gc,arrayBuffer:"ArrayBuffer"in Gc};Zf.arrayBuffer&&(xEt=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],OEt=ArrayBuffer.isView||function(t){return t&&xEt.indexOf(Object.prototype.toString.call(t))>-1});jl.prototype.append=function(t,e){t=gB(t),e=CAe(e);var r=this.map[t];this.map[t]=r?r+", "+e:e};jl.prototype.delete=function(t){delete this.map[gB(t)]};jl.prototype.get=function(t){return t=gB(t),this.has(t)?this.map[t]:null};jl.prototype.has=function(t){return this.map.hasOwnProperty(gB(t))};jl.prototype.set=function(t,e){this.map[gB(t)]=CAe(e)};jl.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)};jl.prototype.keys=function(){var t=[];return this.forEach(function(e,r){t.push(r)}),OAe(t)};jl.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),OAe(t)};jl.prototype.entries=function(){var t=[];return this.forEach(function(e,r){t.push([r,e])}),OAe(t)};Zf.iterable&&(jl.prototype[Symbol.iterator]=jl.prototype.entries);$5r=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];qj.prototype.clone=function(){return new qj(this,{body:this._bodyInit})};EEt.call(qj.prototype);EEt.call(mx.prototype);mx.prototype.clone=function(){return new mx(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new jl(this.headers),url:this.url})};mx.error=function(){var t=new mx(null,{status:200,statusText:""});return t.ok=!1,t.status=0,t.type="error",t};z5r=[301,302,303,307,308];mx.redirect=function(t,e){if(z5r.indexOf(e)===-1)throw new RangeError("Invalid status code");return new mx(null,{status:e,headers:{location:t}})};Bj=Gc.DOMException;try{new Bj}catch{Bj=function(e,r){this.message=e,this.name=r;var n=Error(e);this.stack=n.stack},Bj.prototype=Object.create(Error.prototype),Bj.prototype.constructor=Bj}TEt.polyfill=!0;Gc.fetch||(Gc.fetch=TEt,Gc.Headers=jl,Gc.Request=qj,Gc.Response=mx)});function K5r(){if(typeof window<"u"&&window.navigator){let t=navigator;return"userAgentData"in t&&t.userAgentData?.platform?`${t.userAgentData.platform.toLowerCase()} Browser/${navigator.useLine truncated
`);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)}},W5r=t=>{if(!t)return TEt;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=EEt);let o=`${r.protocol}//${r.hostname}:${n}${r.pathname}`;return o.endsWith("/")&&(o=o.slice(0,-1)),o},K5r=Object.defineProperty,G5r=(t,e,r)=>e in t?K5r(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,CAe=(t,e,r)=>(G5r(t,typeof e!="symbol"?e+"":e,r),r),yB=class{constructor(e){CAe(this,"config"),CAe(this,"fetch"),CAe(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e?.headers},e?.proxy||(this.config.host=W5r(e?.host??TEt)),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 gB(this.fetch,n,r,{signal:i.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");let s=V5r(a.body),u=new PAe(i,s,()=>{let l=this.ongoingStreamedRequests.indexOf(u);l>-1&&this.ongoingStreamedRequests.splice(l,1)});return this.ongoingStreamedRequests.push(u),u}return await(await gB(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 H5r(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await gB(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await PEt(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await gB(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await gB(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await gB(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await PEt(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}},AAo=new yB});var AEt=w(()=>{Wb()});function IEt(t,e=0){return(Jc[t[e+0]]+Jc[t[e+1]]+Jc[t[e+2]]+Jc[t[e+3]]+"-"+Jc[t[e+4]]+Jc[t[e+5]]+"-"+Jc[t[e+6]]+Jc[t[e+7]]+"-"+Jc[t[e+8]]+Jc[t[e+9]]+"-"+Jc[t[e+10]]+Jc[t[e+11]]+Jc[t[e+12]]+Jc[t[e+13]]+Jc[t[e+14]]+Jc[t[e+15]]).toLowerCase()}var Jc,Gre,MEt=w(()=>{Jc=[];for(Gre=0;Gre<256;++Gre)Jc.push((Gre+256).toString(16).slice(1))});function AAe(){if(!Jre&&(Jre=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Jre))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Jre(J5r)}var Jre,J5r,REt=w(()=>{J5r=new Uint8Array(16)});var Y5r,IAe,jEt=w(()=>{Y5r=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),IAe={randomUUID:Y5r}});function Z5r(t,e,r){if(IAe.randomUUID&&!e&&!t)return IAe.randomUUID();t=t||{};var n=t.random||(t.rng||AAe)();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 IEt(n)}var MAe,NEt=w(()=>{jEt();REt();MEt();MAe=Z5r});var DEt=w(()=>{NEt()});function RAe(t,e){return new dr({content:t.content??"",tool_call_chunks:t.tool_calls?.map(r=>({name:r.function.name,args:JSON.stringify(r.function.arguments),type:"tool_call_chunk",index:0,id:MAe()})),response_metadata:e?.responseMetadata,usage_metadata:e?.usageMetadata})}function LEt(t){let e=t.match(/^data:.*?;base64,(.*)$/);return e?e[1]:""}function X5r(t){if(typeof t.content=="string")return[{role:"assistant",content:t.content}];let r=t.content.filter(o=>o.type==="text"&&typeof o.text=="string").map(o=>({role:"assistant",content:o.text})),n;if(t.content.find(o=>o.type==="tool_use")&&t.tool_calls?.length){let o=t.tool_calls?.map(i=>({id:i.id,type:"function",function:{name:i.name,arguments:i.args}}));o&&(n={role:"assistant",tool_calls:o,content:""})}else if(t.content.find(o=>o.type==="tool_use")&&!t.tool_calls?.length)throw new Error("'tool_use' content type is not supported w Line truncated
`):[]}};Gm=new WeakMap;Hj.NEWLINE_CHARS=new Set([`
`,"\r"]);Hj.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function KAe(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 uTt=w(()=>{});async function*yWr(t,e){if(!t.body)throw e.abort(),new vt("Attempted to iterate over a response with no body");let r=new GAe,n=new Hj,o=KAe(t.body);for await(let i of bWr(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*bWr(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=aTt(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function _Wr(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var yx,GAe,ine=w(()=>{l8();Kp();sTt();uTt();Vn();Kp();yx=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 yWr(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 Ys(void 0,s.error,void 0,JAe(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 Ys(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 Hj,s=KAe(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 qAe({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?.()}})}};GAe=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]=_Wr(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function XAe(t,e,r){if(t=await t,cTt(t))return t;if(lTt(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=c8(o)?[await o.arrayBuffer()]:[o];return new ene(i,e,r)}let n=await wWr(t);if(e||(e=xWr(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new ene(n,e,r)}async function wWr(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(c8(t))e.push(await t.arrayBuffer());else if(CWr(t))for await(let r of t)e.push(r);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${SWr(t)}`);return e}function SWr(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function xWr(t){return YAe(t.name)||YAe(t.filename)||YAe(t.path)?.split(/[\\/]/).pop()}var lTt,cTt,c8,vWr,YAe,CWr,QAe,fg,dTt,ZAe,ane=w(()=>{l8();l8();lTt=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",cTt=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&c8(t),c8=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",vWr=t=>cTt(t)||lTt(t)||HAe(t);YAe=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},CWr=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",QAe=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody",fg=async t=>{let e=await dTt(t.body);return UAe(e,t)},dTt=async t=>{let e=new BAe;return await Promise.all(Object.entries(t||{}).map(([r,n])=>ZAe(e,r,n))),e},ZAe=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(vWr(r)){let n=await XAe(r);t.append(e,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>ZAe(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>ZAe(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 yTt(t){let{response:e}=t;if(t.options.stream)return qO("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):yx.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 qO("response",e.status,e.url,e.headers,a),bTt(a,e)}let i=await e.text();return qO("response",e.status,e.url,e.headers,i),i}function bTt(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 IWr(){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 _Tt(t){if(!t)return!0;for(let e in t)return!1;return!0}function vTt(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function hTt(t,e){for(let r in e){if(!vTt(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 qO(t,...e){if(typeof process<"u"&&process?.env?.DEBUG==="true"){let r=e.map(n=>{if(!n)return n;if(n.headers){let i={...n,headers:{...n.headers}};for(let a in n.headers)gTt.has(a.toLowerCase())&&(i.headers[a]="REDACTED");return i}let o=null;for(let i in n)gTt.has(i.toLowerCase())&&(o??(o={...n}),o[i]="REDACTED");return o??n});console.log(`OpenAI:DEBUG:${t}`,...r)}}function TB(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var PWr,EWr,sne,lne,cne,d8,tIe,JAe,TWr,Jr,AWr,fTt,pTt,mTt,MWr,RWr,jWr,NWr,UO,eIe,nne,MA,gTt,DWr,wTt,LWr,une,STt,Vn=w(()=>{QEt();ine();Kp();l8();ane();ane();PWr=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 Line truncated
\r `.includes(t[n]);)n++};return a()},CIe=t=>VWr(t,oc.ALL^oc.NUM)});function KWr(t,e){let{id:r,choices:n,created:o,model:i,system_fingerprint:a,...s}=t,u={...s,id:r,choices:n.map(({message:l,finish_reason:c,index:d,logprobs:f,...p})=>{if(!c)throw new vt(`missing finish_reason for choice ${d}`);let{content:m=null,function_call:h,tool_calls:b,...g}=l,y=l.role;if(!y)throw new vt(`missing role for choice ${d}`);if(h){let{arguments:S,name:x}=h;if(S==null)throw new vt(`missing function_call.arguments for choice ${d}`);if(!x)throw new vt(`missing function_call.name for choice ${d}`);return{...p,message:{content:m,function_call:{arguments:S,name:x},role:y,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}return b?{...p,index:d,finish_reason:c,logprobs:f,message:{...g,role:y,content:m,refusal:l.refusal??null,tool_calls:b.map((S,x)=>{let{function:O,type:P,id:E,...A}=S,{arguments:I,name:R,...N}=O||{};if(E==null)throw new vt(`missing choices[${d}].tool_calls[${x}].id
${wne(t)}`);if(P==null)throw new vt(`missing choices[${d}].tool_calls[${x}].type
${wne(t)}`);if(R==null)throw new vt(`missing choices[${d}].tool_calls[${x}].function.name
${wne(t)}`);if(I==null)throw new vt(`missing choices[${d}].tool_calls[${x}].function.arguments
${wne(t)}`);return{...A,id:E,type:P,function:{...N,name:R,arguments:I}}})}}:{...p,message:{...g,content:m,role:y,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}),created:o,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};return ATt(u,e)}function wne(t){return JSON.stringify(t)}var FB,Ti,Dl,VO,kB,kA,OIe,_ne,PIe,EIe,TIe,vne,AIe,LTt,$B,IIe=w(()=>{Kp();wIe();ine();DB();DTt();FB=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},Ti=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)},$B=class t extends LB{constructor(e){super(),Dl.add(this),VO.set(this,void 0),kB.set(this,void 0),kA.set(this,void 0),FB(this,VO,e,"f"),FB(this,kB,[],"f")}get currentChatCompletionSnapshot(){return Ti(this,kA,"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())),Ti(this,Dl,"m",OIe).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)Ti(this,Dl,"m",PIe).call(this,a);if(i.controller.signal?.aborted)throw new Li;return this._addChatCompletion(Ti(this,Dl,"m",vne).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),Ti(this,Dl,"m",OIe).call(this),this._connected();let o=yx.fromReadableStream(e,this.controller),i;for await(let a of o)i&&i!==a.id&&this._addChatCompletion(Ti(this,Dl,"m",vne).call(this)),Ti(this,Dl,"m",PIe).call(this,a),i=a.id;if(o.controller.signal?.aborted)throw new Li;return this._addChatCompletion(Ti(this,Dl,"m",vne).call(this))}[(VO=new WeakMap,kB=new WeakMap,kA=new WeakMap,Dl=new WeakSet,OIe=function(){this.ended||FB(this,kA,void 0,"f")},_ne=function(r){let n=Ti(this,kB,"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},Ti(this,kB,"f")[r.index]=n,n)},PIe=function(r){if(this.ended)return;let n=Ti(this,Dl,"m",LTt).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=Ti(this,Dl,"m",_ne).call(this,i);i.finish_reason&&(Ti(this,Dl,"m",TIe).call(this,i),a.current_tool_call_index!=null&&Ti(this,Dl,"m",EIe).call(this,i,a.current_tool_call_index));for(let s of o.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(Ti(this,Dl,"m",TIe).call(this,i),a.current_tool_call_index!=null&&Ti(this,Dl,"m",EIe).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))}}},EIe=function(r,n){if(Ti(this,Dl,"m",_ne).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=Ti(this,VO,"f")?.tools?.find(s=>s.type==="function"&&s.function.name===i.function.name);this._emit("tool_calls.function.arguments.done",{name:i.function.name,index:n,arguments:i.function.arguments,parsed_arguments:Kj(a)?a.$parseRaw(i.function.arguments):a?.function.strict?JSON.parse(i Line truncated
`).filter(i=>i!==""))try{yield JSON.parse(o)}catch{console.warn("invalid json: ",o)}},Z5r=t=>{if(!t)return REt;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=MEt);let o=`${r.protocol}//${r.hostname}:${n}${r.pathname}`;return o.endsWith("/")&&(o=o.slice(0,-1)),o},X5r=Object.defineProperty,Q5r=(t,e,r)=>e in t?X5r(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,EAe=(t,e,r)=>(Q5r(t,typeof e!="symbol"?e+"":e,r),r),bB=class{constructor(e){EAe(this,"config"),EAe(this,"fetch"),EAe(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e?.headers},e?.proxy||(this.config.host=Z5r(e?.host??REt)),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 yB(this.fetch,n,r,{signal:i.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");let s=Y5r(a.body),u=new AAe(i,s,()=>{let l=this.ongoingStreamedRequests.indexOf(u);l>-1&&this.ongoingStreamedRequests.splice(l,1)});return this.ongoingStreamedRequests.push(u),u}return await(await yB(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 J5r(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await yB(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await IEt(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await yB(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await yB(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await yB(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await IEt(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}},NAo=new bB});var jEt=w(()=>{Wb()});function NEt(t,e=0){return(Jc[t[e+0]]+Jc[t[e+1]]+Jc[t[e+2]]+Jc[t[e+3]]+"-"+Jc[t[e+4]]+Jc[t[e+5]]+"-"+Jc[t[e+6]]+Jc[t[e+7]]+"-"+Jc[t[e+8]]+Jc[t[e+9]]+"-"+Jc[t[e+10]]+Jc[t[e+11]]+Jc[t[e+12]]+Jc[t[e+13]]+Jc[t[e+14]]+Jc[t[e+15]]).toLowerCase()}var Jc,Jre,DEt=w(()=>{Jc=[];for(Jre=0;Jre<256;++Jre)Jc.push((Jre+256).toString(16).slice(1))});function RAe(){if(!Yre&&(Yre=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Yre))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Yre(eWr)}var Yre,eWr,LEt=w(()=>{eWr=new Uint8Array(16)});var tWr,jAe,FEt=w(()=>{tWr=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),jAe={randomUUID:tWr}});function rWr(t,e,r){if(jAe.randomUUID&&!e&&!t)return jAe.randomUUID();t=t||{};var n=t.random||(t.rng||RAe)();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 NEt(n)}var NAe,kEt=w(()=>{FEt();LEt();DEt();NAe=rWr});var $Et=w(()=>{kEt()});function DAe(t,e){return new dr({content:t.content??"",tool_call_chunks:t.tool_calls?.map(r=>({name:r.function.name,args:JSON.stringify(r.function.arguments),type:"tool_call_chunk",index:0,id:NAe()})),response_metadata:e?.responseMetadata,usage_metadata:e?.usageMetadata})}function BEt(t){let e=t.match(/^data:.*?;base64,(.*)$/);return e?e[1]:""}function nWr(t){if(typeof t.content=="string")return[{role:"assistant",content:t.content}];let r=t.content.filter(o=>o.type==="text"&&typeof o.text=="string").map(o=>({role:"assistant",content:o.text})),n;if(t.content.find(o=>o.type==="tool_use")&&t.tool_calls?.length){let o=t.tool_calls?.map(i=>({id:i.id,type:"function",function:{name:i.name,arguments:i.args}}));o&&(n={role:"assistant",tool_calls:o,content:""})}else if(t.content.find(o=>o.type==="tool_use")&&!t.tool_calls?.length)throw new Error("'tool_use' content type is not supported w Line truncated
`):[]}};Gm=new WeakMap;Vj.NEWLINE_CHARS=new Set([`
`,"\r"]);Vj.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function YAe(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 fTt=w(()=>{});async function*SWr(t,e){if(!t.body)throw e.abort(),new vt("Attempted to iterate over a response with no body");let r=new ZAe,n=new Vj,o=YAe(t.body);for await(let i of xWr(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*xWr(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=cTt(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function CWr(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var yx,ZAe,ane=w(()=>{c8();Kp();dTt();fTt();Vn();Kp();yx=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 SWr(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 Ys(void 0,s.error,void 0,XAe(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 Ys(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 Vj,s=YAe(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 HAe({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?.()}})}};ZAe=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]=CWr(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function tIe(t,e,r){if(t=await t,mTt(t))return t;if(pTt(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=d8(o)?[await o.arrayBuffer()]:[o];return new tne(i,e,r)}let n=await PWr(t);if(e||(e=TWr(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new tne(n,e,r)}async function PWr(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(d8(t))e.push(await t.arrayBuffer());else if(AWr(t))for await(let r of t)e.push(r);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${EWr(t)}`);return e}function EWr(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function TWr(t){return QAe(t.name)||QAe(t.filename)||QAe(t.path)?.split(/[\\/]/).pop()}var pTt,mTt,d8,OWr,QAe,AWr,rIe,fg,hTt,eIe,sne=w(()=>{c8();c8();pTt=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",mTt=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&d8(t),d8=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",OWr=t=>mTt(t)||pTt(t)||KAe(t);QAe=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},AWr=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",rIe=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody",fg=async t=>{let e=await hTt(t.body);return VAe(e,t)},hTt=async t=>{let e=new zAe;return await Promise.all(Object.entries(t||{}).map(([r,n])=>eIe(e,r,n))),e},eIe=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(OWr(r)){let n=await tIe(r);t.append(e,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>eIe(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>eIe(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 wTt(t){let{response:e}=t;if(t.options.stream)return UO("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):yx.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 UO("response",e.status,e.url,e.headers,a),STt(a,e)}let i=await e.text();return UO("response",e.status,e.url,e.headers,i),i}function STt(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 DWr(){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 xTt(t){if(!t)return!0;for(let e in t)return!1;return!0}function CTt(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function _Tt(t,e){for(let r in e){if(!CTt(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 UO(t,...e){if(typeof process<"u"&&process?.env?.DEBUG==="true"){let r=e.map(n=>{if(!n)return n;if(n.headers){let i={...n,headers:{...n.headers}};for(let a in n.headers)vTt.has(a.toLowerCase())&&(i.headers[a]="REDACTED");return i}let o=null;for(let i in n)vTt.has(i.toLowerCase())&&(o??(o={...n}),o[i]="REDACTED");return o??n});console.log(`OpenAI:DEBUG:${t}`,...r)}}function AB(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var MWr,RWr,une,cne,dne,f8,oIe,XAe,jWr,Jr,NWr,gTt,yTt,bTt,LWr,FWr,kWr,$Wr,zO,nIe,one,MA,vTt,BWr,OTt,qWr,lne,PTt,Vn=w(()=>{nTt();ane();Kp();c8();sne();sne();MWr=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 Line truncated
\r `.includes(t[n]);)n++};return a()},EIe=t=>YWr(t,oc.ALL^oc.NUM)});function XWr(t,e){let{id:r,choices:n,created:o,model:i,system_fingerprint:a,...s}=t,u={...s,id:r,choices:n.map(({message:l,finish_reason:c,index:d,logprobs:f,...p})=>{if(!c)throw new vt(`missing finish_reason for choice ${d}`);let{content:m=null,function_call:h,tool_calls:b,...g}=l,y=l.role;if(!y)throw new vt(`missing role for choice ${d}`);if(h){let{arguments:S,name:x}=h;if(S==null)throw new vt(`missing function_call.arguments for choice ${d}`);if(!x)throw new vt(`missing function_call.name for choice ${d}`);return{...p,message:{content:m,function_call:{arguments:S,name:x},role:y,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}return b?{...p,index:d,finish_reason:c,logprobs:f,message:{...g,role:y,content:m,refusal:l.refusal??null,tool_calls:b.map((S,x)=>{let{function:O,type:P,id:E,...A}=S,{arguments:I,name:R,...N}=O||{};if(E==null)throw new vt(`missing choices[${d}].tool_calls[${x}].id
${Sne(t)}`);if(P==null)throw new vt(`missing choices[${d}].tool_calls[${x}].type
${Sne(t)}`);if(R==null)throw new vt(`missing choices[${d}].tool_calls[${x}].function.name
${Sne(t)}`);if(I==null)throw new vt(`missing choices[${d}].tool_calls[${x}].function.arguments
${Sne(t)}`);return{...A,id:E,type:P,function:{...N,name:R,arguments:I}}})}}:{...p,message:{...g,content:m,role:y,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}),created:o,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};return jTt(u,e)}function Sne(t){return JSON.stringify(t)}var kB,Ti,Dl,WO,$B,kA,TIe,vne,AIe,IIe,MIe,wne,RIe,BTt,BB,jIe=w(()=>{Kp();CIe();ane();LB();$Tt();kB=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},Ti=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)},BB=class t extends FB{constructor(e){super(),Dl.add(this),WO.set(this,void 0),$B.set(this,void 0),kA.set(this,void 0),kB(this,WO,e,"f"),kB(this,$B,[],"f")}get currentChatCompletionSnapshot(){return Ti(this,kA,"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())),Ti(this,Dl,"m",TIe).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)Ti(this,Dl,"m",AIe).call(this,a);if(i.controller.signal?.aborted)throw new Li;return this._addChatCompletion(Ti(this,Dl,"m",wne).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),Ti(this,Dl,"m",TIe).call(this),this._connected();let o=yx.fromReadableStream(e,this.controller),i;for await(let a of o)i&&i!==a.id&&this._addChatCompletion(Ti(this,Dl,"m",wne).call(this)),Ti(this,Dl,"m",AIe).call(this,a),i=a.id;if(o.controller.signal?.aborted)throw new Li;return this._addChatCompletion(Ti(this,Dl,"m",wne).call(this))}[(WO=new WeakMap,$B=new WeakMap,kA=new WeakMap,Dl=new WeakSet,TIe=function(){this.ended||kB(this,kA,void 0,"f")},vne=function(r){let n=Ti(this,$B,"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},Ti(this,$B,"f")[r.index]=n,n)},AIe=function(r){if(this.ended)return;let n=Ti(this,Dl,"m",BTt).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=Ti(this,Dl,"m",vne).call(this,i);i.finish_reason&&(Ti(this,Dl,"m",MIe).call(this,i),a.current_tool_call_index!=null&&Ti(this,Dl,"m",IIe).call(this,i,a.current_tool_call_index));for(let s of o.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(Ti(this,Dl,"m",MIe).call(this,i),a.current_tool_call_index!=null&&Ti(this,Dl,"m",IIe).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))}}},IIe=function(r,n){if(Ti(this,Dl,"m",vne).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=Ti(this,WO,"f")?.tools?.find(s=>s.type==="function"&&s.function.name===i.function.name);this._emit("tool_calls.function.arguments.done",{name:i.function.name,index:n,arguments:i.function.arguments,parsed_arguments:Gj(a)?a.$parseRaw(i.function.arguments):a?.function.strict?JSON.parse(i Line truncated
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,
@@ -291,36 +291,36 @@ 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 Xj(this),this.chat=new zO(this),this.embeddings=new Qj(this),this.files=new BA(this),this.images=new iN(this),this.audio=new _x(this),this.moderations=new sN(this),this.models=new UA(this),this.fineTuning=new Yy(this),this.vectorStores=new Zm(this),this.beta=new Jy(this),this.batches=new DA(this),this.uploads=new WA(this),this.responses=new VA(this),this.evals=new xx(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 kAe(e,{arrayFormat:"brackets"})}};nAt=Wt;Wt.OpenAI=nAt;Wt.DEFAULT_TIMEOUT=6e5;Wt.OpenAIError=vt;Wt.APIError=Ys;Wt.APIConnectionError=BO;Wt.APIConnectionTimeoutError=Xf;Wt.APIUserAbortError=Li;Wt.NotFoundError=wB;Wt.ConflictError=SB;Wt.RateLimitError=CB;Wt.BadRequestError=bB;Wt.AuthenticationError=_B;Wt.InternalServerError=OB;Wt.PermissionDeniedError=vB;Wt.UnprocessableEntityError=xB;Wt.toFile=XAe;Wt.fileFromPath=tne;Wt.Completions=Xj;Wt.Chat=zO;Wt.ChatCompletionsPage=NA;Wt.Embeddings=Qj;Wt.Files=BA;Wt.FileObjectsPage=rN;Wt.Images=iN;Wt.Audio=_x;Wt.Moderations=sN;Wt.Models=UA;Wt.ModelsPage=aN;Wt.FineTuning=Yy;Wt.VectorStores=Zm;Wt.VectorStoresPage=uN;Wt.VectorStoreSearchResponsesPage=lN;Wt.Beta=Jy;Wt.Batches=DA;Wt.BatchesPage=Vj;Wt.Uploads=WA;Wt.Responses=VA;Wt.Evals=xx;Wt.EvalListResponsesPage=tN;Rne=class extends Wt{constructor({baseURL:e=MA("OPENAI_BASE_URL"),apiKey:r=MA("AZURE_OPENAI_API_KEY"),apiVersion:n=MA("OPENAI_API_VERSION"),endpoint:o,deployment:i,azureADTokenProvider:a,dangerouslyAllowBrowser:s,...u}={}){if(!n)throw new vt("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof a=="function"&&(s=!0),!a&&!r)throw new vt("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(a&&r)throw new vt("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(r??(r=rAt),u.defaultQuery={...u.defaultQuery,"api-version":n},e){if(o)throw new vt("baseURL and endpoint are mutually exclusive")}else{if(o||(o=process.env.AZURE_OPENAI_ENDPOINT),!o)throw new vt("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${o}/openai`}super({apiKey:r,baseURL:e,...u,...s!==void 0?{dangerouslyAllowBrowser:s}:{}}),this.apiVersion="",this._azureADTokenProvider=a,this.apiVersion=n,this.deploymentName=i}buildRequest(e,r={}){if(v9r.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!TB(e.body))throw new Error("Expected request body to be an object");let n=this.deploymentName||e.body.model||e.__metadata?.model;n!==void 0&&!this.baseURL.includes("/deployments")&&(e.path=`/deployments/${n}${e.path}`)}return super.buildRequest(e,r)}async _getAzureADToken(){if(typeof this._azureADTokenProvider=="function"){let e=await this._azureADTokenProvider();if(!e||typeof e!="string")throw new vt(`Expected 'azureADTokenProvider' argument to return a string but it returned ${e}`);return e}}authHeaders(e){return{}}async prepareOptions(e){if(e.headers?.["api-key"])return super.prepareOptions(e);let r=await this._getAzureADToken();if(e.headers??(e.headers={}),r)e.headers.Authorization=`Bearer ${r}`;else if(this.apiKey!==rAt)e.headers["api-key"]=this.apiKey;else throw new vt("Unable to handle auth");return super.prepareOptions(e)}},v9r=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations"]),rAt="<Missing Key>"});function Jp(t,e){if(t.function===void 0)return;let r;if(e?.partial)try{r=WL(t.function.arguments??"{}")}catch{return}else try{r=JSON.parse(t.function.arguments)}catch(o){throw new vm([`Function "${t.function.name}" arguments:`,"",t.function.arguments,"","are not valid JSON.",`Error: ${o.message}`].join(`
`))}let n={name:t.function.name,args:r,type:"tool_call"};return e?.returnId&&(n.id=t.id),n}function Ox(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 Xm(t,e){return{name:t.function?.name,args:t.function?.arguments,id:t.id,error:e,type:"invalid_tool_call"}}var lMe,Zc,oAt=w(()=>{eF();hhe();$E();SR();lMe=class extends AR{static lc_name(){return"JsonOutputToolsParser"}constructor(e){super(e),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","openai_tools"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.returnId=e?.returnId??this.returnId}_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(Oi(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=>Jp(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}},Zc=class extends lMe{static lc_name(){return"JsonOutputKeyToolsParser"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","openai_tools"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"keyName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"returnSingle",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"zodSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){if(this.zodSchema===void 0)return e;let r=await this.zodSchema.safeParseAsync(e);if(r.success)return r.data;throw new vm(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(r.error.errors)}`,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 iAt=w(()=>{oAt()});var iq=w(()=>{iAt()});var sAt,aAt,uAt,jne=w(()=>{sAt=Symbol("Let zodToJsonSchema decide on which parser to use"),aAt={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},uAt=t=>typeof t=="string"?{...aAt,basePath:["#"],definitions:{},name:t}:{...aAt,basePath:["#"],definitions:{},...t}});function lAt(t){if(!t)return!0;for(let e in t)return!1;return!0}var O8,cMe=w(()=>{O8=t=>"_def"in t?t._def:t});var cAt,dMe=w(()=>{jne();cMe();cAt=t=>{let e=uAt(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[O8(o),{def:O8(o),path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function fMe(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function Wn(t,e,r,n,o){t[e]=r,fMe(t,e,n,o)}var JA=w(()=>{});function dAt(){return{}}var pMe=w(()=>{});function fAt(t,e){let r={type:"array"};return t.type?._def?.typeName!==de.ZodAny&&(r.items=pr(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&Wn(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&Wn(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(Wn(r,"minItems",t.exactLength.value,t.exactLength.message,e),Wn(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var mMe=w(()=>{Td();JA();Zs()});function pAt(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?Wn(r,"minimum",n.value,n.message,e Line truncated
`);super({baseURL:a.baseURL,timeout:a.timeout??6e5,httpAgent:a.httpAgent,maxRetries:a.maxRetries,fetch:a.fetch}),this.completions=new Qj(this),this.chat=new HO(this),this.embeddings=new eN(this),this.files=new BA(this),this.images=new aN(this),this.audio=new _x(this),this.moderations=new uN(this),this.models=new UA(this),this.fineTuning=new Yy(this),this.vectorStores=new Zm(this),this.beta=new Jy(this),this.batches=new DA(this),this.uploads=new WA(this),this.responses=new VA(this),this.evals=new xx(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 qAe(e,{arrayFormat:"brackets"})}};sAt=Wt;Wt.OpenAI=sAt;Wt.DEFAULT_TIMEOUT=6e5;Wt.OpenAIError=vt;Wt.APIError=Ys;Wt.APIConnectionError=qO;Wt.APIConnectionTimeoutError=Xf;Wt.APIUserAbortError=Li;Wt.NotFoundError=SB;Wt.ConflictError=xB;Wt.RateLimitError=OB;Wt.BadRequestError=_B;Wt.AuthenticationError=vB;Wt.InternalServerError=PB;Wt.PermissionDeniedError=wB;Wt.UnprocessableEntityError=CB;Wt.toFile=tIe;Wt.fileFromPath=rne;Wt.Completions=Qj;Wt.Chat=HO;Wt.ChatCompletionsPage=NA;Wt.Embeddings=eN;Wt.Files=BA;Wt.FileObjectsPage=nN;Wt.Images=aN;Wt.Audio=_x;Wt.Moderations=uN;Wt.Models=UA;Wt.ModelsPage=sN;Wt.FineTuning=Yy;Wt.VectorStores=Zm;Wt.VectorStoresPage=lN;Wt.VectorStoreSearchResponsesPage=cN;Wt.Beta=Jy;Wt.Batches=DA;Wt.BatchesPage=Wj;Wt.Uploads=WA;Wt.Responses=VA;Wt.Evals=xx;Wt.EvalListResponsesPage=rN;jne=class extends Wt{constructor({baseURL:e=MA("OPENAI_BASE_URL"),apiKey:r=MA("AZURE_OPENAI_API_KEY"),apiVersion:n=MA("OPENAI_API_VERSION"),endpoint:o,deployment:i,azureADTokenProvider:a,dangerouslyAllowBrowser:s,...u}={}){if(!n)throw new vt("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof a=="function"&&(s=!0),!a&&!r)throw new vt("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(a&&r)throw new vt("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(r??(r=aAt),u.defaultQuery={...u.defaultQuery,"api-version":n},e){if(o)throw new vt("baseURL and endpoint are mutually exclusive")}else{if(o||(o=process.env.AZURE_OPENAI_ENDPOINT),!o)throw new vt("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${o}/openai`}super({apiKey:r,baseURL:e,...u,...s!==void 0?{dangerouslyAllowBrowser:s}:{}}),this.apiVersion="",this._azureADTokenProvider=a,this.apiVersion=n,this.deploymentName=i}buildRequest(e,r={}){if(O9r.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!AB(e.body))throw new Error("Expected request body to be an object");let n=this.deploymentName||e.body.model||e.__metadata?.model;n!==void 0&&!this.baseURL.includes("/deployments")&&(e.path=`/deployments/${n}${e.path}`)}return super.buildRequest(e,r)}async _getAzureADToken(){if(typeof this._azureADTokenProvider=="function"){let e=await this._azureADTokenProvider();if(!e||typeof e!="string")throw new vt(`Expected 'azureADTokenProvider' argument to return a string but it returned ${e}`);return e}}authHeaders(e){return{}}async prepareOptions(e){if(e.headers?.["api-key"])return super.prepareOptions(e);let r=await this._getAzureADToken();if(e.headers??(e.headers={}),r)e.headers.Authorization=`Bearer ${r}`;else if(this.apiKey!==aAt)e.headers["api-key"]=this.apiKey;else throw new vt("Unable to handle auth");return super.prepareOptions(e)}},O9r=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations"]),aAt="<Missing Key>"});function Jp(t,e){if(t.function===void 0)return;let r;if(e?.partial)try{r=KL(t.function.arguments??"{}")}catch{return}else try{r=JSON.parse(t.function.arguments)}catch(o){throw new vm([`Function "${t.function.name}" arguments:`,"",t.function.arguments,"","are not valid JSON.",`Error: ${o.message}`].join(`
`))}let n={name:t.function.name,args:r,type:"tool_call"};return e?.returnId&&(n.id=t.id),n}function Ox(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 Xm(t,e){return{name:t.function?.name,args:t.function?.arguments,id:t.id,error:e,type:"invalid_tool_call"}}var fMe,Zc,uAt=w(()=>{tF();bhe();$E();SR();fMe=class extends AR{static lc_name(){return"JsonOutputToolsParser"}constructor(e){super(e),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","openai_tools"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.returnId=e?.returnId??this.returnId}_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(Oi(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=>Jp(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}},Zc=class extends fMe{static lc_name(){return"JsonOutputKeyToolsParser"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","openai_tools"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"keyName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"returnSingle",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"zodSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){if(this.zodSchema===void 0)return e;let r=await this.zodSchema.safeParseAsync(e);if(r.success)return r.data;throw new vm(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(r.error.errors)}`,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 lAt=w(()=>{uAt()});var aq=w(()=>{lAt()});var dAt,cAt,fAt,Nne=w(()=>{dAt=Symbol("Let zodToJsonSchema decide on which parser to use"),cAt={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},fAt=t=>typeof t=="string"?{...cAt,basePath:["#"],definitions:{},name:t}:{...cAt,basePath:["#"],definitions:{},...t}});function pAt(t){if(!t)return!0;for(let e in t)return!1;return!0}var P8,pMe=w(()=>{P8=t=>"_def"in t?t._def:t});var mAt,mMe=w(()=>{Nne();pMe();mAt=t=>{let e=fAt(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[P8(o),{def:P8(o),path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function hMe(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function Wn(t,e,r,n,o){t[e]=r,hMe(t,e,n,o)}var JA=w(()=>{});function hAt(){return{}}var gMe=w(()=>{});function gAt(t,e){let r={type:"array"};return t.type?._def?.typeName!==de.ZodAny&&(r.items=pr(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&Wn(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&Wn(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(Wn(r,"minItems",t.exactLength.value,t.exactLength.message,e),Wn(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var yMe=w(()=>{Td();JA();Zs()});function yAt(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?Wn(r,"minimum",n.value,n.message,e Line truncated
]))`;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 Lne(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===de.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:pr(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:pr(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===de.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(Nne(t.keyType._def,e)).reduce((o,[i,a])=>i==="type"?o:{...o,[i]:a},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===de.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}var Fne=w(()=>{Td();Zs();Dne()});function xAt(t,e){if(e.mapStrategy==="record")return Lne(t,e);let r=pr(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=pr(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 EMe=w(()=>{Zs();Fne()});function CAt(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 TMe=w(()=>{});function OAt(){return{not:{}}}var AMe=w(()=>{});function PAt(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var IMe=w(()=>{});function TAt(t,e){if(e.target==="openApi3")return EAt(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in P8&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=P8[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 EAt(t,e)}var P8,EAt,kne=w(()=>{Zs();P8={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};EAt=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>pr(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 AAt(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:P8[t.innerType._def.typeName],nullable:!0}:{type:[P8[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=pr(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=pr(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var MMe=w(()=>{Zs();kne()});function IAt(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",fMe(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?Wn(r,"minimum",n.value,n.message,e):Wn(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),Wn(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Wn(r,"maximum",n.value,n.message,e):Wn(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),Wn(r,"maximum",n.value,n.message,e));break;case"multipleOf":Wn(r,"multipleOf",n.value,n.message,e);break}return r}var RMe=w(()=>{JA()});function C9r(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":pr(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":pr(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function MAt(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((n,[o,i Line truncated
This will become an error in a future version of the SDK.`),{properties:{...n.properties,[o]:s},required:i.isOptional()&&!e.openaiStrictMode?n.required:[...n.required,o]})},{properties:{},required:[]}),additionalProperties:C9r(t,e)};return r.required.length||delete r.required,r}var jMe=w(()=>{Zs()});var RAt,NMe=w(()=>{Zs();RAt=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return pr(t.innerType._def,e);let r=pr(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}}});var jAt,DMe=w(()=>{Zs();jAt=(t,e)=>{if(e.pipeStrategy==="input")return pr(t.in._def,e);if(e.pipeStrategy==="output")return pr(t.out._def,e);let r=pr(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=pr(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function NAt(t,e){return pr(t.type._def,e)}var LMe=w(()=>{Zs()});function DAt(t,e){let n={type:"array",uniqueItems:!0,items:pr(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&Wn(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&Wn(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var FMe=w(()=>{JA();Zs()});function LAt(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>pr(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:pr(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>pr(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var kMe=w(()=>{Zs()});function FAt(){return{not:{}}}var $Me=w(()=>{});function kAt(){return{}}var BMe=w(()=>{});var $At,qMe=w(()=>{Zs();$At=(t,e)=>pr(t.innerType._def,e)});function pr(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==sAt)return a}if(n&&!r){let a=O9r(n,e);if(a!==void 0)return"$ref"in a&&e.seenRefs.add(a.$ref),a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let i=E9r(t,t.typeName,e,r);return i&&T9r(t,e,i),o.jsonSchema=i,i}var O9r,P9r,E9r,T9r,Zs=w(()=>{Td();pMe();mMe();hMe();gMe();yMe();bMe();vMe();wMe();SMe();xMe();CMe();OMe();EMe();TMe();AMe();IMe();MMe();RMe();jMe();NMe();DMe();LMe();Fne();FMe();Dne();kMe();$Me();kne();BMe();qMe();jne();O9r=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":let r=t.path.slice(e.basePath.length+1).join("_");return r!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[r]=t.def),{$ref:[...e.basePath,e.definitionPath,r].join("/")};case"relative":return{$ref:P9r(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,o)=>e.currentPath[o]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},P9r=(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("/")},E9r=(t,e,r,n)=>{switch(e){case de.ZodString:return Nne(t,r);case de.ZodNumber:return IAt(t,r);case de.ZodObject:return MAt(t,r);case de.ZodBigInt:return pAt(t,r);case de.ZodBoolean:return mAt();case de.ZodDate:return _Me(t,r);case de.ZodUndefined:return FAt();case de.ZodNull:return PAt(r);case de.ZodArray:return fAt(t,r);case de.ZodUnion:case de.ZodDiscriminatedUnion:return TAt(t,r);case de.ZodIntersection:return vAt(t,r);case de.ZodTuple:return LAt(t,r);case de.ZodRecord:return Lne(t,r);case de.ZodLiteral:return wAt(t,r);case de.ZodEnum:return _At(t);case de.ZodNativeEnum:return CAt(t);case de.ZodNullable:return AAt(t,r);case de.ZodOptional:return RAt(t,r);case de.ZodMap:return xAt(t,r);case de.ZodSet:return DAt(t,r);case de.ZodLazy:return pr(t.getter()._def,r);case de.ZodPromise:return NAt(t,r);case de.ZodNaN:case de.ZodNever:return OAt();case de.ZodEffects:return bAt(t,r,n);case de.ZodAny:return dAt();case de.ZodUnknown:return kAt();case de.ZodDefault:return yAt(t,r);case de.ZodBranded:return hAt(t,r);case de.ZodReadonly:return $At(t,r);case de.ZodCatch:return gAt(t,r);case de.ZodPipeline:return jAt(t,r);case de.ZodFunction:case de.ZodVoid:case de.ZodSymbol:return;default:return(o=>{})(e)}},T9r=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var BAt,qAt=w(()=>{Zs();dMe();cMe();BAt=(t,e)=>{let r=cAt(e),n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=pr(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.title=i);let a=(()=>{if(lAt(r.definitions))return;let u={},l=new Set;for(let c=0;c<500;c++){let d=Object.entries(r.definitions).filter(([f])=>!l.has(f));if(d.length===0)break;for(let[f,p]of d)u[f]=pr(O8(p),{...r,currentPath:[...r.basePath,r.de Line truncated
]`;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 Fne(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===de.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:pr(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:pr(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===de.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(Dne(t.keyType._def,e)).reduce((o,[i,a])=>i==="type"?o:{...o,[i]:a},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===de.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}var kne=w(()=>{Td();Zs();Lne()});function EAt(t,e){if(e.mapStrategy==="record")return Fne(t,e);let r=pr(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=pr(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 IMe=w(()=>{Zs();kne()});function TAt(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 MMe=w(()=>{});function AAt(){return{not:{}}}var RMe=w(()=>{});function IAt(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var jMe=w(()=>{});function RAt(t,e){if(e.target==="openApi3")return MAt(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in E8&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=E8[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 MAt(t,e)}var E8,MAt,$ne=w(()=>{Zs();E8={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};MAt=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>pr(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 jAt(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:E8[t.innerType._def.typeName],nullable:!0}:{type:[E8[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=pr(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=pr(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var NMe=w(()=>{Zs();$ne()});function NAt(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",hMe(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?Wn(r,"minimum",n.value,n.message,e):Wn(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),Wn(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Wn(r,"maximum",n.value,n.message,e):Wn(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),Wn(r,"maximum",n.value,n.message,e));break;case"multipleOf":Wn(r,"multipleOf",n.value,n.message,e);break}return r}var DMe=w(()=>{JA()});function A9r(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":pr(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":pr(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function DAt(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((n,[o,i Line truncated
This will become an error in a future version of the SDK.`),{properties:{...n.properties,[o]:s},required:i.isOptional()&&!e.openaiStrictMode?n.required:[...n.required,o]})},{properties:{},required:[]}),additionalProperties:A9r(t,e)};return r.required.length||delete r.required,r}var LMe=w(()=>{Zs()});var LAt,FMe=w(()=>{Zs();LAt=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return pr(t.innerType._def,e);let r=pr(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}}});var FAt,kMe=w(()=>{Zs();FAt=(t,e)=>{if(e.pipeStrategy==="input")return pr(t.in._def,e);if(e.pipeStrategy==="output")return pr(t.out._def,e);let r=pr(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=pr(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function kAt(t,e){return pr(t.type._def,e)}var $Me=w(()=>{Zs()});function $At(t,e){let n={type:"array",uniqueItems:!0,items:pr(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&Wn(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&Wn(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var BMe=w(()=>{JA();Zs()});function BAt(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>pr(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:pr(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>pr(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var qMe=w(()=>{Zs()});function qAt(){return{not:{}}}var UMe=w(()=>{});function UAt(){return{}}var zMe=w(()=>{});var zAt,HMe=w(()=>{Zs();zAt=(t,e)=>pr(t.innerType._def,e)});function pr(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==dAt)return a}if(n&&!r){let a=I9r(n,e);if(a!==void 0)return"$ref"in a&&e.seenRefs.add(a.$ref),a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let i=R9r(t,t.typeName,e,r);return i&&j9r(t,e,i),o.jsonSchema=i,i}var I9r,M9r,R9r,j9r,Zs=w(()=>{Td();gMe();yMe();bMe();_Me();vMe();wMe();xMe();CMe();OMe();PMe();EMe();TMe();IMe();MMe();RMe();jMe();NMe();DMe();LMe();FMe();kMe();$Me();kne();BMe();Lne();qMe();UMe();$ne();zMe();HMe();Nne();I9r=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":let r=t.path.slice(e.basePath.length+1).join("_");return r!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[r]=t.def),{$ref:[...e.basePath,e.definitionPath,r].join("/")};case"relative":return{$ref:M9r(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,o)=>e.currentPath[o]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},M9r=(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("/")},R9r=(t,e,r,n)=>{switch(e){case de.ZodString:return Dne(t,r);case de.ZodNumber:return NAt(t,r);case de.ZodObject:return DAt(t,r);case de.ZodBigInt:return yAt(t,r);case de.ZodBoolean:return bAt();case de.ZodDate:return SMe(t,r);case de.ZodUndefined:return qAt();case de.ZodNull:return IAt(r);case de.ZodArray:return gAt(t,r);case de.ZodUnion:case de.ZodDiscriminatedUnion:return RAt(t,r);case de.ZodIntersection:return CAt(t,r);case de.ZodTuple:return BAt(t,r);case de.ZodRecord:return Fne(t,r);case de.ZodLiteral:return OAt(t,r);case de.ZodEnum:return xAt(t);case de.ZodNativeEnum:return TAt(t);case de.ZodNullable:return jAt(t,r);case de.ZodOptional:return LAt(t,r);case de.ZodMap:return EAt(t,r);case de.ZodSet:return $At(t,r);case de.ZodLazy:return pr(t.getter()._def,r);case de.ZodPromise:return kAt(t,r);case de.ZodNaN:case de.ZodNever:return AAt();case de.ZodEffects:return SAt(t,r,n);case de.ZodAny:return hAt();case de.ZodUnknown:return UAt();case de.ZodDefault:return wAt(t,r);case de.ZodBranded:return _At(t,r);case de.ZodReadonly:return zAt(t,r);case de.ZodCatch:return vAt(t,r);case de.ZodPipeline:return FAt(t,r);case de.ZodFunction:case de.ZodVoid:case de.ZodSymbol:return;default:return(o=>{})(e)}},j9r=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var HAt,VAt=w(()=>{Zs();mMe();pMe();HAt=(t,e)=>{let r=mAt(e),n=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=pr(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??{},i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.title=i);let a=(()=>{if(pAt(r.definitions))return;let u={},l=new Set;for(let c=0;c<500;c++){let d=Object.entries(r.definitions).filter(([f])=>!l.has(f));if(d.length===0)break;for(let[f,p]of d)u[f]=pr(P8(p),{...r,currentPath:[...r.basePath,r.de Line truncated
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
`,t}var HAt=w(()=>{});function JO(t){let e;return t.constructor.name===Xf.name?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===Li.name?(e=new Error(t.message),e.name="AbortError"):t.status===400&&t.message.includes("tool_calls")?e=E8(t,"INVALID_TOOL_RESULTS"):t.status===401?e=E8(t,"MODEL_AUTHENTICATION"):t.status===429?e=E8(t,"MODEL_RATE_LIMIT"):t.status===404?e=E8(t,"MODEL_NOT_FOUND"):e=t,e}function UMe(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 dN=w(()=>{pg();Km();Ec();pB();HAt()});function A9r(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function VAt(t){let e=["namespace functions {",""];for(let r of t)r.description&&e.push(`// ${r.description}`),Object.keys(r.parameters.properties??{}).length>0?(e.push(`type ${r.name} = (_: {`),e.push(WAt(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
`)}function WAt(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}: ${Bne(o,e)},`):r.push(`${n}?: ${Bne(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
`)}function Bne(t,e){if(A9r(t))return t.anyOf.map(r=>Bne(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["{",WAt(t,e+2),"}"].join(`
`);case"array":return t.items?`${Bne(t.items,e)}[]`:"any[]";default:return""}}var KAt=w(()=>{});function GAt(t,e){let r;return rc(t)?r=dx(t):r=t,e?.strict!==void 0&&(r.function.strict=e.strict),r}var JAt=w(()=>{Km();dN()});function I9r(t){return t.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}function VMe(t){let e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":{if(!Cs.isInstance(t))throw new Error("Invalid generic chat message");return I9r(t)}default:throw new Error(`Unknown message type: ${e}`)}}function HMe(t,e){return t.flatMap(r=>{let n=VMe(r);n==="system"&&WMe(e)&&(n="developer");let o={role:n,content:r.content};if(r.name!=null&&(o.name=r.name),r.additional_kwargs.function_call!=null&&(o.function_call=r.additional_kwargs.function_call,o.content=""),Oi(r)&&r.tool_calls?.length?(o.tool_calls=r.tool_calls.map(Ox),o.content=""):(r.additional_kwargs.tool_calls!=null&&(o.tool_calls=r.additional_kwargs.tool_calls),r.tool_call_id!=null&&(o.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio){let i={role:"assistant",audio:{id:r.additional_kwargs.audio.id}};return[o,i]}return o})}function YAt(t,e){return t.flatMap(r=>{let n=VMe(r);if(n==="system"&&WMe(e)&&(n="developer"),n==="function")throw new Error("Function messages are not supported in Responses API");if(n==="tool"){let i=r;return i.additional_kwargs?.type==="computer_call_output"?{type:"computer_call_output",output:(()=>{if(typeof i.content=="string")return{type:"computer_screenshot",image_url:i.content};if(Array.isArray(i.content)){let s=i.content.find(l=>l.type==="computer_screenshot");if(s)return s;let u=i.content.find(l=>l.type==="image_url");if(u)return{type:"computer_screenshot",image_url:typeof u.image_url=="string"?u.image_url:u.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:i.tool_call_id}:{type:"function_call_output",call_id:i.tool_call_id,id:i.id,output:typeof i.content!="string"?JSON.stringify(i.content):i.content}}if(n==="assistant"){let i=[];r.additional_kwargs.reasoning!=null&&(c=>typeof c=="object"&&c!=null&&"type"in c&&c.type==="reasoning")(r.additional_kwargs.reasoning)&&i.push(r.additional_kwargs.reasoning);let{content:a}=r;r.additional_kwargs.refusal!=null&&(typeof a=="string"&&(a=[{type:"output_text",text:a,annotations:[]}]),a=[...a,{type:"refusal",refusal:r.additional_kwargs.refusal}]),i.push({type:"message",role:"assistant",content:typeof a=="string"?a:a.flatMap(l=>l.type==="text"?{type:"output_text",text:l.text,annotations:l.annotations??[]}:l.type==="output_text"||l.type==="refusal"?l:[])});let s=r.additional_kwargs[uq];Oi(r)&&r.tool_calls?.length?i.push(...r.tool_calls.map(l=>({type:"function_call",name:l.name,arguments:JSON.stringify(l.args),call_id:l.id,id:s?.[l.id]}))):r.additional_kwargs.tool_calls!=null&&i.push(...r.additional_kwargs.tool_calls.map(l=>({type:"function_call",name:l.function.name,call_id:l.id,id:s?.[l.id],arguments:l.function.arguments})));let u=r.response_metadata.output?.length?r.response_metadata.output:r.additional_kwargs.tool_outputs;if(u!=null){let l=u,c=l?.filter(f=>f.type==="reasoning"),d=l?.filter(f=>f.type==="computer_call");c.length>0&&d.length>0&&i.push(...c),d.length>0&&i.push(...d)}return i}let o=typeof r.content=="string"?r.content:r.content.flatMap(i=>{if(i.type==="text")return{type:"input_text",text:i.text};if(i.type==="image_url"){let a=typeof i.image_url=="string"?i.image_url:i.image_url.url,s=typeof i.image_url=="string"?"auto":i.image_url.detail;return{type:"input_image",image_url:a,detail:s}}return i.type==="input_text"||i.type==="input_image"||i.type==="input_file"?i:[]});return n==="user"||n==="system"||n==="developer"?{type:"message",role:n,content:o}:(console.warn(`Unsupported role found when converting to OpenAI Responses API: ${n}`),[])})}function XAt(t){if(t.error){let a=new Error(t.error.message);throw a.name=t.error.code,a}let e=[],r=[],n=[],o={model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,status:t.status,user:t.user,model_name:t.model},i={};for(let a of t.output)if(a.type==="message")e.push(...a.content.flatMap(s=>s.type==="output_text"?("parsed"in s&&s.parsed!=null&&(i.parsed=s.parsed),{type:"text",text:s.text,annotations:s.annotations}):s.type==="refusal"?(i.refusal=s.refusal,[]):s));else if(a.type==="function_call"){let s={function:{name:a.name,arguments:a.arguments},id:a.call_id};try{r.push(Jp(s,{returnId:!0}))}catch(u){let l;typeof u=="object"&&u!=null&&"message"in u&&typeof u.message=="string"&&(l=u.message),n.push(Xm(s,l))}i[uq]??(i[uq]={}),a.id&&(i[uq][a.call_id]=a.id)}else a.type==="reasoning"?i.reasoning=a:(i.tool_outputs??(i.tool_outputs=[ Line truncated
`,t}var GAt=w(()=>{});function YO(t){let e;return t.constructor.name===Xf.name?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===Li.name?(e=new Error(t.message),e.name="AbortError"):t.status===400&&t.message.includes("tool_calls")?e=T8(t,"INVALID_TOOL_RESULTS"):t.status===401?e=T8(t,"MODEL_AUTHENTICATION"):t.status===429?e=T8(t,"MODEL_RATE_LIMIT"):t.status===404?e=T8(t,"MODEL_NOT_FOUND"):e=t,e}function VMe(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 fN=w(()=>{pg();Km();Ec();mB();GAt()});function N9r(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function JAt(t){let e=["namespace functions {",""];for(let r of t)r.description&&e.push(`// ${r.description}`),Object.keys(r.parameters.properties??{}).length>0?(e.push(`type ${r.name} = (_: {`),e.push(YAt(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
`)}function YAt(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}: ${qne(o,e)},`):r.push(`${n}?: ${qne(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
`)}function qne(t,e){if(N9r(t))return t.anyOf.map(r=>qne(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["{",YAt(t,e+2),"}"].join(`
`);case"array":return t.items?`${qne(t.items,e)}[]`:"any[]";default:return""}}var ZAt=w(()=>{});function XAt(t,e){let r;return rc(t)?r=dx(t):r=t,e?.strict!==void 0&&(r.function.strict=e.strict),r}var QAt=w(()=>{Km();fN()});function D9r(t){return t.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}function GMe(t){let e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":{if(!Cs.isInstance(t))throw new Error("Invalid generic chat message");return D9r(t)}default:throw new Error(`Unknown message type: ${e}`)}}function KMe(t,e){return t.flatMap(r=>{let n=GMe(r);n==="system"&&JMe(e)&&(n="developer");let o={role:n,content:r.content};if(r.name!=null&&(o.name=r.name),r.additional_kwargs.function_call!=null&&(o.function_call=r.additional_kwargs.function_call,o.content=""),Oi(r)&&r.tool_calls?.length?(o.tool_calls=r.tool_calls.map(Ox),o.content=""):(r.additional_kwargs.tool_calls!=null&&(o.tool_calls=r.additional_kwargs.tool_calls),r.tool_call_id!=null&&(o.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio){let i={role:"assistant",audio:{id:r.additional_kwargs.audio.id}};return[o,i]}return o})}function eIt(t,e){return t.flatMap(r=>{let n=GMe(r);if(n==="system"&&JMe(e)&&(n="developer"),n==="function")throw new Error("Function messages are not supported in Responses API");if(n==="tool"){let i=r;return i.additional_kwargs?.type==="computer_call_output"?{type:"computer_call_output",output:(()=>{if(typeof i.content=="string")return{type:"computer_screenshot",image_url:i.content};if(Array.isArray(i.content)){let s=i.content.find(l=>l.type==="computer_screenshot");if(s)return s;let u=i.content.find(l=>l.type==="image_url");if(u)return{type:"computer_screenshot",image_url:typeof u.image_url=="string"?u.image_url:u.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:i.tool_call_id}:{type:"function_call_output",call_id:i.tool_call_id,id:i.id,output:typeof i.content!="string"?JSON.stringify(i.content):i.content}}if(n==="assistant"){let i=[];r.additional_kwargs.reasoning!=null&&(c=>typeof c=="object"&&c!=null&&"type"in c&&c.type==="reasoning")(r.additional_kwargs.reasoning)&&i.push(r.additional_kwargs.reasoning);let{content:a}=r;r.additional_kwargs.refusal!=null&&(typeof a=="string"&&(a=[{type:"output_text",text:a,annotations:[]}]),a=[...a,{type:"refusal",refusal:r.additional_kwargs.refusal}]),i.push({type:"message",role:"assistant",content:typeof a=="string"?a:a.flatMap(l=>l.type==="text"?{type:"output_text",text:l.text,annotations:l.annotations??[]}:l.type==="output_text"||l.type==="refusal"?l:[])});let s=r.additional_kwargs[lq];Oi(r)&&r.tool_calls?.length?i.push(...r.tool_calls.map(l=>({type:"function_call",name:l.name,arguments:JSON.stringify(l.args),call_id:l.id,id:s?.[l.id]}))):r.additional_kwargs.tool_calls!=null&&i.push(...r.additional_kwargs.tool_calls.map(l=>({type:"function_call",name:l.function.name,call_id:l.id,id:s?.[l.id],arguments:l.function.arguments})));let u=r.response_metadata.output?.length?r.response_metadata.output:r.additional_kwargs.tool_outputs;if(u!=null){let l=u,c=l?.filter(f=>f.type==="reasoning"),d=l?.filter(f=>f.type==="computer_call");c.length>0&&d.length>0&&i.push(...c),d.length>0&&i.push(...d)}return i}let o=typeof r.content=="string"?r.content:r.content.flatMap(i=>{if(i.type==="text")return{type:"input_text",text:i.text};if(i.type==="image_url"){let a=typeof i.image_url=="string"?i.image_url:i.image_url.url,s=typeof i.image_url=="string"?"auto":i.image_url.detail;return{type:"input_image",image_url:a,detail:s}}return i.type==="input_text"||i.type==="input_image"||i.type==="input_file"?i:[]});return n==="user"||n==="system"||n==="developer"?{type:"message",role:n,content:o}:(console.warn(`Unsupported role found when converting to OpenAI Responses API: ${n}`),[])})}function rIt(t){if(t.error){let a=new Error(t.error.message);throw a.name=t.error.code,a}let e=[],r=[],n=[],o={model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,status:t.status,user:t.user,model_name:t.model},i={};for(let a of t.output)if(a.type==="message")e.push(...a.content.flatMap(s=>s.type==="output_text"?("parsed"in s&&s.parsed!=null&&(i.parsed=s.parsed),{type:"text",text:s.text,annotations:s.annotations}):s.type==="refusal"?(i.refusal=s.refusal,[]):s));else if(a.type==="function_call"){let s={function:{name:a.name,arguments:a.arguments},id:a.call_id};try{r.push(Jp(s,{returnId:!0}))}catch(u){let l;typeof u=="object"&&u!=null&&"message"in u&&typeof u.message=="string"&&(l=u.message),n.push(Xm(s,l))}i[lq]??(i[lq]={}),a.id&&(i[lq][a.call_id]=a.id)}else a.type==="reasoning"?i.reasoning=a:(i.tool_outputs??(i.tool_outputs=[ Line truncated
Details: ${m.message}`),new wR(h,JSON.stringify(e))}else{let m=oa(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(b=>`${b.keywordLocation}: ${b.error}`).join(`
`)}`),new wR(h,JSON.stringify(e))}i=o}let a=CR(r),u=await Bs.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;RE(e)&&(f=e.id),!f&&B4e(a)&&(f=a.toolCall.id);let p=N9r({content:c,artifact:d,toolCallId:f,name:this.name});return await u?.handleToolEnd(p),p}},ZO=class extends Hne{constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:Wr.object({input:Wr.string().optional()}).transform(r=>r.input)})}call(e,r){let n=typeof e=="string"||e==null?{input:e}:e;return super.call(n,r)}},JMe=class extends ZO{static lc_name(){return"DynamicTool"}constructor(e){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}async call(e,r){let n=CR(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)}},YMe=class extends Hne{static lc_name(){return"DynamicStructuredTool"}constructor(e){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}async call(e,r,n){let o=CR(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)}}});var ZA=w(()=>{iIt()});var ZMe,aIt=w(()=>{Dn();pg();ZA();ZMe=class extends ZO{static lc_name(){return"DallEAPIWrapper"}constructor(e){e?.responseFormat!==void 0&&["url","b64_json"].includes(e.responseFormat)&&(e.dallEResponseFormat=e.responseFormat,e.responseFormat="content"),super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"dalle_api_wrapper"}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:"A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description."}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"dall-e-3"}),Object.defineProperty(this,"style",{enumerable:!0,configurable:!0,writable:!0,value:"vivid"}),Object.defineProperty(this,"quality",{enumerable:!0,configurable:!0,writable:!0,value:"standard"}),Object.defineProperty(this,"n",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:"1024x1024"}),Object.defineProperty(this,"dallEResponseFormat",{enumerable:!0,configurable:!0,writable:!0,value:"url"}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let r=e?.apiKey??e?.openAIApiKey??ot("OPENAI_API_KEY"),n=e?.organization??ot("OPENAI_ORGANIZATION"),o={apiKey:r,organization:n,dangerouslyAllowBrowser:!0,baseURL:e?.baseUrl};this.client=new Wt(o),this.model=e?.model??e?.modelName??this.model,this.style=e?.style??this.style,this.quality=e?.quality??this.quality,this.n=e?.n??this.n,this.size=e?.size??this.size,this.dallEResponseFormat=e?.dallEResponseFormat??this.dallEResponseFormat,this.user=e?.user}processMultipleGeneratedUrls(e){return this.dallEResponseFormat==="url"?e.flatMap(r=>r.data.flatMap(o=>o.url?{type:"image_url",image_url:o.url}:[]).filter(o=>o!==void 0&&o.type==="image_url"&&typeof o.image_url=="string"&&o.image_url!==void 0)):e.flatMap(r=>r.data.flatMap(o=>o.b64_json?{type:"image_url",image_url:{url:o.b64_json}}:[]).filter(o=>o!==void 0&&o.type==="image_url"&&typeof o.image_url=="object"&&"url"in o.image_url&&typeof o.image_url.url=="string"&&o.image_url.url!==void 0))}async _call(e){let r={model:this.model,prompt:e,n:1,size:this.size,response_format:this.dallEResponseFormat,style:this.style,quality:this.quality,user:this.user};if(this.n>1){let i=await Promise.all(Array.from({length:this.n}).map(()=>this.client.images.generate(r)));return this.processMultipleGeneratedUrls(i)}let n=await this.client.images.generate(r),o="";return this.dallEResponseFormat==="url"?[o]=n.data.map(i=>i.url).filter(i=>i!=="undefined"):[o]=n.data.map(i=>i.b64_json).filter(i=>i!=="undefined"),o}};Object.defineProperty(ZMe,"toolName",{enumerable:!0,configurable:!0,writable:!0,value:"dalle_api_wrapper"})});var sIt=w(()=>{aIt()});var uIt=w(()=>{Une()});var lIt=w(()=>{Une();QAt();KMe();rIt();nIt();GMe();oIt();dN();YA();sIt();uIt()});var XMe=w(()=>{lIt()});var Vne,cIt=w(()=>{$O();dg();Dn();Vne=class extends Jf{c Line truncated
Result: ${JSON.stringify(l)}`);else c=l;let f;RE(e)&&(f=e.id),!f&&U4e(a)&&(f=a.toolCall.id);let p=$9r({content:c,artifact:d,toolCallId:f,name:this.name});return await u?.handleToolEnd(p),p}},ZO=class extends Vne{constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:Wr.object({input:Wr.string().optional()}).transform(r=>r.input)})}call(e,r){let n=typeof e=="string"||e==null?{input:e}:e;return super.call(n,r)}},XMe=class extends ZO{static lc_name(){return"DynamicTool"}constructor(e){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}async call(e,r){let n=CR(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)}},QMe=class extends Vne{static lc_name(){return"DynamicStructuredTool"}constructor(e){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}async call(e,r,n){let o=CR(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)}}});var ZA=w(()=>{lIt()});var eRe,cIt=w(()=>{Dn();pg();ZA();eRe=class extends ZO{static lc_name(){return"DallEAPIWrapper"}constructor(e){e?.responseFormat!==void 0&&["url","b64_json"].includes(e.responseFormat)&&(e.dallEResponseFormat=e.responseFormat,e.responseFormat="content"),super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"dalle_api_wrapper"}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:"A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description."}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"dall-e-3"}),Object.defineProperty(this,"style",{enumerable:!0,configurable:!0,writable:!0,value:"vivid"}),Object.defineProperty(this,"quality",{enumerable:!0,configurable:!0,writable:!0,value:"standard"}),Object.defineProperty(this,"n",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:"1024x1024"}),Object.defineProperty(this,"dallEResponseFormat",{enumerable:!0,configurable:!0,writable:!0,value:"url"}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let r=e?.apiKey??e?.openAIApiKey??ot("OPENAI_API_KEY"),n=e?.organization??ot("OPENAI_ORGANIZATION"),o={apiKey:r,organization:n,dangerouslyAllowBrowser:!0,baseURL:e?.baseUrl};this.client=new Wt(o),this.model=e?.model??e?.modelName??this.model,this.style=e?.style??this.style,this.quality=e?.quality??this.quality,this.n=e?.n??this.n,this.size=e?.size??this.size,this.dallEResponseFormat=e?.dallEResponseFormat??this.dallEResponseFormat,this.user=e?.user}processMultipleGeneratedUrls(e){return this.dallEResponseFormat==="url"?e.flatMap(r=>r.data.flatMap(o=>o.url?{type:"image_url",image_url:o.url}:[]).filter(o=>o!==void 0&&o.type==="image_url"&&typeof o.image_url=="string"&&o.image_url!==void 0)):e.flatMap(r=>r.data.flatMap(o=>o.b64_json?{type:"image_url",image_url:{url:o.b64_json}}:[]).filter(o=>o!==void 0&&o.type==="image_url"&&typeof o.image_url=="object"&&"url"in o.image_url&&typeof o.image_url.url=="string"&&o.image_url.url!==void 0))}async _call(e){let r={model:this.model,prompt:e,n:1,size:this.size,response_format:this.dallEResponseFormat,style:this.style,quality:this.quality,user:this.user};if(this.n>1){let i=await Promise.all(Array.from({length:this.n}).map(()=>this.client.images.generate(r)));return this.processMultipleGeneratedUrls(i)}let n=await this.client.images.generate(r),o="";return this.dallEResponseFormat==="url"?[o]=n.data.map(i=>i.url).filter(i=>i!=="undefined"):[o]=n.data.map(i=>i.b64_json).filter(i=>i!=="undefined"),o}};Object.defineProperty(eRe,"toolName",{enumerable:!0,configurable:!0,writable:!0,value:"dalle_api_wrapper"})});var dIt=w(()=>{cIt()});var fIt=w(()=>{zne()});var pIt=w(()=>{zne();nIt();YMe();aIt();sIt();ZMe();uIt();fN();YA();dIt();fIt()});var Wne=w(()=>{pIt()});var Kne,mIt=w(()=>{BO();dg();Dn();Kne=class extends Jf{c Line truncated
without CORS Error: `+ei(n)+`
with CORS Error: `+ei(o);throw new Error(i)}}}}});function hIt(t){return t!==void 0&&T8.includes(t)?pIt[t]:void 0}var pIt,mIt,T8,Gne=w(()=>{pIt={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"},mIt={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},T8=Object.keys(pIt)});function ki(t,e){if(e.length<QMe)Array.prototype.push.apply(t,e);else{let r=e.length;for(let n=0;n<r;n+=QMe)Array.prototype.push.apply(t,e.slice(n,n+QMe))}}function vIt(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 $9r(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function B9r(){return typeof process<"u"&&process.release&&process.release.name==="node"}function _It(){return BigInt(Math.floor(performance.now()*1e6))}function pN(t){return typeof t=="number"&&(t=BigInt(t)),t<gIt?`${t}ns`:t<yIt?`${t/gIt}\u03BCs`:t<bIt?`${t/yIt}ms`:`${t/bIt}s`}function Qy(){return $9r()?_It():B9r()||typeof process<"u"&&typeof process?.hrtime?.bigint=="function"?process.hrtime.bigint():typeof performance<"u"?_It():BigInt(0)}function A8(){return`${F9r}-${k9r++}`}function lq(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 wIt(t,e){return e[1]===t[1]?t[0]-e[0]:e[1]-t[1]}function cq(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 Jne(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 dq(t,e){return Jne(t,[e])[e]}function eRe(t,e){let r=q9r[e];if(r===void 0)throw new Error(qt("INVALID_DISTANCE_SUFFIX",t).message);return t*r}function Yne(t,e){t.hits=t.hits.map(r=>({...r,document:{...r.document,...e.reduce((n,o)=>{let i=o.split("."),a=i.pop(),s=n;for(let u of i)s[u]=s[u]??{},s=s[u];return s[a]=null,n},r.document)}}))}function Qs(t){return t?.constructor?.name==="AsyncFunction"}var F9r,k9r,gIt,yIt,bIt,QMe,q9r,Ds=w(()=>{ic();F9r=Date.now().toString().slice(5),k9r=0,gIt=BigInt(1e3),yIt=BigInt(1e6),bIt=BigInt(1e9),QMe=65535;q9r={cm:.01,m:1,km:1e3,ft:.3048,yd:.9144,mi:1609.344}});function qt(t,...e){let r=new Error(vIt(z9r[t]??`Unsupported Orama Error code: ${t}`,...e));return r.code=t,"captureStackTrace"in Error.prototype&&Error.captureStackTrace(r),r}var U9r,z9r,ic=w(()=>{Gne();Ds();U9r=T8.join(`
- `),z9r={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.
with CORS Error: `+ei(o);throw new Error(i)}}}}});function vIt(t){return t!==void 0&&A8.includes(t)?bIt[t]:void 0}var bIt,_It,A8,Zne=w(()=>{bIt={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"},_It={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},A8=Object.keys(bIt)});function ki(t,e){if(e.length<tRe)Array.prototype.push.apply(t,e);else{let r=e.length;for(let n=0;n<r;n+=tRe)Array.prototype.push.apply(t,e.slice(n,n+tRe))}}function OIt(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 H9r(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function V9r(){return typeof process<"u"&&process.release&&process.release.name==="node"}function CIt(){return BigInt(Math.floor(performance.now()*1e6))}function mN(t){return typeof t=="number"&&(t=BigInt(t)),t<wIt?`${t}ns`:t<SIt?`${t/wIt}\u03BCs`:t<xIt?`${t/SIt}ms`:`${t/xIt}s`}function Qy(){return H9r()?CIt():V9r()||typeof process<"u"&&typeof process?.hrtime?.bigint=="function"?process.hrtime.bigint():typeof performance<"u"?CIt():BigInt(0)}function I8(){return`${U9r}-${z9r++}`}function cq(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 PIt(t,e){return e[1]===t[1]?t[0]-e[0]:e[1]-t[1]}function dq(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 Xne(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 fq(t,e){return Xne(t,[e])[e]}function rRe(t,e){let r=W9r[e];if(r===void 0)throw new Error(qt("INVALID_DISTANCE_SUFFIX",t).message);return t*r}function Qne(t,e){t.hits=t.hits.map(r=>({...r,document:{...r.document,...e.reduce((n,o)=>{let i=o.split("."),a=i.pop(),s=n;for(let u of i)s[u]=s[u]??{},s=s[u];return s[a]=null,n},r.document)}}))}function Qs(t){return t?.constructor?.name==="AsyncFunction"}var U9r,z9r,wIt,SIt,xIt,tRe,W9r,Ds=w(()=>{ic();U9r=Date.now().toString().slice(5),z9r=0,wIt=BigInt(1e3),SIt=BigInt(1e6),xIt=BigInt(1e9),tRe=65535;W9r={cm:.01,m:1,km:1e3,ft:.3048,yd:.9144,mi:1609.344}});function qt(t,...e){let r=new Error(OIt(G9r[t]??`Unsupported Orama Error code: ${t}`,...e));return r.code=t,"captureStackTrace"in Error.prototype&&Error.captureStackTrace(r),r}var K9r,G9r,ic=w(()=>{Zne();Ds();K9r=A8.join(`
- `),G9r={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:
- ${U9r}`,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.
- ${K9r}`,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 SIt(t){return{raw:Number(t),formatted:pN(t)}}function xIt(t){if(t.id){if(typeof t.id!="string")throw qt("DOCUMENT_ID_MUST_BE_STRING",typeof t.id);return t.id}return A8()}function tRe(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(XO(n)){let i=nRe(n);if(!Array.isArray(o)||o.length!==i)throw qt("INVALID_INPUT_VECTOR",r,i,o.length);continue}if(fq(n)){if(!Array.isArray(o))return r;let i=rRe(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=tRe(o,n);if(i)return r+"."+i;continue}if(typeof o!==n)return r}}}function CIt(t){return t==="geopoint"}function XO(t){return typeof t=="string"&&/^vector\[\d+\]$/.test(t)}function fq(t){return typeof t=="string"&&H9r[t]}function rRe(t){return V9r[t]}function nRe(t){let e=Number(t.slice(7,-1));switch(!0){case isNaN(e):throw qt("INVALID_VECTOR_VALUE",t);case e<=0:throw qt("INVALID_VECTOR_SIZE",t);default:return e}}var H9r,V9r,I8=w(()=>{ic();Ds();Ds();H9r={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},V9r={"string[]":"string","number[]":"number","boolean[]":"boolean","enum[]":"enum"}});function OIt(){return{idToInternalId:new Map,internalIdToId:[],save:W9r,load:K9r}}function W9r(t){return{internalIdToId:t.internalIdToId}}function K9r(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 wi(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?wi(t,e.toString()):e}function hg(t,e){if(t.internalIdToId.length<e)throw new Error(`Invalid internalId ${e}`);return t.internalIdToId[e-1]}var gg=w(()=>{});function J9r(t,e){return{sharedInternalDocumentStore:e,docs:{},count:0}}function Y9r(t,e){let r=wi(t.sharedInternalDocumentStore,e);return t.docs[r]}function Z9r(t,e){let r=e.length,n=Array.from({length:r});for(let o=0;o<r;o++){let i=wi(t.sharedInternalDocumentStore,e[o]);n[o]=t.docs[i]}return n}function X9r(t){return t.docs}function Q9r(t,e,r){let n=wi(t.sharedInternalDocumentStore,e);return typeof t.docs[n]<"u"?!1:(t.docs[n]=r,t.count++,!0)}function eKr(t,e){let r=wi(t.sharedInternalDocumentStore,e);return typeof t.docs[r]>"u"?!1:(delete t.docs[r],t.count--,!0)}function tKr(t){return t.count}function rKr(t,e){let r=e;return{docs:r.docs,count:r.count,sharedInternalDocumentStore:t}}function nKr(t){return{docs:t.docs,count:t.count}}function PIt(){return{create:J9r,get:Y9r,getMultiple:Z9r,getAll:X9r,store:Q9r,remove:eKr,count:tKr,load:rKr,save:nKr}}var oRe=w(()=>{gg()});function TIt(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),qt("PLUGIN_CRASHED")}return r}var EIt,AIt=w(()=>{ic();EIt=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeLoad","afterLoad","afterCreate"]});function eb(t,e,r,n){if(t.some(Qs))return(async()=>{for(let i of t)await i(e,r,n)})();for(let i of t)i(e,r,n)}function mN(t,e,r){if(t.some(Qs))return(async()=>{for(let o of t)await o(e,r)})();for(let o of t)o(e,r)}function pq(t,e,r,n,o){if(t.some(Qs))return(async()=>{for(let a of t)await a(e,r,n,o)})();for(let a of t)a(e,r,n,o)}function mq(t,e,r,n){if(t.some(Qs))return(async()=>{for(let i of t)await i(e,r,n)})();for(let i of t)i(e,r,n)}function MIt(t,e){if(t.some(Qs))return(async()=>{for(let n of t)await n(e)})();for(let n of t)n(e)}var IIt,iRe,XA=w(()=>{Ds();IIt=["tokenizer","index","documentsStore","sorter"],iRe=["validateSchema","getDocumentIndexId","getDocumentProperties","formatElapsedTime"]});function aRe(t){let e=t.r;return t.r=e.l,e.l=t,t.h=Math.max(yg(t.l),yg(t.r))+1,e.h=Math.max(yg(e.l),yg(e.r))+1,e}function sRe(t){let e=t.l;return t.l=e.r,e.r=t,t.h=Math.max(yg(t.l),yg(t.r))+1,e.h=Math.max(yg(e.l),yg(e.r))+1,e}function jIt(t,e,r){let n=[];function o(i){i!==null&&(e<i.k&&o(i.l),i.k>=e&&i.k<=r&&ki(n,i.v),r>i.k&&o(i.r))}return o(t.root),n}function uRe(t,e,r=!1){let n=[];if(t===null)ret Line truncated
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}},nie=class t extends URe{static lc_name(){return"RecursiveCharacterTextSplitter"}constructor(e){super(e),Object.defineProperty(this,"separators",{enumerable:!0,configurable:!0,writable:!0,value:[`
`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages."}});function EIt(t){return{raw:Number(t),formatted:mN(t)}}function TIt(t){if(t.id){if(typeof t.id!="string")throw qt("DOCUMENT_ID_MUST_BE_STRING",typeof t.id);return t.id}return I8()}function nRe(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(XO(n)){let i=iRe(n);if(!Array.isArray(o)||o.length!==i)throw qt("INVALID_INPUT_VECTOR",r,i,o.length);continue}if(pq(n)){if(!Array.isArray(o))return r;let i=oRe(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=nRe(o,n);if(i)return r+"."+i;continue}if(typeof o!==n)return r}}}function AIt(t){return t==="geopoint"}function XO(t){return typeof t=="string"&&/^vector\[\d+\]$/.test(t)}function pq(t){return typeof t=="string"&&J9r[t]}function oRe(t){return Y9r[t]}function iRe(t){let e=Number(t.slice(7,-1));switch(!0){case isNaN(e):throw qt("INVALID_VECTOR_VALUE",t);case e<=0:throw qt("INVALID_VECTOR_SIZE",t);default:return e}}var J9r,Y9r,M8=w(()=>{ic();Ds();Ds();J9r={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},Y9r={"string[]":"string","number[]":"number","boolean[]":"boolean","enum[]":"enum"}});function IIt(){return{idToInternalId:new Map,internalIdToId:[],save:Z9r,load:X9r}}function Z9r(t){return{internalIdToId:t.internalIdToId}}function X9r(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 wi(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?wi(t,e.toString()):e}function hg(t,e){if(t.internalIdToId.length<e)throw new Error(`Invalid internalId ${e}`);return t.internalIdToId[e-1]}var gg=w(()=>{});function eKr(t,e){return{sharedInternalDocumentStore:e,docs:{},count:0}}function tKr(t,e){let r=wi(t.sharedInternalDocumentStore,e);return t.docs[r]}function rKr(t,e){let r=e.length,n=Array.from({length:r});for(let o=0;o<r;o++){let i=wi(t.sharedInternalDocumentStore,e[o]);n[o]=t.docs[i]}return n}function nKr(t){return t.docs}function oKr(t,e,r){let n=wi(t.sharedInternalDocumentStore,e);return typeof t.docs[n]<"u"?!1:(t.docs[n]=r,t.count++,!0)}function iKr(t,e){let r=wi(t.sharedInternalDocumentStore,e);return typeof t.docs[r]>"u"?!1:(delete t.docs[r],t.count--,!0)}function aKr(t){return t.count}function sKr(t,e){let r=e;return{docs:r.docs,count:r.count,sharedInternalDocumentStore:t}}function uKr(t){return{docs:t.docs,count:t.count}}function MIt(){return{create:eKr,get:tKr,getMultiple:rKr,getAll:nKr,store:oKr,remove:iKr,count:aKr,load:sKr,save:uKr}}var aRe=w(()=>{gg()});function jIt(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),qt("PLUGIN_CRASHED")}return r}var RIt,NIt=w(()=>{ic();RIt=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeLoad","afterLoad","afterCreate"]});function eb(t,e,r,n){if(t.some(Qs))return(async()=>{for(let i of t)await i(e,r,n)})();for(let i of t)i(e,r,n)}function hN(t,e,r){if(t.some(Qs))return(async()=>{for(let o of t)await o(e,r)})();for(let o of t)o(e,r)}function mq(t,e,r,n,o){if(t.some(Qs))return(async()=>{for(let a of t)await a(e,r,n,o)})();for(let a of t)a(e,r,n,o)}function hq(t,e,r,n){if(t.some(Qs))return(async()=>{for(let i of t)await i(e,r,n)})();for(let i of t)i(e,r,n)}function LIt(t,e){if(t.some(Qs))return(async()=>{for(let n of t)await n(e)})();for(let n of t)n(e)}var DIt,sRe,XA=w(()=>{Ds();DIt=["tokenizer","index","documentsStore","sorter"],sRe=["validateSchema","getDocumentIndexId","getDocumentProperties","formatElapsedTime"]});function uRe(t){let e=t.r;return t.r=e.l,e.l=t,t.h=Math.max(yg(t.l),yg(t.r))+1,e.h=Math.max(yg(e.l),yg(e.r))+1,e}function lRe(t){let e=t.l;return t.l=e.r,e.r=t,t.h=Math.max(yg(t.l),yg(t.r))+1,e.h=Math.max(yg(e.l),yg(e.r))+1,e}function kIt(t,e,r){let n=[];function o(i){i!==null&&(e<i.k&&o(i.l),i.k>=e&&i.k<=r&&ki(n,i.v),r>i.k&&o(i.r))}return o(t.root),n}function cRe(t,e,r=!1){let n=[];if(t===null)ret Line truncated
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}},aie=class t extends HRe{static lc_name(){return"RecursiveCharacterTextSplitter"}constructor(e){super(e),Object.defineProperty(this,"separators",{enumerable:!0,configurable:!0,writable:!0,value:[`
`,`
`," ",""]}),this.separators=e?.separators??this.separators,this.keepSeparator=e?.keepSeparator??!0}async _splitText(e,r){let n=[],o=r[r.length-1],i;for(let l=0;l<r.length;l+=1){let c=r[l];if(c===""){o=c;break}if(e.includes(c)){o=c,i=r.slice(l+1);break}}let a=this.splitOnSeparator(e,o),s=[],u=this.keepSeparator?"":o;for(let l of a)if(await this.lengthFunction(l)<this.chunkSize)s.push(l);else{if(s.length){let c=await this.mergeSplits(s,u);n.push(...c),s=[]}if(!i)n.push(l);else{let c=await this._splitText(l,i);n.push(...c)}}if(s.length){let l=await this.mergeSplits(s,u);n.push(...l)}return n}async splitText(e){return this._splitText(e,this.separators)}static fromLanguage(e,r){return new t({...r,separators:t.getSeparatorsForLanguage(e)})}static getSeparatorsForLanguage(e){if(e==="cpp")return[`
@@ -517,7 +517,7 @@ do while `,`
assembly `,`
`,`
`," ",""];throw new Error(`Language ${e} is not supported.`)}}});var i1t=w(()=>{o1t()});var a1t=w(()=>{i1t()});var s1t=w(()=>{a1t()});var u1t=w(()=>{s1t()});var l1t,Ax,oie,c1t=w(()=>{$r();fN();yo();QRt();nr();Cn();l1t=F(vq());u1t();Ax=require("obsidian");_g();oie=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=ue();this.rateLimiter=new q8(o.embeddingRequestsPerMin),this.embeddingBatchSize=o.embeddingBatchSize,this.checkpointInterval=8*this.embeddingBatchSize,xa(async()=>{let i=ue();this.rateLimiter=new q8(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 Ax.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 Ax.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){fe(`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(()=>{ie("Copilot index final save completed."),this.dbOps.checkIndexIntegrity().catch(s=>{fe("Background integrity check failed:",s)})}).catch(s=>{fe("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=Xs.getModelName(r),o=nie.fromLanguage("markdown",{chunkSize:wVe}),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:Vl(new Date(a.stat.ctime)).display,modified:Vl(new Date(a.stat.mtime)).display}};(await o.createDocuments([s],[],{chunkHeader:`
`," ",""];throw new Error(`Language ${e} is not supported.`)}}});var c1t=w(()=>{l1t()});var d1t=w(()=>{c1t()});var f1t=w(()=>{d1t()});var p1t=w(()=>{f1t()});var m1t,Ix,sie,h1t=w(()=>{$r();pN();yo();o1t();nr();yn();m1t=F(wq());p1t();Ix=require("obsidian");_g();sie=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=ue();this.rateLimiter=new U8(o.embeddingRequestsPerMin),this.embeddingBatchSize=o.embeddingBatchSize,this.checkpointInterval=8*this.embeddingBatchSize,xa(async()=>{let i=ue();this.rateLimiter=new U8(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 Ix.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 Ix.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){fe(`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(()=>{ie("Copilot index final save completed."),this.dbOps.checkIndexIntegrity().catch(s=>{fe("Background integrity check failed:",s)})}).catch(s=>{fe("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=Xs.getModelName(r),o=aie.fromLanguage("markdown",{chunkSize:OVe}),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:Vl(new Date(a.stat.ctime)).display,modified:Vl(new Date(a.stat.mtime)).display}};(await o.createDocuments([s],[],{chunkHeader:`
NOTE TITLE: [[${l.title}]]
@@ -525,24 +525,24 @@ 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,l1t.MD5)(e).toString()}async getFilesToIndex(e){let{inclusions:r,exclusions:n}=rf(),o=this.app.vault.getMarkdownFiles();if(e)return o.filter(c=>eu(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(!eu(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 ie([`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 Ax.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 Ax.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=ue(),o=bg(n.qaInclusions);o.length>0&&r.push(`Inclusions: ${o.join(", ")}`);let a=[...Zoe(this.app),...bg(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 Ax.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 Ax.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 Ax.Notice("Indexing cancelled");return}e.length>0?new Ax.Notice(`Indexing completed with ${e.length} errors. Check console for details.`):new Ax.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(),ue().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 d1t={};Cf(d1t,{default:()=>ma});var U8,ma,Ix=w(()=>{wT();fN();nr();U8=require("obsidian");Qoe();XRt();c1t();ma=class t{constructor(){this.embeddingsManager=Xs.getInstance(),this.dbOps=new eP(app),this.indexOps=new oie(app,this.dbOps,this.embeddingsManager),this.eventHandler=new eie(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={...ue()};let e=async()=>{let r=ue(),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())}};xa(()=>{this.initializationPromise=e()})}async initialize(){try{let e=3;for(;e>0;)try{await this.dbOps.initializeDB(await this.embeddingsManager.getEmbeddingsAPI());break}catch(r){if(r instanceof Rr&&r.message.includes("Vault adapter not available")&&(e--,e>0)){await new Promise(n=>setTimeout(n,100));continue}new U8.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:",r);break}}catch(e){console.error("Failed to initialize vector store:",e)}}async waitForInitialization(){await this.initializationPromise}async indexVaultToVectorStore(e){return await this.waitForInitialization(),U8.Platform.isMobile&&ue().disableIndexOnMobile?(new U8.Notice("Indexing is disabled on mobile devices"),0):this.indexOps.indexVaultToVectorStore(e)}async clearIndex(){await this.waitForInitialization(),await this.dbOps.clearIndex(await this.embeddingsManager.getEmbeddingsAPI())}async garbageCollectVectorStore(){return await this.waitForInitialization(),this.dbOps.garbageCollect()}async getIndexedFiles(){return await this.waitForInitialization(),this.dbOps.getIndexedFiles()}async isIndexEmpty(){return await this.waitForInitialization(),this.dbOps.isIndexEmpty()}async hasIndex(e){return await this.waitForInitialization(),this.dbOps.hasIndex(e)}onunload(){this.eventHandler.cleanup(),this.dbOps.onunload()}async getDbOps(){return await this.waitForInitialization(),this.dbOps}async getDb(){await this.waitForInitialization();let e=this.dbOps.getDb();if(!e)throw new Error("Database is not loaded. Please restart the plugin.");return e}async reindexFile(e){await this.waitForInitialization(),await this.indexOps.reindexFile(e)}}});function Hbe(t){return t.split("|")[1]==="copilot-plus"}function Sq(){return Rn Line truncated
${n}`:"";super(`${e}: Status ${o} Content-Type ${i} Body ${a}`),this.rawResponse=r,this.body=n,this.statusCode=o,this.contentType=i,this.name="SDKError"}};Xae.SDKError=INe});var U5=v(q5=>{"use strict";Object.defineProperty(q5,"__esModule",{value:!0});q5.EventStream=void 0;q5.discardSentinel=Jen;var $5=10,B5=13,DLt=new Set([$5,B5]),Ken=[new Uint8Array([B5,$5,B5,$5]),new Uint8Array([B5,B5]),new Uint8Array([$5,$5])],RNe=class{constructor(e){this.stream=e.stream,this.decoder=e.decoder}async*[Symbol.asyncIterator](){let e=this.stream.getReader(),r=new Uint8Array([]),n=0;try{for(;;){let{done:o,value:i}=await e.read();if(o)break;let a=new Uint8Array(r.length+i.length);a.set(r),a.set(i,r.length),r=a;for(let s=n;s<r.length;s++){let u=LLt(r,s);if(u==null)continue;let l=r.slice(n,s);n=s+u.length;let c=jNe(l,this.decoder);c!=null&&(yield c)}n>0&&(r=r.slice(n),n=0)}if(r.length>0){let o=jNe(r,this.decoder);o!=null&&(yield o)}}catch(o){if(o instanceof Error&&o.name==="AbortError")return;throw o}finally{e.releaseLock()}}};q5.EventStream=RNe;function LLt(t,e){let r=t[e],n=t[e+1];if(r==null||n==null||!DLt.has(r)||!DLt.has(n))return null;for(let o of Ken){let i=Gen(e,t,o);if(i!=null)return i}return null}function Gen(t,e,r){if(r.length>e.length-t)return null;for(let n=0;n<r.length;n++)if(e[t+n]!==r[n])return null;return r}function jNe(t,e){if(!t.length)return null;let o=new TextDecoder().decode(t).split(/\r?\n|\r/g),i=!1,a={};for(let s of o){if(!s)continue;let u=s.indexOf(":");if(u===0)continue;let l=u>0?s.substring(0,u):"",c=u>0?s.substring(u+1):"";switch(c.charAt(0)===" "&&(c=c.substring(1)),l){case"event":{i=!0,a.event=c;break}case"data":{i=!0,a.data??(a.data=""),a.data+=c+`
`;break}case"id":{i=!0,a.id=c;break}case"retry":{let d=parseInt(c,10);Number.isNaN(d)||(i=!0,a.retry=d);break}}}return i?(a.data!=null&&(a.data=a.data.slice(0,-1)),e(a)):null}function Jen(t,e){return new ReadableStream({async start(r){let n=new Uint8Array([]),o=0,i=!1,a=!1,s=t.getReader();try{for(;!i;){let u=await s.read(),l=u.value;if(i=i||u.done,a||typeof l>"u")continue;let c=new Uint8Array(n.length+l.length);c.set(n),c.set(l,n.length),n=c;for(let d=o;d<n.length;d++){let f=LLt(n,d);if(f==null)continue;let p=o,m=n.slice(p,d);o=d+f.length,jNe(m,Yen)?.data===e?(r.enqueue(n.slice(0,p)),a=!0):(r.enqueue(n.slice(0,o)),n=n.slice(o),o=0)}}}catch(u){r.error(u)}finally{r.close(),s.releaseLock()}}})}function Yen(t){return t}});var LNe=v(db=>{"use strict";var Zen=db&&db.__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]}),Xen=db&&db.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Qen=db&&db.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Zen(e,t,r);return Xen(e,t),e};Object.defineProperty(db,"__esModule",{value:!0});db.SDKValidationError=void 0;db.formatZodError=DNe;var etn=Qen(Te()),NNe=class extends Error{constructor(e,r,n){super(`${e}: ${r}`),this.name="SDKValidationError",this.cause=r,this.rawValue=n,this.rawMessage=e}pretty(){return this.cause instanceof etn.ZodError?`${this.rawMessage}
${DNe(this.cause)}`:this.toString()}};db.SDKValidationError=NNe;function DNe(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(`${DNe(c,e+1)}`)})}}}return t.issues.length&&o("\u2514\u2500*"),n.slice(1)}});var ve=v(z5=>{"use strict";Object.defineProperty(z5,"__esModule",{value:!0});z5.parse=rtn;z5.safeParse=ntn;z5.collectExtraKeys=otn;var ttn=Te(),kLt=LNe(),FLt=Ig();function rtn(t,e,r){try{return e(t)}catch(n){throw n instanceof ttn.ZodError?new kLt.SDKValidationError(r,n,t):n}}function ntn(t,e,r){try{return(0,FLt.OK)(e(t))}catch(n){return(0,FLt.ERR)(new kLt.SDKValidationError(r,n,t))}}function otn(t,e,r){return t.transform(n=>{let o={},{shape:i}=t;for(let[a]of Object.entries(n)){if(a in i)continue;let s=n[a];typeof s>"u"||(o[a]=s,delete n[a])}return r&&Object.keys(o).length===0?n:{...n,[e]:o}})}});var ai=v(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});hc.jsonErr=stn;hc.json=utn;hc.textErr=ltn;hc.text=ctn;hc.bytesErr=dtn;hc.bytes=ftn;hc.streamErr=ptn;hc.stream=mtn;hc.sseErr=htn;hc.sse=gtn;hc.nilErr=ytn;hc.nil=btn;hc.fail=_tn;hc.match=vtn;hc.unpackHeaders=Qae;hc.discardResponseBody=zLt;var $Lt=MNe(),itn=U5(),BLt=L5(),qLt=SNe(),ULt=ve(),atn={json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function stn(t,e,r){return{...r,err:!0,enc:"json",codes:t,schema:e}}function utn(t,e,r){return{...r,enc:"json",codes:t,schema:e}}function ltn(t,e,r){return{...r,err:!0,enc:"text",codes:t,schema:e}}function ctn(t,e,r){return{...r,enc:"text",codes:t,schema:e}}function dtn(t,e,r){return{...r,err:!0,enc:"bytes",codes:t,schema:e}}function ftn(t,e,r){return{...r,enc:"bytes",codes:t,schema:e}}function ptn(t,e,r){return{...r,err:!0,enc:"stream",codes:t,schema:e}}function mtn(t,e,r){return{...r,enc:"stream",codes:t,schema:e}}function htn(t,e,r){return{...r,err:!0,enc:"sse",codes:t,schema:e}}function gtn(t,e,r){return{...r,enc:"sse",codes:t,schema:e}}function ytn(t,e,r){return{...r,err:!0,enc:"nil",codes:t,schema:e}}function btn(t,e,r){return{...r,enc:"nil",codes:t,schema:e}}function _tn(t){return{enc:"fail",codes:t}}function vtn(...t){return async function(r,n){let o,i;for(let l of t){let{codes:c}=l,d="ctype"in l?l.ctype:atn[l.enc];if(d&&(0,BLt.matchResponse)(r,c,d)){i=l;break}else if(!d&&(0,BLt.matchStatusCode)(r,c)){i=l;break}}if(!i){let l=await r.text();return[{ok:!1,error:new $Lt.SDKError("Unexpected API response status or content-type",r,l)},l]}let a=i.enc;switch(a){case"json":o=await r.json();break;case"bytes":o=new Uint8Array(await r.arrayBuffer());break;case"stream":o=r.body;break;case"text":o=await r.text();break;case"sse":o=r.body&&i.sseSentinel?(0,itn.discardSentinel)(r.body,i.sseSentinel):r.body;break;case"nil":o=await zLt(r);break;case"fail":o=await r.text();break;default:throw new Error(`Unsupported response type: ${a}`)}if(i.enc==="fail")return[{ok:!1,error:new $Lt.SDKError("API error occurred",r,typeof o=="string"?o:"")},o];let s=i.key||n?.resultKey,u;if("err"in i?u={...n?.extraFields,...i.hdrs?{Headers:Qae(r.headers)}:null,...(0,qLt.isPlainObject)(o)?o:null}:s?u={...n?.extraFields,...i.hdrs?{Headers:Qae(r.headers)}:null,[s]:o}:i.hdrs?u={...n?.extraFields,...i.hdrs?{Headers:Qae(r.headers)}:null,...(0,qLt.isPlainObject)(o)?o:null}:u=o,"err"in i){let l=(0,ULt.safeParse)(u,c=>i.schema.parse(c),"Response validation failed");return[l.ok?{ok:!1,error:l.value}:l,o]}else return[(0,ULt.safeParse)(u,l=>i.schema.parse(l),"Response validation failed"),o]}}var wtn=/, */;function Qae(t){let e={};for(let[r,n]of t.entries())e[r]=n.split(wtn);return e}async function zLt(t){let e=t.body?.getReader();if(e!=null)try{let r=!1;for(;!r;)r=(await e.read()).done}finally{e.releaseLock()}}});var Ue=v(dD=>{"use strict";Object.defineProperty(dD,"__esModule",{value:!0});dD.invariant=Stn;dD.remap=xtn;dD.combineSignals=Ctn;dD.abortSignalAny=HLt;dD.compactMap=Otn;var FNe=class extends Error{constructor(e){super(e),this.name="InvariantError"}};function Stn(t,e){if(!t)throw new FNe(e)}function xtn(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 Ctn(...t){let e=[];for(let r of t)r&&e.push(r);switch(e.length){case 0:case 1:return e[ Line truncated
`,appendChunkOverlapHeader:!0})).forEach(d=>{d.pageContent.trim()&&i.push({content:d.pageContent,fileInfo:l})})}return i}getDocHash(e){return(0,m1t.MD5)(e).toString()}async getFilesToIndex(e){let{inclusions:r,exclusions:n}=rf(),o=this.app.vault.getMarkdownFiles();if(e)return o.filter(c=>eu(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(!eu(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 ie([`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 Ix.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 Ix.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=ue(),o=bg(n.qaInclusions);o.length>0&&r.push(`Inclusions: ${o.join(", ")}`);let a=[...eie(this.app),...bg(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 Ix.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 Ix.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 Ix.Notice("Indexing cancelled");return}e.length>0?new Ix.Notice(`Indexing completed with ${e.length} errors. Check console for details.`):new Ix.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(),ue().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 g1t={};Cf(g1t,{default:()=>ma});var z8,ma,Mx=w(()=>{wT();pN();nr();z8=require("obsidian");rie();n1t();h1t();ma=class t{constructor(){this.embeddingsManager=Xs.getInstance(),this.dbOps=new eP(app),this.indexOps=new sie(app,this.dbOps,this.embeddingsManager),this.eventHandler=new nie(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={...ue()};let e=async()=>{let r=ue(),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())}};xa(()=>{this.initializationPromise=e()})}async initialize(){try{let e=3;for(;e>0;)try{let r=await this.embeddingsManager.getEmbeddingsAPI();await this.dbOps.initializeDB(r);break}catch(r){if(r instanceof Rr&&r.message.includes("Vault adapter not available")&&(e--,e>0)){await new Promise(n=>setTimeout(n,100));continue}new z8.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:",r);break}}catch(e){console.error("Failed to initialize vector store:",e)}}async waitForInitialization(){await this.initializationPromise}async indexVaultToVectorStore(e){return await this.waitForInitialization(),z8.Platform.isMobile&&ue().disableIndexOnMobile?(new z8.Notice("Indexing is disabled on mobile devices"),0):this.indexOps.indexVaultToVectorStore(e)}async clearIndex(){await this.waitForInitialization(),await this.dbOps.clearIndex(await this.embeddingsManager.getEmbeddingsAPI())}async garbageCollectVectorStore(){return await this.waitForInitialization(),this.dbOps.garbageCollect()}async getIndexedFiles(){return await this.waitForInitialization(),this.dbOps.getIndexedFiles()}async isIndexEmpty(){return await this.waitForInitialization(),await this.dbOps.isIndexEmpty()}async hasIndex(e){return await this.waitForInitialization(),this.dbOps.hasIndex(e)}onunload(){this.eventHandler.cleanup(),this.dbOps.onunload()}async getDbOps(){return await this.waitForInitialization(),this.dbOps}async getDb(){await this.waitForInitialization();let e=this.dbOps.getDb();if(!e)throw new Error("Database is not loaded. Please restart the plugin.");return e}async reindexFile(e){await this.waitForInitialization(),await this.indexOps.reindexFile(e)}}});function Kbe(t){return t.split("|")[1]==="copilot-plus"}function Line truncated
${n}`:"";super(`${e}: Status ${o} Content-Type ${i} Body ${a}`),this.rawResponse=r,this.body=n,this.statusCode=o,this.contentType=i,this.name="SDKError"}};tse.SDKError=RNe});var z5=v(U5=>{"use strict";Object.defineProperty(U5,"__esModule",{value:!0});U5.EventStream=void 0;U5.discardSentinel=etn;var B5=10,q5=13,BLt=new Set([B5,q5]),Xen=[new Uint8Array([q5,B5,q5,B5]),new Uint8Array([q5,q5]),new Uint8Array([B5,B5])],NNe=class{constructor(e){this.stream=e.stream,this.decoder=e.decoder}async*[Symbol.asyncIterator](){let e=this.stream.getReader(),r=new Uint8Array([]),n=0;try{for(;;){let{done:o,value:i}=await e.read();if(o)break;let a=new Uint8Array(r.length+i.length);a.set(r),a.set(i,r.length),r=a;for(let s=n;s<r.length;s++){let u=qLt(r,s);if(u==null)continue;let l=r.slice(n,s);n=s+u.length;let c=DNe(l,this.decoder);c!=null&&(yield c)}n>0&&(r=r.slice(n),n=0)}if(r.length>0){let o=DNe(r,this.decoder);o!=null&&(yield o)}}catch(o){if(o instanceof Error&&o.name==="AbortError")return;throw o}finally{e.releaseLock()}}};U5.EventStream=NNe;function qLt(t,e){let r=t[e],n=t[e+1];if(r==null||n==null||!BLt.has(r)||!BLt.has(n))return null;for(let o of Xen){let i=Qen(e,t,o);if(i!=null)return i}return null}function Qen(t,e,r){if(r.length>e.length-t)return null;for(let n=0;n<r.length;n++)if(e[t+n]!==r[n])return null;return r}function DNe(t,e){if(!t.length)return null;let o=new TextDecoder().decode(t).split(/\r?\n|\r/g),i=!1,a={};for(let s of o){if(!s)continue;let u=s.indexOf(":");if(u===0)continue;let l=u>0?s.substring(0,u):"",c=u>0?s.substring(u+1):"";switch(c.charAt(0)===" "&&(c=c.substring(1)),l){case"event":{i=!0,a.event=c;break}case"data":{i=!0,a.data??(a.data=""),a.data+=c+`
`;break}case"id":{i=!0,a.id=c;break}case"retry":{let d=parseInt(c,10);Number.isNaN(d)||(i=!0,a.retry=d);break}}}return i?(a.data!=null&&(a.data=a.data.slice(0,-1)),e(a)):null}function etn(t,e){return new ReadableStream({async start(r){let n=new Uint8Array([]),o=0,i=!1,a=!1,s=t.getReader();try{for(;!i;){let u=await s.read(),l=u.value;if(i=i||u.done,a||typeof l>"u")continue;let c=new Uint8Array(n.length+l.length);c.set(n),c.set(l,n.length),n=c;for(let d=o;d<n.length;d++){let f=qLt(n,d);if(f==null)continue;let p=o,m=n.slice(p,d);o=d+f.length,DNe(m,ttn)?.data===e?(r.enqueue(n.slice(0,p)),a=!0):(r.enqueue(n.slice(0,o)),n=n.slice(o),o=0)}}}catch(u){r.error(u)}finally{r.close(),s.releaseLock()}}})}function ttn(t){return t}});var kNe=v(db=>{"use strict";var rtn=db&&db.__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]}),ntn=db&&db.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),otn=db&&db.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&rtn(e,t,r);return ntn(e,t),e};Object.defineProperty(db,"__esModule",{value:!0});db.SDKValidationError=void 0;db.formatZodError=FNe;var itn=otn(Te()),LNe=class extends Error{constructor(e,r,n){super(`${e}: ${r}`),this.name="SDKValidationError",this.cause=r,this.rawValue=n,this.rawMessage=e}pretty(){return this.cause instanceof itn.ZodError?`${this.rawMessage}
${FNe(this.cause)}`:this.toString()}};db.SDKValidationError=LNe;function FNe(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(`${FNe(c,e+1)}`)})}}}return t.issues.length&&o("\u2514\u2500*"),n.slice(1)}});var ve=v(H5=>{"use strict";Object.defineProperty(H5,"__esModule",{value:!0});H5.parse=stn;H5.safeParse=utn;H5.collectExtraKeys=ltn;var atn=Te(),zLt=kNe(),ULt=Ig();function stn(t,e,r){try{return e(t)}catch(n){throw n instanceof atn.ZodError?new zLt.SDKValidationError(r,n,t):n}}function utn(t,e,r){try{return(0,ULt.OK)(e(t))}catch(n){return(0,ULt.ERR)(new zLt.SDKValidationError(r,n,t))}}function ltn(t,e,r){return t.transform(n=>{let o={},{shape:i}=t;for(let[a]of Object.entries(n)){if(a in i)continue;let s=n[a];typeof s>"u"||(o[a]=s,delete n[a])}return r&&Object.keys(o).length===0?n:{...n,[e]:o}})}});var ai=v(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});hc.jsonErr=ftn;hc.json=ptn;hc.textErr=mtn;hc.text=htn;hc.bytesErr=gtn;hc.bytes=ytn;hc.streamErr=btn;hc.stream=_tn;hc.sseErr=vtn;hc.sse=wtn;hc.nilErr=Stn;hc.nil=xtn;hc.fail=Ctn;hc.match=Otn;hc.unpackHeaders=rse;hc.discardResponseBody=GLt;var HLt=jNe(),ctn=z5(),VLt=F5(),WLt=CNe(),KLt=ve(),dtn={json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function ftn(t,e,r){return{...r,err:!0,enc:"json",codes:t,schema:e}}function ptn(t,e,r){return{...r,enc:"json",codes:t,schema:e}}function mtn(t,e,r){return{...r,err:!0,enc:"text",codes:t,schema:e}}function htn(t,e,r){return{...r,enc:"text",codes:t,schema:e}}function gtn(t,e,r){return{...r,err:!0,enc:"bytes",codes:t,schema:e}}function ytn(t,e,r){return{...r,enc:"bytes",codes:t,schema:e}}function btn(t,e,r){return{...r,err:!0,enc:"stream",codes:t,schema:e}}function _tn(t,e,r){return{...r,enc:"stream",codes:t,schema:e}}function vtn(t,e,r){return{...r,err:!0,enc:"sse",codes:t,schema:e}}function wtn(t,e,r){return{...r,enc:"sse",codes:t,schema:e}}function Stn(t,e,r){return{...r,err:!0,enc:"nil",codes:t,schema:e}}function xtn(t,e,r){return{...r,enc:"nil",codes:t,schema:e}}function Ctn(t){return{enc:"fail",codes:t}}function Otn(...t){return async function(r,n){let o,i;for(let l of t){let{codes:c}=l,d="ctype"in l?l.ctype:dtn[l.enc];if(d&&(0,VLt.matchResponse)(r,c,d)){i=l;break}else if(!d&&(0,VLt.matchStatusCode)(r,c)){i=l;break}}if(!i){let l=await r.text();return[{ok:!1,error:new HLt.SDKError("Unexpected API response status or content-type",r,l)},l]}let a=i.enc;switch(a){case"json":o=await r.json();break;case"bytes":o=new Uint8Array(await r.arrayBuffer());break;case"stream":o=r.body;break;case"text":o=await r.text();break;case"sse":o=r.body&&i.sseSentinel?(0,ctn.discardSentinel)(r.body,i.sseSentinel):r.body;break;case"nil":o=await GLt(r);break;case"fail":o=await r.text();break;default:throw new Error(`Unsupported response type: ${a}`)}if(i.enc==="fail")return[{ok:!1,error:new HLt.SDKError("API error occurred",r,typeof o=="string"?o:"")},o];let s=i.key||n?.resultKey,u;if("err"in i?u={...n?.extraFields,...i.hdrs?{Headers:rse(r.headers)}:null,...(0,WLt.isPlainObject)(o)?o:null}:s?u={...n?.extraFields,...i.hdrs?{Headers:rse(r.headers)}:null,[s]:o}:i.hdrs?u={...n?.extraFields,...i.hdrs?{Headers:rse(r.headers)}:null,...(0,WLt.isPlainObject)(o)?o:null}:u=o,"err"in i){let l=(0,KLt.safeParse)(u,c=>i.schema.parse(c),"Response validation failed");return[l.ok?{ok:!1,error:l.value}:l,o]}else return[(0,KLt.safeParse)(u,l=>i.schema.parse(l),"Response validation failed"),o]}}var Ptn=/, */;function rse(t){let e={};for(let[r,n]of t.entries())e[r]=n.split(Ptn);return e}async function GLt(t){let e=t.body?.getReader();if(e!=null)try{let r=!1;for(;!r;)r=(await e.read()).done}finally{e.releaseLock()}}});var Ue=v(fD=>{"use strict";Object.defineProperty(fD,"__esModule",{value:!0});fD.invariant=Etn;fD.remap=Ttn;fD.combineSignals=Atn;fD.abortSignalAny=JLt;fD.compactMap=Itn;var $Ne=class extends Error{constructor(e){super(e),this.name="InvariantError"}};function Etn(t,e){if(!t)throw new $Ne(e)}function Ttn(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 Atn(...t){let e=[];for(let r of t)r&&e.push(r);switch(e.length){case 0:case 1:return e[ Line truncated
]))`;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 Kue=v(Wue=>{"use strict";Object.defineProperty(Wue,"__esModule",{value:!0});Wue.parseRecordDef=void 0;var rW=Te(),x2t=ml(),Vhn=Vue(),Whn=Fue();function Khn(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===rW.ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:(0,x2t.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:(0,x2t.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===rW.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=(0,Vhn.parseStringDef)(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===rW.ZodFirstPartyTypeKind.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===rW.ZodFirstPartyTypeKind.ZodBranded&&t.keyType._def.type._def.typeName===rW.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=(0,Whn.parseBrandedDef)(t.keyType._def,e);return{...r,propertyNames:o}}}return r}Wue.parseRecordDef=Khn});var BDe=v(Gue=>{"use strict";Object.defineProperty(Gue,"__esModule",{value:!0});Gue.parseMapDef=void 0;var C2t=ml(),Ghn=Kue();function Jhn(t,e){if(e.mapStrategy==="record")return(0,Ghn.parseRecordDef)(t,e);let r=(0,C2t.parseDef)(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=(0,C2t.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}}}Gue.parseMapDef=Jhn});var qDe=v(Jue=>{"use strict";Object.defineProperty(Jue,"__esModule",{value:!0});Jue.parseNativeEnumDef=void 0;function Yhn(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}}Jue.parseNativeEnumDef=Yhn});var UDe=v(Yue=>{"use strict";Object.defineProperty(Yue,"__esModule",{value:!0});Yue.parseNeverDef=void 0;function Zhn(){return{not:{}}}Yue.parseNeverDef=Zhn});var zDe=v(Zue=>{"use strict";Object.defineProperty(Zue,"__esModule",{value:!0});Zue.parseNullDef=void 0;function Xhn(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}Zue.parseNullDef=Xhn});var Xue=v(GI=>{"use strict";Object.defineProperty(GI,"__esModule",{value:!0});GI.parseUnionDef=GI.primitiveMappings=void 0;var Qhn=ml();GI.primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function egn(t,e){if(e.target==="openApi3")return O2t(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in GI.primitiveMappings&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=GI.primitiveMappings[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((i,a,s)=>s.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return O2t(t,e)}GI.parseUnionDef=egn;var O2t=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>(0,Qhn.parseDef)(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}});var HDe=v(Que=>{"use strict";Object.defineProperty(Que,"__esModule",{value:!0});Que.parseNullableDef=void 0;var P2t=ml(),E2t=Xue();function tgn(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"?{type:E2t.primitiveMappings[t.innerType._def.typeName],nullable:!0}:{type:[E2t.primitiveMappings[t.innerType._ Line truncated
`),r=[],n="",o="",i="";for(let a of e)a.startsWith("**user**:")||a.startsWith("**ai**:")?(n&&o&&r.push({sender:n===Pi?Pi:e_,message:o.trim(),isVisible:!0,timestamp:i?Yhe(i):null}),n=a.startsWith("**user**:")?Pi:e_,o=a.substring(a.indexOf(":")+1).trim(),i=""):a.startsWith("[Timestamp:")?i=a.substring(11,a.length-1).trim():o+=`
`+a;return n&&o&&r.push({sender:n===Pi?Pi:e_,message:o.trim(),isVisible:!0,timestamp:i?Yhe(i):null}),r}async function _N(t,e){await e.clearChatMemory();for(let r=0;r<t.length-1;r++){let n=t[r];if(n.sender===Pi){let o=t[r+1];o?.sender===e_&&await e.getMemory().saveContext({input:n.message},{output:o.message})}}}$r();yo();yo();Cn();var vN=require("obsidian"),Mx=class{static async isImageUrl(e,r){try{let n,o=!1;try{let i=new URL(e),a=i.pathname,s=a.lastIndexOf("."),u=a.lastIndexOf("/");if(s>u&&s>-1&&(n=a.substring(s+1).toLowerCase()),n&&!this.IMAGE_EXTENSIONS.some(c=>c.toLowerCase()===`.${n}`))return fe(`Unsupported image format from URL path: .${n}. Supported formats: ${this.IMAGE_EXTENSIONS.join(", ")}`,e),!1;try{let c=(await Us(e,{method:"HEAD",headers:{}})).headers.get("content-type");return c?.startsWith("image/")?!0:(console.warn(`HEAD request succeeded for ${e} but Content-Type (${c}) is not image/*.`),!1)}catch(l){console.warn(`HEAD request failed for URL: ${e}. Proceeding to heuristic check.`,l);let c=i.searchParams,f=[c.has("w")||c.has("width"),c.has("h")||c.has("height"),c.has("format"),c.has("fit"),c.has("quality"),i.pathname.includes("/image/"),i.pathname.includes("/images/"),i.pathname.includes("/img/"),c.has("auto"),c.has("crop")].filter(Boolean).length;return f>=2?(fe(`Identified as image based on URL heuristics (indicator count: ${f}): ${e}`),!0):!1}}catch{o=!0;let i=e.lastIndexOf(".");if(i>-1)n=e.substring(i+1).toLowerCase();else return!1}if(o)if(n&&this.IMAGE_EXTENSIONS.some(i=>i.toLowerCase()===`.${n}`)){let i=r.getAbstractFileByPath(e);return i instanceof vN.TFile?i.stat.size>this.MAX_IMAGE_SIZE?(fe(`Vault file too large: ${i.stat.size} bytes for path: ${e}`),!1):!0:(fe(`File with image extension not found in vault: ${e}.`),!1)}else return n&&fe(`Unsupported image format for potential vault path: .${n}. Supported formats: ${this.IMAGE_EXTENSIONS.join(", ")}`,e),!1;return fe(`Could not determine image status for URL/path: ${e}`),!1}catch(n){return fe(`Unexpected error in isImageUrl for "${e}":`,n),!1}}static async handleVaultImage(e,r){try{if(e.stat.size>this.MAX_IMAGE_SIZE)return fe(`Image too large: ${e.stat.size} bytes, skipping: ${e.path}`),null;let n=await r.readBinary(e),o=await this.getMimeType(n,e.extension);if(!o.startsWith("image/"))return fe(`Invalid MIME type: ${o}, skipping: ${e.path}`),null;let a=Buffer.from(n).toString("base64");return`data:${o};base64,${a}`}catch(n){return fe("Error processing vault image:",n),null}}static async handleWebImage(e){try{let r=await Us(e,{method:"GET",headers:{}});if(!r.ok)return fe(`Failed to fetch image: ${r.statusText}, URL: ${e}`),null;let n=r.headers.get("content-type");if(!n?.startsWith("image/"))return fe(`Invalid content type: ${n}, URL: ${e}`),null;let o=await r.arrayBuffer();if(o.byteLength>this.MAX_IMAGE_SIZE)return fe(`Image too large: ${o.byteLength} bytes, URL: ${e}`),null;let a=Buffer.from(o).toString("base64");return`data:${n};base64,${a}`}catch(r){return fe("Error converting web image to base64:",r),null}}static async handleLocalImage(e,r){try{let n=decodeURIComponent(e.replace("app://","")),o=r.getAbstractFileByPath(n);if(!o||!(o instanceof vN.TFile))return fe(`Local image not found: ${n}`),null;if(o.stat.size>this.MAX_IMAGE_SIZE)return fe(`Image too large: ${o.stat.size} bytes, path: ${n}`),null;let i=await r.readBinary(o),a=await this.getMimeType(i,o.extension);if(!a.startsWith("image/"))return fe(`Invalid MIME type: ${a}, path: ${n}`),null;let u=Buffer.from(i).toString("base64");return`data:${a};base64,${u}`}catch(n){return fe("Error processing local image:",n),null}}static async imageToBase64(e,r){if(e.startsWith("data:"))return e;if(e.startsWith("attachment:")){let o=e.substring(11),i=r.getAbstractFileByPath(o);return i instanceof vN.TFile?await this.handleVaultImage(i,r):(console.warn(`Could not find attachment file in vault: ${o}`),null)}if(e.startsWith("app://"))return await this.handleLocalImage(e,r);let n=r.getAbstractFileByPath(e);return n instanceof vN.TFile?await this.handleVaultImage(n,r):await this.handleWebImage(e)}static async convertToBase64(e,r){let n=await this.imageToBase64(e,r);return n?{type:"image_url",image_url:{url:n}}:(fe(`Failed to convert image to base64: ${e}`),null)}static async getMimeType(e,r){let n=new Uint8Array(e.slice(0,4));if(n[0]===255&&n[1]===216)return"image/jpeg";if(n[0]===137&&n[1]===80)return"image/png";if(n[0]===71&&n[1]===73)return"image/gif";if(n[0]===82&&n[1]===73)return"image/webp";if(n[0]===66&&n[1]===77)return"image/bmp";if(n[0]===60&&n[1]===115)throw new Error("SVG files are not supported");let o=this.MIME_TYPES[r.toLowerCase()];if(!o){let i=`Unsupported image extension: ${r}`;throw fe(i),new Error(i)}return o}};Mx.IMAGE_EXTENSIONS=[".jpg",".jpeg",".png",".gif",".webp",".bmp"],Mx.MAX_IMAGE_SIZE=3*1024*1024,Mx.MIME_TYPES={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp"};var wN=class t{static async processUr Line truncated
]`;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 Yue=v(Jue=>{"use strict";Object.defineProperty(Jue,"__esModule",{value:!0});Jue.parseRecordDef=void 0;var nW=Te(),T2t=ml(),Yhn=Gue(),Zhn=Bue();function Xhn(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===nW.ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:(0,T2t.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:(0,T2t.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===nW.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=(0,Yhn.parseStringDef)(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===nW.ZodFirstPartyTypeKind.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===nW.ZodFirstPartyTypeKind.ZodBranded&&t.keyType._def.type._def.typeName===nW.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=(0,Zhn.parseBrandedDef)(t.keyType._def,e);return{...r,propertyNames:o}}}return r}Jue.parseRecordDef=Xhn});var UDe=v(Zue=>{"use strict";Object.defineProperty(Zue,"__esModule",{value:!0});Zue.parseMapDef=void 0;var A2t=ml(),Qhn=Yue();function egn(t,e){if(e.mapStrategy==="record")return(0,Qhn.parseRecordDef)(t,e);let r=(0,A2t.parseDef)(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=(0,A2t.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}}}Zue.parseMapDef=egn});var zDe=v(Xue=>{"use strict";Object.defineProperty(Xue,"__esModule",{value:!0});Xue.parseNativeEnumDef=void 0;function tgn(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}}Xue.parseNativeEnumDef=tgn});var HDe=v(Que=>{"use strict";Object.defineProperty(Que,"__esModule",{value:!0});Que.parseNeverDef=void 0;function rgn(){return{not:{}}}Que.parseNeverDef=rgn});var VDe=v(ele=>{"use strict";Object.defineProperty(ele,"__esModule",{value:!0});ele.parseNullDef=void 0;function ngn(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}ele.parseNullDef=ngn});var tle=v(GI=>{"use strict";Object.defineProperty(GI,"__esModule",{value:!0});GI.parseUnionDef=GI.primitiveMappings=void 0;var ogn=ml();GI.primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ign(t,e){if(e.target==="openApi3")return I2t(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in GI.primitiveMappings&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=GI.primitiveMappings[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((i,a,s)=>s.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return I2t(t,e)}GI.parseUnionDef=ign;var I2t=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>(0,ogn.parseDef)(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}});var WDe=v(rle=>{"use strict";Object.defineProperty(rle,"__esModule",{value:!0});rle.parseNullableDef=void 0;var M2t=ml(),R2t=tle();function agn(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"?{type:R2t.primitiveMappings[t.innerType._def.typeName],nullable:!0}:{type:[R2t.primitiveMappings[t.innerType._ Line truncated
`),r=[],n="",o="",i="";for(let a of e)a.startsWith("**user**:")||a.startsWith("**ai**:")?(n&&o&&r.push({sender:n===Pi?Pi:e_,message:o.trim(),isVisible:!0,timestamp:i?Qhe(i):null}),n=a.startsWith("**user**:")?Pi:e_,o=a.substring(a.indexOf(":")+1).trim(),i=""):a.startsWith("[Timestamp:")?i=a.substring(11,a.length-1).trim():o+=`
`+a;return n&&o&&r.push({sender:n===Pi?Pi:e_,message:o.trim(),isVisible:!0,timestamp:i?Qhe(i):null}),r}async function vN(t,e){await e.clearChatMemory();for(let r=0;r<t.length-1;r++){let n=t[r];if(n.sender===Pi){let o=t[r+1];o?.sender===e_&&await e.getMemory().saveContext({input:n.message},{output:o.message})}}}$r();yo();yo();yn();var wN=require("obsidian"),Rx=class{static async isImageUrl(e,r){try{let n,o=!1;try{let i=new URL(e),a=i.pathname,s=a.lastIndexOf("."),u=a.lastIndexOf("/");if(s>u&&s>-1&&(n=a.substring(s+1).toLowerCase()),n&&!this.IMAGE_EXTENSIONS.some(c=>c.toLowerCase()===`.${n}`))return fe(`Unsupported image format from URL path: .${n}. Supported formats: ${this.IMAGE_EXTENSIONS.join(", ")}`,e),!1;try{let c=(await Us(e,{method:"HEAD",headers:{}})).headers.get("content-type");return c?.startsWith("image/")?!0:(console.warn(`HEAD request succeeded for ${e} but Content-Type (${c}) is not image/*.`),!1)}catch(l){console.warn(`HEAD request failed for URL: ${e}. Proceeding to heuristic check.`,l);let c=i.searchParams,f=[c.has("w")||c.has("width"),c.has("h")||c.has("height"),c.has("format"),c.has("fit"),c.has("quality"),i.pathname.includes("/image/"),i.pathname.includes("/images/"),i.pathname.includes("/img/"),c.has("auto"),c.has("crop")].filter(Boolean).length;return f>=2?(fe(`Identified as image based on URL heuristics (indicator count: ${f}): ${e}`),!0):!1}}catch{o=!0;let i=e.lastIndexOf(".");if(i>-1)n=e.substring(i+1).toLowerCase();else return!1}if(o)if(n&&this.IMAGE_EXTENSIONS.some(i=>i.toLowerCase()===`.${n}`)){let i=r.getAbstractFileByPath(e);return i instanceof wN.TFile?i.stat.size>this.MAX_IMAGE_SIZE?(fe(`Vault file too large: ${i.stat.size} bytes for path: ${e}`),!1):!0:(fe(`File with image extension not found in vault: ${e}.`),!1)}else return n&&fe(`Unsupported image format for potential vault path: .${n}. Supported formats: ${this.IMAGE_EXTENSIONS.join(", ")}`,e),!1;return fe(`Could not determine image status for URL/path: ${e}`),!1}catch(n){return fe(`Unexpected error in isImageUrl for "${e}":`,n),!1}}static async handleVaultImage(e,r){try{if(e.stat.size>this.MAX_IMAGE_SIZE)return fe(`Image too large: ${e.stat.size} bytes, skipping: ${e.path}`),null;let n=await r.readBinary(e),o=await this.getMimeType(n,e.extension);if(!o.startsWith("image/"))return fe(`Invalid MIME type: ${o}, skipping: ${e.path}`),null;let a=Buffer.from(n).toString("base64");return`data:${o};base64,${a}`}catch(n){return fe("Error processing vault image:",n),null}}static async handleWebImage(e){try{let r=await Us(e,{method:"GET",headers:{}});if(!r.ok)return fe(`Failed to fetch image: ${r.statusText}, URL: ${e}`),null;let n=r.headers.get("content-type");if(!n?.startsWith("image/"))return fe(`Invalid content type: ${n}, URL: ${e}`),null;let o=await r.arrayBuffer();if(o.byteLength>this.MAX_IMAGE_SIZE)return fe(`Image too large: ${o.byteLength} bytes, URL: ${e}`),null;let a=Buffer.from(o).toString("base64");return`data:${n};base64,${a}`}catch(r){return fe("Error converting web image to base64:",r),null}}static async handleLocalImage(e,r){try{let n=decodeURIComponent(e.replace("app://","")),o=r.getAbstractFileByPath(n);if(!o||!(o instanceof wN.TFile))return fe(`Local image not found: ${n}`),null;if(o.stat.size>this.MAX_IMAGE_SIZE)return fe(`Image too large: ${o.stat.size} bytes, path: ${n}`),null;let i=await r.readBinary(o),a=await this.getMimeType(i,o.extension);if(!a.startsWith("image/"))return fe(`Invalid MIME type: ${a}, path: ${n}`),null;let u=Buffer.from(i).toString("base64");return`data:${a};base64,${u}`}catch(n){return fe("Error processing local image:",n),null}}static async imageToBase64(e,r){if(e.startsWith("data:"))return e;if(e.startsWith("attachment:")){let o=e.substring(11),i=r.getAbstractFileByPath(o);return i instanceof wN.TFile?await this.handleVaultImage(i,r):(console.warn(`Could not find attachment file in vault: ${o}`),null)}if(e.startsWith("app://"))return await this.handleLocalImage(e,r);let n=r.getAbstractFileByPath(e);return n instanceof wN.TFile?await this.handleVaultImage(n,r):await this.handleWebImage(e)}static async convertToBase64(e,r){let n=await this.imageToBase64(e,r);return n?{type:"image_url",image_url:{url:n}}:(fe(`Failed to convert image to base64: ${e}`),null)}static async getMimeType(e,r){let n=new Uint8Array(e.slice(0,4));if(n[0]===255&&n[1]===216)return"image/jpeg";if(n[0]===137&&n[1]===80)return"image/png";if(n[0]===71&&n[1]===73)return"image/gif";if(n[0]===82&&n[1]===73)return"image/webp";if(n[0]===66&&n[1]===77)return"image/bmp";if(n[0]===60&&n[1]===115)throw new Error("SVG files are not supported");let o=this.MIME_TYPES[r.toLowerCase()];if(!o){let i=`Unsupported image extension: ${r}`;throw fe(i),new Error(i)}return o}};Rx.IMAGE_EXTENSIONS=[".jpg",".jpeg",".png",".gif",".webp",".bmp"],Rx.MAX_IMAGE_SIZE=3*1024*1024,Rx.MIME_TYPES={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp"};var SN=class t{static async processUr Line truncated
${e.join(`
`)}`)}};mg();Cn();var Cq=class t{constructor(){this.mentions=new Map,this.brevilabsClient=Fi.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).filter(n=>!gVe(n))}async processUrl(e){try{return await this.brevilabsClient.url4llm(e)}catch(r){return console.error(`Error processing URL ${e}:`,r),{response:e,elapsed_time_ms:0}}}async processUrls(e){let r=this.extractUrls(e),n="",o=[];if(r.length===0)return{urlContext:"",imageUrls:[]};let i=r.map(async s=>{if(await Mx.isImageUrl(s,app.vault))return o.push(s),null;if(!this.mentions.has(s)){let u=await this.processUrl(s);this.mentions.set(s,{type:"url",original:s,processed:u.response})}return this.mentions.get(s)});return(await Promise.all(i)).forEach(s=>{s?.processed&&(n+=`
`)}`)}};mg();yn();var Oq=class t{constructor(){this.mentions=new Map,this.brevilabsClient=Fi.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).filter(n=>!bVe(n))}async processUrl(e){try{return await this.brevilabsClient.url4llm(e)}catch(r){return console.error(`Error processing URL ${e}:`,r),{response:e,elapsed_time_ms:0}}}async processUrls(e){let r=this.extractUrls(e),n="",o=[];if(r.length===0)return{urlContext:"",imageUrls:[]};let i=r.map(async s=>{if(await Rx.isImageUrl(s,app.vault))return o.push(s),null;if(!this.mentions.has(s)){let u=await this.processUrl(s);this.mentions.set(s,{type:"url",original:s,processed:u.response})}return this.mentions.get(s)});return(await Promise.all(i)).forEach(s=>{s?.processed&&(n+=`
Content from ${s.original}:
${s.processed}`)}),{urlContext:n,imageUrls:o}}getMentions(){return this.mentions}clearMentions(){this.mentions.clear()}};_g();nr();yo();var C1t=F(vq()),sie=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)||(ie("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,C1t.MD5)(r).toString();return ie("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)){ie("Cache hit for PDF:",e.path);let o=await app.vault.adapter.read(n);return JSON.parse(o)}return ie("Cache miss for PDF:",e.path),null}catch(r){return fe("Error reading from PDF cache:",r),null}}async set(e,r){try{await this.ensureCacheDir();let n=this.getCacheKey(e),o=this.getCachePath(n);ie("Caching PDF response for:",e.path),await app.vault.adapter.write(o,JSON.stringify(r))}catch(n){fe("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);ie("Clearing PDF cache, removing files:",e.files.length);for(let r of e.files)await app.vault.adapter.remove(r)}}catch(e){fe("Error clearing PDF cache:",e)}}};yo();function SN(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 O1t(t){let r=(t?.message||t?.toString()||"").match(/Try again in ([\d\w\s]+)/);return r?r[1]:"some time"}var T1t=require("obsidian");var P1t=require("obsidian");var lie,E1t,uie=class{constructor(e){this.vault=e;pUe(this,lie)}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 P1t.TFile?await this.vault.cachedRead(l):"";return{...u,content:c}}return u.type==="text"?{...u,content:u.text??""}:{...u,content:""}})),a=[...o];mUe(this,lie,E1t).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:
${s.processed}`)}),{urlContext:n,imageUrls:o}}getMentions(){return this.mentions}clearMentions(){this.mentions.clear()}};_g();nr();yo();var A1t=F(wq()),cie=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)||(ie("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,A1t.MD5)(r).toString();return ie("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)){ie("Cache hit for PDF:",e.path);let o=await app.vault.adapter.read(n);return JSON.parse(o)}return ie("Cache miss for PDF:",e.path),null}catch(r){return fe("Error reading from PDF cache:",r),null}}async set(e,r){try{await this.ensureCacheDir();let n=this.getCacheKey(e),o=this.getCachePath(n);ie("Caching PDF response for:",e.path),await app.vault.adapter.write(o,JSON.stringify(r))}catch(n){fe("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);ie("Clearing PDF cache, removing files:",e.files.length);for(let r of e.files)await app.vault.adapter.remove(r)}}catch(e){fe("Error clearing PDF cache:",e)}}};yo();function xN(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 I1t(t){let r=(t?.message||t?.toString()||"").match(/Try again in ([\d\w\s]+)/);return r?r[1]:"some time"}var j1t=require("obsidian");var M1t=require("obsidian");var fie,R1t,die=class{constructor(e){this.vault=e;hUe(this,fie)}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 M1t.TFile?await this.vault.cachedRead(l):"";return{...u,content:c}}return u.type==="text"?{...u,content:u.text??""}:{...u,content:""}})),a=[...o];gUe(this,fie,R1t).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:
@@ -557,9 +557,9 @@ 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}};lie=new WeakSet,E1t=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 ZRe=class{constructor(){this.supportedExtensions=["md"]}async parseFile(e,r){return await r.read(e)}},cie=class{constructor(e){this.supportedExtensions=["pdf"];this.brevilabsClient=e,this.pdfCache=sie.getInstance()}async parseFile(e,r){try{ie("Parsing PDF file:",e.path);let n=await this.pdfCache.get(e);if(n)return ie("Using cached PDF content for:",e.path),n.response;let o=await r.readBinary(e);ie("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 fe(`Error extracting content from PDF ${e.path}:`,n),`[Error: Could not extract content from PDF ${e.basename}]`}}async clearCache(){ie("Clearing PDF cache"),await this.pdfCache.clear()}},XRe=class{constructor(){this.supportedExtensions=["canvas"]}async parseFile(e,r){try{ie("Parsing Canvas file:",e.path);let n=new uie(r),o=await n.load(e);return n.buildPrompt(o)}catch(n){return fe(`Error parsing Canvas file ${e.path}:`,n),`[Error: Could not parse Canvas file ${e.basename}]`}}},Oq=class Oq{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=tb.getInstance(),this.currentProject=r}static resetRateLimitNoticeTimer(){Oq.lastRateLimitNoticeTime=0}async parseFile(e,r){try{if(ie(`[Docs4LLMParser] Project ${this.currentProject?.name}: Parsing ${e.extension} file: ${e.path}`),!this.currentProject)throw fe("[Docs4LLMParser] No project context for parsing file: ",e.path),new Error("No project context provided for file parsing");let n=await this.projectContextCache.getFileContext(this.currentProject,e.path);if(n)return ie(`[Docs4LLMParser] Project ${this.currentProject.name}: Using cached content for: ${e.path}`),n;ie(`[Docs4LLMParser] Project ${this.currentProject.name}: Cache miss for: ${e.path}. Proceeding to API call.`);let o=await r.readBinary(e);ie(`[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(`
`,o}};fie=new WeakSet,R1t=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 QRe=class{constructor(){this.supportedExtensions=["md"]}async parseFile(e,r){return await r.read(e)}},pie=class{constructor(e){this.supportedExtensions=["pdf"];this.brevilabsClient=e,this.pdfCache=cie.getInstance()}async parseFile(e,r){try{ie("Parsing PDF file:",e.path);let n=await this.pdfCache.get(e);if(n)return ie("Using cached PDF content for:",e.path),n.response;let o=await r.readBinary(e);ie("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 fe(`Error extracting content from PDF ${e.path}:`,n),`[Error: Could not extract content from PDF ${e.basename}]`}}async clearCache(){ie("Clearing PDF cache"),await this.pdfCache.clear()}},e1e=class{constructor(){this.supportedExtensions=["canvas"]}async parseFile(e,r){try{ie("Parsing Canvas file:",e.path);let n=new die(r),o=await n.load(e);return n.buildPrompt(o)}catch(n){return fe(`Error parsing Canvas file ${e.path}:`,n),`[Error: Could not parse Canvas file ${e.basename}]`}}},Pq=class Pq{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=tb.getInstance(),this.currentProject=r}static resetRateLimitNoticeTimer(){Pq.lastRateLimitNoticeTime=0}async parseFile(e,r){try{if(ie(`[Docs4LLMParser] Project ${this.currentProject?.name}: Parsing ${e.extension} file: ${e.path}`),!this.currentProject)throw fe("[Docs4LLMParser] No project context for parsing file: ",e.path),new Error("No project context provided for file parsing");let n=await this.projectContextCache.getFileContext(this.currentProject,e.path);if(n)return ie(`[Docs4LLMParser] Project ${this.currentProject.name}: Using cached content for: ${e.path}`),n;ie(`[Docs4LLMParser] Project ${this.currentProject.name}: Cache miss for: ${e.path}. Proceeding to API call.`);let o=await r.readBinary(e);ie(`[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),ie(`[Docs4LLMParser] Project ${this.currentProject.name}: Successfully processed and cached: ${e.path}`),a}catch(n){throw fe(`[Docs4LLMParser] Project ${this.currentProject?.name}: Error processing file ${e.path}:`,n),SN(n)&&this.showRateLimitNotice(n),n}}showRateLimitNotice(e){let r=Date.now();if(r-Oq.lastRateLimitNoticeTime<6e4)return;Oq.lastRateLimitNoticeTime=r;let n=O1t(e);new T1t.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(){ie("Cache clearing is now handled at the project level")}};Oq.lastRateLimitNoticeTime=0;var z8=Oq,oI=class{constructor(e,r,n=!1,o=null){this.parsers=new Map;this.isProjectMode=n,this.currentProject=o,this.registerParser(new ZRe),this.registerParser(new z8(e,o)),n||this.registerParser(new cie(e)),this.registerParser(new XRe)}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 cie&&await e.clearCache()}};Cn();var vW=require("obsidian");mg();Cl();Fd();$r();Cl();Cn();async function die(t,e){let r=`Given the following conversation and a follow up question,
`)}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),ie(`[Docs4LLMParser] Project ${this.currentProject.name}: Successfully processed and cached: ${e.path}`),a}catch(n){throw fe(`[Docs4LLMParser] Project ${this.currentProject?.name}: Error processing file ${e.path}:`,n),xN(n)&&this.showRateLimitNotice(n),n}}showRateLimitNotice(e){let r=Date.now();if(r-Pq.lastRateLimitNoticeTime<6e4)return;Pq.lastRateLimitNoticeTime=r;let n=I1t(e);new j1t.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(){ie("Cache clearing is now handled at the project level")}};Pq.lastRateLimitNoticeTime=0;var H8=Pq,oI=class{constructor(e,r,n=!1,o=null){this.parsers=new Map;this.isProjectMode=n,this.currentProject=o,this.registerParser(new QRe),this.registerParser(new H8(e,o)),n||this.registerParser(new pie(e)),this.registerParser(new e1e)}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 pie&&await e.clearCache()}};yn();var wW=require("obsidian");mg();Cl();Fd();$r();Cl();yn();async function mie(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.
@@ -570,59 +570,59 @@ When describing this canvas, please:
{chat_history}
Follow Up Input: {question}
Standalone question:`,n=e.map(({role:o,content:i})=>`${o}: ${i}`).join(`
`);return await yy(async()=>{let i=await ac.instance.getCurrentChainManager().chatModelManager.getChatModel().bind({temperature:0}).invoke([{role:"user",content:r.replace("{chat_history}",n).replace("{question}",t)}]);return FR(i.content)})}$r();mg();yo();mg();fN();yo();Ix();nr();Cn();rie();qE();LE();Df();Hb();var fie=class extends xn{constructor(e){super(e),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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){return this.getRelevantDocuments(e,un(r))}async getRelevantDocuments(e,r){let n=un(CR(r)),i=await(await Bs.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}}};L8();Qoe();var Rx=class extends fie{constructor(r){super();this.options=r;this.lc_namespace=["hybrid_retriever"];this.queryRewritePrompt=xp.fromTemplate(`Please write a passage to answer the question. If you don't know the answer, just make up a passage.
`);return await yy(async()=>{let i=await ac.instance.getCurrentChainManager().chatModelManager.getChatModel().bind({temperature:0}).invoke([{role:"user",content:r.replace("{chat_history}",n).replace("{question}",t)}]);return kR(i.content)})}$r();mg();yo();mg();pN();yo();Mx();nr();yn();iie();qE();LE();Df();Hb();var hie=class extends Cn{constructor(e){super(e),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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){return this.getRelevantDocuments(e,un(r))}async getRelevantDocuments(e,r){let n=un(CR(r)),i=await(await Bs.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}}};F8();rie();var jx=class extends hie{constructor(r){super();this.options=r;this.lc_namespace=["hybrid_retriever"];this.queryRewritePrompt=xp.fromTemplate(`Please write a passage to answer the question. If you don't know the answer, just make up a passage.
Question: {question}
Passage:`)}async getRelevantDocuments(r,n){return yy(async()=>{let o=NC(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 ue().debug&&console.log("No chunks found for query:",r),d;let f=c.reduce((h,b)=>{let g=b.metadata.score;return typeof g=="number"&&!isNaN(g)?Math.max(h,g):h},0),p=c.every(h=>typeof h.metadata.score!="number"||isNaN(h.metadata.score)),m=this.options.useRerankerThreshold&&(f<this.options.useRerankerThreshold||p);return m&&(d=(await Fi.getInstance().rerank(r,c.map(b=>b.pageContent.slice(0,3e3)))).response.data.map(b=>({...c[b.index],metadata:{...c[b.index].metadata,rerank_score:b.relevance_score}}))),ue().debug&&(console.log("*** HYBRID RETRIEVER DEBUG INFO: ***"),n?.runName!=="no_hyde"&&(console.log(`
Passage:`)}async getRelevantDocuments(r,n){return yy(async()=>{let o=DC(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 ue().debug&&console.log("No chunks found for query:",r),d;let f=c.reduce((h,b)=>{let g=b.metadata.score;return typeof g=="number"&&!isNaN(g)?Math.max(h,g):h},0),p=c.every(h=>typeof h.metadata.score!="number"||isNaN(h.metadata.score)),m=this.options.useRerankerThreshold&&(f<this.options.useRerankerThreshold||p);return m&&(d=(await Fi.getInstance().rerank(r,c.map(b=>b.pageContent.slice(0,3e3)))).response.data.map(b=>({...c[b.index],metadata:{...c[b.index].metadata,rerank_score:b.relevance_score}}))),ue().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{let n=await this.queryRewritePrompt.format({question:r}),o=await yy(()=>ac.instance.getCurrentChainManager().chatModelManager.getChatModel().bind({temperature:0}).invoke(n));return o&&"content"in o?FR(o.content):(console.warn("Unexpected rewrittenQuery format. Falling back to original query."),r)}catch(n){return console.error("Error in rewriteQuery:",n),r}}async getExplicitChunks(r){let n=[];for(let o of r){let i=await ma.getInstance().getDb(),a=await eP.getDocsByPath(i,o.path);if(a){let s=a.map(u=>new tP({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 ma.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&&(ue().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);ie("==== Daily note date range: ====",d[0],d[d.length-1]);let f=NC(d.join(", "),app.vault),m=(await this.getExplicitChunks(f)).map(S=>({...S,metadata:{...S.metadata,includeInContext:!0}}));ie("==== Modified time range: ====",l,c),s.where={mtime:{between:[l,c]}};let b=(await Xc(a,s)).hits.map(S=>new tP({pageContent:S.document.content,metadata:{...S.document.metadata,score:S.score,path:S.document.path,mtime:S.document.mtime,ctime:S.document.ctime,title:S.document.title,id:S.document.id,embeddingModel:S.document.embeddingModel,tags:S.document.tags,extension:S.document.extension,created_at:S.document.created_at,nchars:S.document.nchars}})),g=[...m,...b];return Array.from(new Set(g.map(S=>S.metadata.id))).map(S=>g.find(x=>x.metadata.id===S)).filter(S=>S!==void 0)}ue().debug&&console.log(`==== Orama Search Params: ====
`,s);let u=await Xc(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 tP({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 Xs.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}}))}};nr();var QRe=require("obsidian"),A1t=t=>{switch(t){case"@vault":return"Search through your vault for relevant information";case"@websearch":return"Search the web for information";case"@youtube":return"Get the transcript of a YouTube video. Example: @youtube <video_url>";case"@pomodoro":return"Start a pomodoro timer. Example: @pomodoro 25m";case"@composer":return"Edit existing notes or create new notes.";default:return""}},Pq=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 QRe.Notice(n.message):new QRe.Notice("An error occurred while executing the tool. Check console for details."),null}}};Cn();var UNt=require("obsidian");Cl();ZA();Td();_g();function YGr(t){return"children"in t&&"path"in t}function ZGr(t){return"path"in t&&!("children"in t)}function XGr(t){let e=t.split(".");return e.length>1&&e.pop()?.toLowerCase()||""}function e1e(t,e=!0){let r=[],n={},o={},{inclusions:i,exclusions:a}=rf();for(let u of t.children)if(ZGr(u)){if(eu(u,i,a)){e&&r.push(u.name);let l=XGr(u.name)||"unknown";l&&(n[l]=(n[l]||0)+1)}}else if(YGr(u)){let l=e1e(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 I1t=t=>Qm(async()=>{let e=e1e(t,!0),r=`A JSON represents the file tree as a nested structure:
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{let n=await this.queryRewritePrompt.format({question:r}),o=await yy(()=>ac.instance.getCurrentChainManager().chatModelManager.getChatModel().bind({temperature:0}).invoke(n));return o&&"content"in o?kR(o.content):(console.warn("Unexpected rewrittenQuery format. Falling back to original query."),r)}catch(n){return console.error("Error in rewriteQuery:",n),r}}async getExplicitChunks(r){let n=[];for(let o of r){let i=await ma.getInstance().getDb(),a=await eP.getDocsByPath(i,o.path);if(a){let s=a.map(u=>new tP({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 ma.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&&(ue().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);ie("==== Daily note date range: ====",d[0],d[d.length-1]);let f=DC(d.join(", "),app.vault),m=(await this.getExplicitChunks(f)).map(S=>({...S,metadata:{...S.metadata,includeInContext:!0}}));ie("==== Modified time range: ====",l,c),s.where={mtime:{between:[l,c]}};let b=(await Xc(a,s)).hits.map(S=>new tP({pageContent:S.document.content,metadata:{...S.document.metadata,score:S.score,path:S.document.path,mtime:S.document.mtime,ctime:S.document.ctime,title:S.document.title,id:S.document.id,embeddingModel:S.document.embeddingModel,tags:S.document.tags,extension:S.document.extension,created_at:S.document.created_at,nchars:S.document.nchars}})),g=[...m,...b];return Array.from(new Set(g.map(S=>S.metadata.id))).map(S=>g.find(x=>x.metadata.id===S)).filter(S=>S!==void 0)}ue().debug&&console.log(`==== Orama Search Params: ====
`,s);let u=await Xc(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 tP({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 Xs.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}}))}};nr();var t1e=require("obsidian"),N1t=t=>{switch(t){case"@vault":return"Search through your vault for relevant information";case"@websearch":return"Search the web for information";case"@youtube":return"Get the transcript of a YouTube video. Example: @youtube <video_url>";case"@pomodoro":return"Start a pomodoro timer. Example: @pomodoro 25m";case"@composer":return"Edit existing notes or create new notes.";default:return""}},Eq=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 t1e.Notice(n.message):new t1e.Notice("An error occurred while executing the tool. Check console for details."),null}}};yn();var KNt=require("obsidian");Cl();ZA();Td();_g();function tJr(t){return"children"in t&&"path"in t}function rJr(t){return"path"in t&&!("children"in t)}function nJr(t){let e=t.split(".");return e.length>1&&e.pop()?.toLowerCase()||""}function r1e(t,e=!0){let r=[],n={},o={},{inclusions:i,exclusions:a}=rf();for(let u of t.children)if(rJr(u)){if(eu(u,i,a)){e&&r.push(u.name);let l=nJr(u.name)||"unknown";l&&(n[l]=(n[l]||0)+1)}}else if(tJr(u)){let l=r1e(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 D1t=t=>Qm(async()=>{let e=r1e(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=e1e(t,!1);return r+JSON.stringify(o)}return r+n},{name:"getFileTree",description:"Get the file tree as a nested structure of folders and files",schema:Wr.void()});$r();wT();mg();Ix();nr();ZA();Td();var t1e=Qm(async({timeRange:t,query:e,salientTerms:r})=>{if(await ma.getInstance().isIndexEmpty())throw new Rr(oJ);let o=t!==void 0,i=ue().maxSourceChunks<nge?nge:ue().maxSourceChunks;ue().debug&&console.log("returnAll:",o);let u=(await new Rx({minSimilarityScore:o?0:.1,maxK:o?1e3:i,salientTerms:r,timeRange:t?{startTime:t.startTime.epoch,endTime:t.endTime.epoch}:void 0,textWeight:SVe,returnAll:o,useRerankerThreshold:.5}).getRelevantDocuments(e)).map(l=>({title:l.metadata.title,content:l.pageContent,path:l.metadata.path,score:l.metadata.score,rerank_score:l.metadata.rerank_score,includeInContext:l.metadata.includeInContext}));return JSON.stringify(u)},{name:"localSearch",description:"Search for notes based on the time range and query",schema:Wr.object({timeRange:Wr.object({startTime:Wr.any(),endTime:Wr.any()}).optional(),query:Wr.string().describe("The search query"),salientTerms:Wr.array(Wr.string()).describe("List of salient terms extracted from the query")})}),M1t=Qm(async()=>{try{let t=await ma.getInstance().indexVaultToVectorStore();return`Please report whether the indexing was successful.
If success is true, just say it is successful. If 0 files is indexed, say there are no new files to index.`+JSON.stringify({success:!0,message:t===0?"No new files to index.":`Indexed ${t} files in the vault.`})}catch(t){return console.error("Error indexing vault:",t),JSON.stringify({success:!1,message:"An error occurred while indexing the vault."})}},{name:"indexVault",description:"Index the vault to the Copilot index"}),r1e=Qm(async({query:t,chatHistory:e})=>{try{let r=await die(t,e),n=await Fi.getInstance().webSearch(r),o=n.response.citations||[],i=o.length>0?`
`,n=JSON.stringify(e);if(n.length>5e5){let o=r1e(t,!1);return r+JSON.stringify(o)}return r+n},{name:"getFileTree",description:"Get the file tree as a nested structure of folders and files",schema:Wr.void()});$r();wT();mg();Mx();nr();ZA();Td();var n1e=Qm(async({timeRange:t,query:e,salientTerms:r})=>{if(await ma.getInstance().isIndexEmpty())throw new Rr(iJ);let o=t!==void 0,i=ue().maxSourceChunks<age?age:ue().maxSourceChunks;ue().debug&&console.log("returnAll:",o);let u=(await new jx({minSimilarityScore:o?0:.1,maxK:o?1e3:i,salientTerms:r,timeRange:t?{startTime:t.startTime.epoch,endTime:t.endTime.epoch}:void 0,textWeight:PVe,returnAll:o,useRerankerThreshold:.5}).getRelevantDocuments(e)).map(l=>({title:l.metadata.title,content:l.pageContent,path:l.metadata.path,score:l.metadata.score,rerank_score:l.metadata.rerank_score,includeInContext:l.metadata.includeInContext}));return JSON.stringify(u)},{name:"localSearch",description:"Search for notes based on the time range and query",schema:Wr.object({timeRange:Wr.object({startTime:Wr.any(),endTime:Wr.any()}).optional(),query:Wr.string().describe("The search query"),salientTerms:Wr.array(Wr.string()).describe("List of salient terms extracted from the query")})}),L1t=Qm(async()=>{try{let t=await ma.getInstance().indexVaultToVectorStore();return`Please report whether the indexing was successful.
If success is true, just say it is successful. If 0 files is indexed, say there are no new files to index.`+JSON.stringify({success:!0,message:t===0?"No new files to index.":`Indexed ${t} files in the vault.`})}catch(t){return console.error("Error indexing vault:",t),JSON.stringify({success:!1,message:"An error occurred while indexing the vault."})}},{name:"indexVault",description:"Index the vault to the Copilot index"}),o1e=Qm(async({query:t,chatHistory:e})=>{try{let r=await mie(t,e),n=await Fi.getInstance().webSearch(r),o=n.response.citations||[],i=o.length>0?`
Sources:
`+o.map((a,s)=>`[${s+1}] ${a}`).join(`
`):"";return`Here are the web search results. Please provide a response based on this information and include source citations listed at the end of your response under the heading '#### Sources' as a list of markdown links. For each URL, create a descriptive title based on the domain and path and return it in the markdown format '- [title](url)':
`+n.response.choices[0].message.content+i}catch(r){return console.error(`Error processing web search query ${t}:`,r),""}},{name:"webSearch",description:"Search the web for information",schema:Wr.object({query:Wr.string().describe("The search query"),chatHistory:Wr.array(Wr.object({role:Wr.enum(["user","assistant"]),content:Wr.string()})).describe("Previous conversation turns")})});ZA();var D1t=F(R1t(),1),H8=F(iI(),1);var oo;(function(t){t[t.AM=0]="AM",t[t.PM=1]="PM"})(oo||(oo={}));var tu;(function(t){t[t.SUNDAY=0]="SUNDAY",t[t.MONDAY=1]="MONDAY",t[t.TUESDAY=2]="TUESDAY",t[t.WEDNESDAY=3]="WEDNESDAY",t[t.THURSDAY=4]="THURSDAY",t[t.FRIDAY=5]="FRIDAY",t[t.SATURDAY=6]="SATURDAY"})(tu||(tu={}));var eh;(function(t){t[t.JANUARY=1]="JANUARY",t[t.FEBRUARY=2]="FEBRUARY",t[t.MARCH=3]="MARCH",t[t.APRIL=4]="APRIL",t[t.MAY=5]="MAY",t[t.JUNE=6]="JUNE",t[t.JULY=7]="JULY",t[t.AUGUST=8]="AUGUST",t[t.SEPTEMBER=9]="SEPTEMBER",t[t.OCTOBER=10]="OCTOBER",t[t.NOVEMBER=11]="NOVEMBER",t[t.DECEMBER=12]="DECEMBER"})(eh||(eh={}));function j1t(t,e){e=e.add(1,"day"),xN(t,e),Eq(t,e)}function rb(t,e){t.assign("day",e.date()),t.assign("month",e.month()+1),t.assign("year",e.year())}function pie(t,e){t.assign("hour",e.hour()),t.assign("minute",e.minute()),t.assign("second",e.second()),t.assign("millisecond",e.millisecond()),t.get("hour")<12?t.assign("meridiem",oo.AM):t.assign("meridiem",oo.PM)}function xN(t,e){t.imply("day",e.date()),t.imply("month",e.month()+1),t.imply("year",e.year())}function Eq(t,e){t.imply("hour",e.hour()),t.imply("minute",e.minute()),t.imply("second",e.second()),t.imply("millisecond",e.millisecond())}var s1e=F(iI(),1);var QGr={ACDT:630,ACST:570,ADT:-180,AEDT:660,AEST:600,AFT:270,AKDT:-480,AKST:-540,ALMT:360,AMST:-180,AMT:-240,ANAST:720,ANAT:720,AQTT:300,ART:-180,AST:-240,AWDT:540,AWST:480,AZOST:0,AZOT:-60,AZST:300,AZT:240,BNT:480,BOT:-240,BRST:-120,BRT:-180,BST:60,BTT:360,CAST:480,CAT:120,CCT:390,CDT:-300,CEST:120,CET:{timezoneOffsetDuringDst:2*60,timezoneOffsetNonDst:60,dstStart:t=>N1t(t,eh.MARCH,tu.SUNDAY,2),dstEnd:t=>N1t(t,eh.OCTOBER,tu.SUNDAY,3)},CHADT:825,CHAST:765,CKT:-600,CLST:-180,CLT:-240,COT:-300,CST:-360,CT:{timezoneOffsetDuringDst:-5*60,timezoneOffsetNonDst:-6*60,dstStart:t=>aI(t,eh.MARCH,tu.SUNDAY,2,2),dstEnd:t=>aI(t,eh.NOVEMBER,tu.SUNDAY,1,2)},CVT:-60,CXT:420,ChST:600,DAVT:420,EASST:-300,EAST:-360,EAT:180,ECT:-300,EDT:-240,EEST:180,EET:120,EGST:0,EGT:-60,EST:-300,ET:{timezoneOffsetDuringDst:-4*60,timezoneOffsetNonDst:-5*60,dstStart:t=>aI(t,eh.MARCH,tu.SUNDAY,2,2),dstEnd:t=>aI(t,eh.NOVEMBER,tu.SUNDAY,1,2)},FJST:780,FJT:720,FKST:-180,FKT:-240,FNT:-120,GALT:-360,GAMT:-540,GET:240,GFT:-180,GILT:720,GMT:0,GST:240,GYT:-240,HAA:-180,HAC:-300,HADT:-540,HAE:-240,HAP:-420,HAR:-360,HAST:-600,HAT:-90,HAY:-480,HKT:480,HLV:-210,HNA:-240,HNC:-360,HNE:-300,HNP:-480,HNR:-420,HNT:-150,HNY:-540,HOVT:420,ICT:420,IDT:180,IOT:360,IRDT:270,IRKST:540,IRKT:540,IRST:210,IST:330,JST:540,KGT:360,KRAST:480,KRAT:480,KST:540,KUYT:240,LHDT:660,LHST:630,LINT:840,MAGST:720,MAGT:720,MART:-510,MAWT:300,MDT:-360,MESZ:120,MEZ:60,MHT:720,MMT:390,MSD:240,MSK:180,MST:-420,MT:{timezoneOffsetDuringDst:-6*60,timezoneOffsetNonDst:-7*60,dstStart:t=>aI(t,eh.MARCH,tu.SUNDAY,2,2),dstEnd:t=>aI(t,eh.NOVEMBER,tu.SUNDAY,1,2)},MUT:240,MVT:300,MYT:480,NCT:660,NDT:-90,NFT:690,NOVST:420,NOVT:360,NPT:345,NST:-150,NUT:-660,NZDT:780,NZST:720,OMSST:420,OMST:420,PDT:-420,PET:-300,PETST:720,PETT:720,PGT:600,PHOT:780,PHT:480,PKT:300,PMDT:-120,PMST:-180,PONT:660,PST:-480,PT:{timezoneOffsetDuringDst:-7*60,timezoneOffsetNonDst:-8*60,dstStart:t=>aI(t,eh.MARCH,tu.SUNDAY,2,2),dstEnd:t=>aI(t,eh.NOVEMBER,tu.SUNDAY,1,2)},PWT:540,PYST:-180,PYT:-240,RET:240,SAMT:240,SAST:120,SBT:660,SCT:240,SGT:480,SRT:-180,SST:-660,TAHT:-600,TFT:300,TJT:300,TKT:780,TLT:540,TMT:300,TVT:720,ULAT:480,UTC:0,UYST:-120,UYT:-180,UZT:300,VET:-210,VLAST:660,VLAT:660,VUT:660,WAST:120,WAT:60,WEST:60,WESZ:60,WET:0,WEZ:0,WFT:720,WGST:-120,WGT:-180,WIB:420,WIT:540,WITA:480,WST:780,WT:0,YAKST:600,YAKT:600,YAPT:600,YEKST:360,YEKT:360};function aI(t,e,r,n,o=0){let i=0,a=0;for(;a<n;)i++,new Date(t,e-1,i).getDay()===r&&a++;return new Date(t,e-1,i,o)}function N1t(t,e,r,n=0){let o=r===0?7:r,i=new Date(t,e-1+1,1,12),a=i.getDay()===0?7:i.getDay(),s;return a===o?s=7:a<o?s=7+a-o:s=a-o,i.setDate(i.getDate()-s),new Date(t,e-1,i.getDate(),n)}function mie(t,e,r={}){if(t==null)return null;if(typeof t=="number")return t;let n=r[t]??QGr[t];return n==null?null:typeof n=="number"?n:e==null?null:(0,s1e.default)(e).isAfter(n.dstStart(e.getFullYear()))&&!(0,s1e.default)(e).isAfter(n.dstEnd(e.getFullYear()))?n.timezoneOffsetDuringDst:n.timezoneOffsetNonDst}H8.default.extend(D1t.default);var sI=class{constructor(e){e=e??new Date,e instanceof Date?this.instant=e:(this.instant=e.instant??new Date,this.timezoneOffset=mie(e.timezone,this.instant))}getDateWithAdjustedTimezone(){return new Date(this.instant.getTime()+this.getSystemTimezoneAdjustmentMinute(this.instant)*6e4)}getSystemTimezoneAdjustmentMinute(e,r){(!e||e.getTime()<0)&&(e=new Line truncated
`+n.response.choices[0].message.content+i}catch(r){return console.error(`Error processing web search query ${t}:`,r),""}},{name:"webSearch",description:"Search the web for information",schema:Wr.object({query:Wr.string().describe("The search query"),chatHistory:Wr.array(Wr.object({role:Wr.enum(["user","assistant"]),content:Wr.string()})).describe("Previous conversation turns")})});ZA();var B1t=F(F1t(),1),V8=F(iI(),1);var oo;(function(t){t[t.AM=0]="AM",t[t.PM=1]="PM"})(oo||(oo={}));var tu;(function(t){t[t.SUNDAY=0]="SUNDAY",t[t.MONDAY=1]="MONDAY",t[t.TUESDAY=2]="TUESDAY",t[t.WEDNESDAY=3]="WEDNESDAY",t[t.THURSDAY=4]="THURSDAY",t[t.FRIDAY=5]="FRIDAY",t[t.SATURDAY=6]="SATURDAY"})(tu||(tu={}));var eh;(function(t){t[t.JANUARY=1]="JANUARY",t[t.FEBRUARY=2]="FEBRUARY",t[t.MARCH=3]="MARCH",t[t.APRIL=4]="APRIL",t[t.MAY=5]="MAY",t[t.JUNE=6]="JUNE",t[t.JULY=7]="JULY",t[t.AUGUST=8]="AUGUST",t[t.SEPTEMBER=9]="SEPTEMBER",t[t.OCTOBER=10]="OCTOBER",t[t.NOVEMBER=11]="NOVEMBER",t[t.DECEMBER=12]="DECEMBER"})(eh||(eh={}));function k1t(t,e){e=e.add(1,"day"),CN(t,e),Tq(t,e)}function rb(t,e){t.assign("day",e.date()),t.assign("month",e.month()+1),t.assign("year",e.year())}function gie(t,e){t.assign("hour",e.hour()),t.assign("minute",e.minute()),t.assign("second",e.second()),t.assign("millisecond",e.millisecond()),t.get("hour")<12?t.assign("meridiem",oo.AM):t.assign("meridiem",oo.PM)}function CN(t,e){t.imply("day",e.date()),t.imply("month",e.month()+1),t.imply("year",e.year())}function Tq(t,e){t.imply("hour",e.hour()),t.imply("minute",e.minute()),t.imply("second",e.second()),t.imply("millisecond",e.millisecond())}var l1e=F(iI(),1);var oJr={ACDT:630,ACST:570,ADT:-180,AEDT:660,AEST:600,AFT:270,AKDT:-480,AKST:-540,ALMT:360,AMST:-180,AMT:-240,ANAST:720,ANAT:720,AQTT:300,ART:-180,AST:-240,AWDT:540,AWST:480,AZOST:0,AZOT:-60,AZST:300,AZT:240,BNT:480,BOT:-240,BRST:-120,BRT:-180,BST:60,BTT:360,CAST:480,CAT:120,CCT:390,CDT:-300,CEST:120,CET:{timezoneOffsetDuringDst:2*60,timezoneOffsetNonDst:60,dstStart:t=>$1t(t,eh.MARCH,tu.SUNDAY,2),dstEnd:t=>$1t(t,eh.OCTOBER,tu.SUNDAY,3)},CHADT:825,CHAST:765,CKT:-600,CLST:-180,CLT:-240,COT:-300,CST:-360,CT:{timezoneOffsetDuringDst:-5*60,timezoneOffsetNonDst:-6*60,dstStart:t=>aI(t,eh.MARCH,tu.SUNDAY,2,2),dstEnd:t=>aI(t,eh.NOVEMBER,tu.SUNDAY,1,2)},CVT:-60,CXT:420,ChST:600,DAVT:420,EASST:-300,EAST:-360,EAT:180,ECT:-300,EDT:-240,EEST:180,EET:120,EGST:0,EGT:-60,EST:-300,ET:{timezoneOffsetDuringDst:-4*60,timezoneOffsetNonDst:-5*60,dstStart:t=>aI(t,eh.MARCH,tu.SUNDAY,2,2),dstEnd:t=>aI(t,eh.NOVEMBER,tu.SUNDAY,1,2)},FJST:780,FJT:720,FKST:-180,FKT:-240,FNT:-120,GALT:-360,GAMT:-540,GET:240,GFT:-180,GILT:720,GMT:0,GST:240,GYT:-240,HAA:-180,HAC:-300,HADT:-540,HAE:-240,HAP:-420,HAR:-360,HAST:-600,HAT:-90,HAY:-480,HKT:480,HLV:-210,HNA:-240,HNC:-360,HNE:-300,HNP:-480,HNR:-420,HNT:-150,HNY:-540,HOVT:420,ICT:420,IDT:180,IOT:360,IRDT:270,IRKST:540,IRKT:540,IRST:210,IST:330,JST:540,KGT:360,KRAST:480,KRAT:480,KST:540,KUYT:240,LHDT:660,LHST:630,LINT:840,MAGST:720,MAGT:720,MART:-510,MAWT:300,MDT:-360,MESZ:120,MEZ:60,MHT:720,MMT:390,MSD:240,MSK:180,MST:-420,MT:{timezoneOffsetDuringDst:-6*60,timezoneOffsetNonDst:-7*60,dstStart:t=>aI(t,eh.MARCH,tu.SUNDAY,2,2),dstEnd:t=>aI(t,eh.NOVEMBER,tu.SUNDAY,1,2)},MUT:240,MVT:300,MYT:480,NCT:660,NDT:-90,NFT:690,NOVST:420,NOVT:360,NPT:345,NST:-150,NUT:-660,NZDT:780,NZST:720,OMSST:420,OMST:420,PDT:-420,PET:-300,PETST:720,PETT:720,PGT:600,PHOT:780,PHT:480,PKT:300,PMDT:-120,PMST:-180,PONT:660,PST:-480,PT:{timezoneOffsetDuringDst:-7*60,timezoneOffsetNonDst:-8*60,dstStart:t=>aI(t,eh.MARCH,tu.SUNDAY,2,2),dstEnd:t=>aI(t,eh.NOVEMBER,tu.SUNDAY,1,2)},PWT:540,PYST:-180,PYT:-240,RET:240,SAMT:240,SAST:120,SBT:660,SCT:240,SGT:480,SRT:-180,SST:-660,TAHT:-600,TFT:300,TJT:300,TKT:780,TLT:540,TMT:300,TVT:720,ULAT:480,UTC:0,UYST:-120,UYT:-180,UZT:300,VET:-210,VLAST:660,VLAT:660,VUT:660,WAST:120,WAT:60,WEST:60,WESZ:60,WET:0,WEZ:0,WFT:720,WGST:-120,WGT:-180,WIB:420,WIT:540,WITA:480,WST:780,WT:0,YAKST:600,YAKT:600,YAPT:600,YEKST:360,YEKT:360};function aI(t,e,r,n,o=0){let i=0,a=0;for(;a<n;)i++,new Date(t,e-1,i).getDay()===r&&a++;return new Date(t,e-1,i,o)}function $1t(t,e,r,n=0){let o=r===0?7:r,i=new Date(t,e-1+1,1,12),a=i.getDay()===0?7:i.getDay(),s;return a===o?s=7:a<o?s=7+a-o:s=a-o,i.setDate(i.getDate()-s),new Date(t,e-1,i.getDate(),n)}function yie(t,e,r={}){if(t==null)return null;if(typeof t=="number")return t;let n=r[t]??oJr[t];return n==null?null:typeof n=="number"?n:e==null?null:(0,l1e.default)(e).isAfter(n.dstStart(e.getFullYear()))&&!(0,l1e.default)(e).isAfter(n.dstEnd(e.getFullYear()))?n.timezoneOffsetDuringDst:n.timezoneOffsetNonDst}V8.default.extend(B1t.default);var sI=class{constructor(e){e=e??new Date,e instanceof Date?this.instant=e:(this.instant=e.instant??new Date,this.timezoneOffset=yie(e.timezone,this.instant))}getDateWithAdjustedTimezone(){return new Date(this.instant.getTime()+this.getSystemTimezoneAdjustmentMinute(this.instant)*6e4)}getSystemTimezoneAdjustmentMinute(e,r){(!e||e.getTime()<0)&&(e=new Line truncated
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,H8.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,H8.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?(pie(o,n),rb(o,n),e.timezoneOffset!==null&&o.assign("timezoneOffset",-e.instant.getTimezoneOffset())):(Eq(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}},rP=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 io(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 u1e(t,e,r="\\s{0,5},?\\s{0,5}"){let n=e.replace(/\((?!\?)/g,"(?:");return`${t}${n}(?:${r}${n}){0,10}`}function eJr(t){let e;return t instanceof Array?e=[...t]:t instanceof Map?e=Array.from(t.keys()):e=Object.keys(t),e}function Qc(t){return`(?:${eJr(t).sort((r,n)=>n.length-r.length).join("|").replace(/\./g,"\\.")})`}var L1t=F(iI(),1);function hie(t){return t<100&&(t>50?t=t+1900:t=t+2e3),t}function uI(t,e,r){let n=(0,L1t.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 d1e={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},f1e={january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12},vg={...f1e,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},l1e={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12},c1e={first:1,second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,tenth:10,eleventh:11,twelfth:12,thirteenth:13,fourteenth:14,fifteenth:15,sixteenth:16,seventeenth:17,eighteenth:18,nineteenth:19,twentieth:20,"twenty first":21,"twenty-first":21,"twenty second":22,"twenty-second":22,"twenty third":23,"twenty-third":23,"twenty fourth":24,"twenty-fourth":24,"twenty fifth":25,"twenty-fifth":25,"twenty sixth":26,"twenty-sixth":26,"twenty seventh":27,"twenty-seventh":27,"twenty eighth":28,"twenty-eighth":28,"twenty ninth":29,"twenty-ninth":29,thirtieth:30,"thirty first":31,"thirty-first":31},k1t={second:"second",seconds:"second",minute:"minute",minutes:"minute",hour:"hour",hours:"hour",day:"d",days:"d",week:"week",weeks:"week",month:"month",months:"month",quarter:"quarter",quarters:"quarter",year:"year",years:"year"},V8={s:"second",sec:"second",second:"second",seconds:"second",m:"minute",min:"minute",mins:"minute",minute:"minute",minutes:"minute",h:"hour",hr:"hour",hrs:"hour",hour:"hour",hours:"hour",d:"d",day:"d",days:"d",w:"w",week:"week",weeks:"week",mo:"month",mon:"month",mos:"month",month:"month",months:"month",qtr:"quarter",quarter:"quarter",quarters:"quarter",y:"year",yr:"year",year:"year",years:"year",...k1t},$1t=`(?:${Qc(l1e)}|[0-9]+|[0-9]+\\.[0-9]+|half(?:\\s{0,2}an?)?|an?\\b(?:\\s{0,2}few)?|few|several|the|a?\\s{0,2}couple\\s{0,2}(?:of)?)`;function tJr(t){let e=t.toLowerCase();return l1e[e]!==void 0?l1e[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)}var Tq=`(?:${Qc(c1e)}|[0-9]{1,2}(?:st|nd|rd|th)?)`;function Aq(t){let e=t.toLowerCase();return c1e[e]!==void 0?c1e[e]:(e=e.replace(/(?:st|nd|rd|th)$/i,""),parseInt(e))}var lI="(?:[1-9][0-9]{0,3}\\s{0,2}(?:BE|AD|BC|BCE|CE)|[1-2][0-9]{3}|[5-9 Line truncated
reference: ${JSON.stringify(this.reference)}]`}dayjs(){return(0,V8.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,V8.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?(gie(o,n),rb(o,n),e.timezoneOffset!==null&&o.assign("timezoneOffset",-e.instant.getTimezoneOffset())):(Tq(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}},rP=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 io(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 c1e(t,e,r="\\s{0,5},?\\s{0,5}"){let n=e.replace(/\((?!\?)/g,"(?:");return`${t}${n}(?:${r}${n}){0,10}`}function iJr(t){let e;return t instanceof Array?e=[...t]:t instanceof Map?e=Array.from(t.keys()):e=Object.keys(t),e}function Qc(t){return`(?:${iJr(t).sort((r,n)=>n.length-r.length).join("|").replace(/\./g,"\\.")})`}var q1t=F(iI(),1);function bie(t){return t<100&&(t>50?t=t+1900:t=t+2e3),t}function uI(t,e,r){let n=(0,q1t.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 p1e={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},m1e={january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12},vg={...m1e,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},d1e={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12},f1e={first:1,second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,tenth:10,eleventh:11,twelfth:12,thirteenth:13,fourteenth:14,fifteenth:15,sixteenth:16,seventeenth:17,eighteenth:18,nineteenth:19,twentieth:20,"twenty first":21,"twenty-first":21,"twenty second":22,"twenty-second":22,"twenty third":23,"twenty-third":23,"twenty fourth":24,"twenty-fourth":24,"twenty fifth":25,"twenty-fifth":25,"twenty sixth":26,"twenty-sixth":26,"twenty seventh":27,"twenty-seventh":27,"twenty eighth":28,"twenty-eighth":28,"twenty ninth":29,"twenty-ninth":29,thirtieth:30,"thirty first":31,"thirty-first":31},z1t={second:"second",seconds:"second",minute:"minute",minutes:"minute",hour:"hour",hours:"hour",day:"d",days:"d",week:"week",weeks:"week",month:"month",months:"month",quarter:"quarter",quarters:"quarter",year:"year",years:"year"},W8={s:"second",sec:"second",second:"second",seconds:"second",m:"minute",min:"minute",mins:"minute",minute:"minute",minutes:"minute",h:"hour",hr:"hour",hrs:"hour",hour:"hour",hours:"hour",d:"d",day:"d",days:"d",w:"w",week:"week",weeks:"week",mo:"month",mon:"month",mos:"month",month:"month",months:"month",qtr:"quarter",quarter:"quarter",quarters:"quarter",y:"year",yr:"year",year:"year",years:"year",...z1t},H1t=`(?:${Qc(d1e)}|[0-9]+|[0-9]+\\.[0-9]+|half(?:\\s{0,2}an?)?|an?\\b(?:\\s{0,2}few)?|few|several|the|a?\\s{0,2}couple\\s{0,2}(?:of)?)`;function aJr(t){let e=t.toLowerCase();return d1e[e]!==void 0?d1e[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)}var Aq=`(?:${Qc(f1e)}|[0-9]{1,2}(?:st|nd|rd|th)?)`;function Iq(t){let e=t.toLowerCase();return f1e[e]!==void 0?f1e[e]:(e=e.replace(/(?:st|nd|rd|th)$/i,""),parseInt(e))}var lI="(?:[1-9][0-9]{0,3}\\s{0,2}(?:BE|AD|BC|BCE|CE)|[1-2][0-9]{3}|[5-9 Line truncated
<think>`,this.hasOpenThinkBlock=!0),this.fullResponse+=n.thinking,this.updateCurrentAiMessage(this.fullResponse),!0}return r&&(this.fullResponse+=r),!1}handleDeepseekChunk(e){return typeof e.content=="string"&&(this.fullResponse+=e.content),e.additional_kwargs?.reasoning_content?(this.hasOpenThinkBlock||(this.fullResponse+=`
<think>`,this.hasOpenThinkBlock=!0),this.fullResponse+=e.additional_kwargs.reasoning_content,!0):!1}processChunk(e){let r=!1;Array.isArray(e.content)?r=this.handleClaude37Chunk(e.content):r=this.handleDeepseekChunk(e),this.hasOpenThinkBlock&&!r&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),this.updateCurrentAiMessage(this.fullResponse)}close(){return this.hasOpenThinkBlock&&(this.fullResponse+="</think>",this.updateCurrentAiMessage(this.fullResponse)),this.fullResponse}},Q6=class{constructor(e){this.chainManager=e}async handleResponse(e,r,n,o,i,a){return e&&!(n.signal.aborted&&n.signal.reason==="new-chat")?(await this.chainManager.memoryManager.getMemory().saveContext({input:r.message},{output:e}),o({message:e,sender:e_,isVisible:!0,timestamp:Vl(new Date),sources:a}),i("")):n.signal.reason==="new-chat"&&i(""),ie(`==== Chat Memory ====
<think>`,this.hasOpenThinkBlock=!0),this.fullResponse+=e.additional_kwargs.reasoning_content,!0):!1}processChunk(e){let r=!1;Array.isArray(e.content)?r=this.handleClaude37Chunk(e.content):r=this.handleDeepseekChunk(e),this.hasOpenThinkBlock&&!r&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),this.updateCurrentAiMessage(this.fullResponse)}close(){return this.hasOpenThinkBlock&&(this.fullResponse+="</think>",this.updateCurrentAiMessage(this.fullResponse)),this.fullResponse}},e5=class{constructor(e){this.chainManager=e}async handleResponse(e,r,n,o,i,a){return e&&!(n.signal.aborted&&n.signal.reason==="new-chat")?(await this.chainManager.memoryManager.getMemory().saveContext({input:r.message},{output:e}),o({message:e,sender:e_,isVisible:!0,timestamp:Vl(new Date),sources:a}),i("")):n.signal.reason==="new-chat"&&i(""),ie(`==== Chat Memory ====
`,this.chainManager.memoryManager.getMemory().chatHistory.messages.map(s=>s.content)),ie(`==== Final AI Response ====
`,e),e}async handleError(e,r,n){let o=ei(e);fe("Error during LLM invocation:",o);let i=e?.response?.data?.error||o,a=i?.code||o,s="";if(e?.message?.includes("Invalid license key")?s="Invalid Copilot Plus license key. Please check your license key in settings.":a==="model_not_found"?s="You do not have access to this model or the model does not exist, please check with your API provider.":s=`${a}`,fe(i),r&&n){n("");let u=s.search("Troubleshooting URL");s=u!==-1?s.slice(0,u):s,o.search(/401|invalid|not valid/gi)!==-1&&(s=`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: `+s),r({message:s,isErrorMessage:!0,sender:e_,isVisible:!0,timestamp:Vl(new Date)})}else new UNt.Notice(s),fe(i)}},qie=class extends Q6{async run(e,r,n,o,i){let a=new X6(n);try{let l=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),c=DR(l),d=[],f=Yb(),p=this.chainManager.chatModelManager.getChatModel();f&&d.push({role:nJ(p),content:f});for(let h of c)d.push({role:h.role,content:h.content});d.push({role:"user",content:e.message}),ie(`==== Final Request to AI ====
`,d);let m=await yy(()=>this.chainManager.chatModelManager.getChatModel().stream(d,{signal:r.signal}));for await(let h of m){if(r.signal.aborted){ie("Stream iteration aborted",{reason:r.signal.reason});break}a.processChunk(h)}}catch(u){u.name==="AbortError"||r.signal.aborted?ie("Stream aborted by user",{reason:r.signal.reason}):await this.handleError(u,o,n)}let s=a.close();return r.signal.aborted&&r.signal.reason==="new-chat"?(n(""),""):this.handleResponse(s,e,r,o,n)}},Uie=class extends Q6{async run(e,r,n,o,i){let a=new X6(n);try{if(await this.chainManager.vectorStoreManager.isIndexEmpty())return this.handleResponse(oJ,e,r,o,n);let c=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),d=DR(c),f=e.message;d.length>0&&(f=e.message);let m=await new Rx({minSimilarityScore:.01,maxK:ue().maxSourceChunks,salientTerms:[]}).getRelevantDocuments(f);this.chainManager.storeRetrieverDocuments(m);let h=m.map(P=>P.pageContent).join(`
Error Details: `+s),r({message:s,isErrorMessage:!0,sender:e_,isVisible:!0,timestamp:Vl(new Date)})}else new KNt.Notice(s),fe(i)}},Hie=class extends e5{async run(e,r,n,o,i){let a=new Q6(n);try{let l=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),c=LR(l),d=[],f=Yb(),p=this.chainManager.chatModelManager.getChatModel();f&&d.push({role:oJ(p),content:f});for(let h of c)d.push({role:h.role,content:h.content});d.push({role:"user",content:e.message}),ie(`==== Final Request to AI ====
`,d);let m=await yy(()=>this.chainManager.chatModelManager.getChatModel().stream(d,{signal:r.signal}));for await(let h of m){if(r.signal.aborted){ie("Stream iteration aborted",{reason:r.signal.reason});break}a.processChunk(h)}}catch(u){u.name==="AbortError"||r.signal.aborted?ie("Stream aborted by user",{reason:r.signal.reason}):await this.handleError(u,o,n)}let s=a.close();return r.signal.aborted&&r.signal.reason==="new-chat"?(n(""),""):this.handleResponse(s,e,r,o,n)}},Vie=class extends e5{async run(e,r,n,o,i){let a=new Q6(n);try{if(await this.chainManager.vectorStoreManager.isIndexEmpty())return this.handleResponse(iJ,e,r,o,n);let c=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),d=LR(c),f=e.message;d.length>0&&(f=e.message);let m=await new jx({minSimilarityScore:.01,maxK:ue().maxSourceChunks,salientTerms:[]}).getRelevantDocuments(f);this.chainManager.storeRetrieverDocuments(m);let h=m.map(P=>P.pageContent).join(`
`),b=[],g=Yb(),y=`
Answer the question with as detailed as possible based only on the following context:
`+h,S=g+y,x=this.chainManager.chatModelManager.getChatModel();S&&b.push({role:nJ(x),content:S});for(let P of d)b.push({role:P.role,content:P.content});b.push({role:"user",content:e.message}),ie(`==== Final Request to AI ====
`,b);let O=await yy(()=>this.chainManager.chatModelManager.getChatModel().stream(b,{signal:r.signal}));for await(let P of O){if(r.signal.aborted){ie("VaultQA stream iteration aborted",{reason:r.signal.reason});break}a.processChunk(P)}}catch(u){u.name==="AbortError"||r.signal.aborted?ie("VaultQA stream aborted by user",{reason:r.signal.reason}):await this.handleError(u,o,n)}let s=a.close();return r.signal.aborted&&r.signal.reason==="new-chat"?(n(""),""):(s=this.addSourcestoResponse(s),this.handleResponse(s,e,r,o,n))}addSourcestoResponse(e){let r=hVe(this.chainManager.getRetrievedDocuments());if(r.length>0){let n=r.map(o=>`- [[${o}]]`).join(`
`+h,S=g+y,x=this.chainManager.chatModelManager.getChatModel();S&&b.push({role:oJ(x),content:S});for(let P of d)b.push({role:P.role,content:P.content});b.push({role:"user",content:e.message}),ie(`==== Final Request to AI ====
`,b);let O=await yy(()=>this.chainManager.chatModelManager.getChatModel().stream(b,{signal:r.signal}));for await(let P of O){if(r.signal.aborted){ie("VaultQA stream iteration aborted",{reason:r.signal.reason});break}a.processChunk(P)}}catch(u){u.name==="AbortError"||r.signal.aborted?ie("VaultQA stream aborted by user",{reason:r.signal.reason}):await this.handleError(u,o,n)}let s=a.close();return r.signal.aborted&&r.signal.reason==="new-chat"?(n(""),""):(s=this.addSourcestoResponse(s),this.handleResponse(s,e,r,o,n))}addSourcestoResponse(e){let r=yVe(this.chainManager.getRetrievedDocuments());if(r.length>0){let n=r.map(o=>`- [[${o}]]`).join(`
`);e+=`
#### Sources:
`+n}return e}},e5=class extends Q6{isYoutubeOnlyMessage(e){let r=e.trim(),n=r.includes("@youtube"),o=Qhe(r),i=r.split(/\s+/).filter(a=>a!=="@youtube"&&a.length>0);return n&&o!==null&&i.length===1}async processImageUrls(e){let r=[],n=await wN.processUrlBatch(e,r,this.chainManager.app.vault);return wN.showFailedImagesNotice(r),n}async processChatInputImages(e){let r=[],n=await wN.processChatImageBatch(e,r,this.chainManager.app.vault);return wN.showFailedImagesNotice(r),n}async extractEmbeddedImages(e){let r=/!\[\[(.*?\.(png|jpg|jpeg|gif|webp|bmp|svg))\]\]/g;return[...e.matchAll(r)].map(i=>i[1])}async buildMessageContent(e,r){let n=[],o=[],i=ue(),a=[],s=r.context?.urls;if(s&&s.length>0&&a.push({urls:s,type:"context"}),i.passMarkdownImages){let d=await this.extractEmbeddedImages(e);d.length>0&&a.push({urls:d,type:"embedded"})}for(let d of a){let f=await this.processImageUrls(d.urls);o.push(...f.successfulImages),n.push(...f.failureDescriptions)}let u=r.content;if(u&&u.length>0){let d=await this.processChatInputImages(u);o.push(...d.successfulImages),n.push(...d.failureDescriptions)}let l=e;n.length>0&&(l=`${e}
`+n}return e}},t5=class extends e5{isYoutubeOnlyMessage(e){let r=e.trim(),n=r.includes("@youtube"),o=rge(r),i=r.split(/\s+/).filter(a=>a!=="@youtube"&&a.length>0);return n&&o!==null&&i.length===1}async processImageUrls(e){let r=[],n=await SN.processUrlBatch(e,r,this.chainManager.app.vault);return SN.showFailedImagesNotice(r),n}async processChatInputImages(e){let r=[],n=await SN.processChatImageBatch(e,r,this.chainManager.app.vault);return SN.showFailedImagesNotice(r),n}async extractEmbeddedImages(e){let r=/!\[\[(.*?\.(png|jpg|jpeg|gif|webp|bmp|svg))\]\]/g;return[...e.matchAll(r)].map(i=>i[1])}async buildMessageContent(e,r){let n=[],o=[],i=ue(),a=[],s=r.context?.urls;if(s&&s.length>0&&a.push({urls:s,type:"context"}),i.passMarkdownImages){let d=await this.extractEmbeddedImages(e);d.length>0&&a.push({urls:d,type:"embedded"})}for(let d of a){let f=await this.processImageUrls(d.urls);o.push(...f.successfulImages),n.push(...f.failureDescriptions)}let u=r.content;if(u&&u.length>0){let d=await this.processChatInputImages(u);o.push(...d.successfulImages),n.push(...d.failureDescriptions)}let l=e;n.length>0&&(l=`${e}
Note:
${n.join(`
`)}
`);let c=[{type:"text",text:l}];return o.length>0&&c.push(...o),c}hasCapability(e,r){let n=e.modelName||e.model||"";return this.chainManager.chatModelManager.findModelByName(n)?.capabilities?.includes(r)??!1}isMultimodalModel(e){return this.hasCapability(e,"vision")}async streamMultimodalResponse(e,r,n,o){let a=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),s=DR(a),u=[],l=await this.getSystemPrompt();s.length>0&&(l+=`
`);let c=[{type:"text",text:l}];return o.length>0&&c.push(...o),c}hasCapability(e,r){let n=e.modelName||e.model||"";return this.chainManager.chatModelManager.findModelByName(n)?.capabilities?.includes(r)??!1}isMultimodalModel(e){return this.hasCapability(e,"vision")}async streamMultimodalResponse(e,r,n,o){let a=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),s=LR(a),u=[],l=await this.getSystemPrompt();s.length>0&&(l+=`
The following is the relevant conversation history. Use this context to maintain consistency in your responses:`);let c=this.chainManager.chatModelManager.getChatModel();l&&u.push({role:nJ(c),content:`${l}
The following is the relevant conversation history. Use this context to maintain consistency in your responses:`);let c=this.chainManager.chatModelManager.getChatModel();l&&u.push({role:oJ(c),content:`${l}
IMPORTANT: Maintain consistency with previous responses in the conversation. If you've provided information about a person or topic before, use that same information in follow-up questions.`});for(let g of s)u.push({role:g.role,content:g.content});let d=this.chainManager.chatModelManager.getChatModel(),p=this.isMultimodalModel(d)?await this.buildMessageContent(e,r):e;u.push({role:"user",content:p});let m=p instanceof Array?p[0].text:p;ie("Enhanced user message: ",m),ie(`==== Final Request to AI ====
`,u);let h=new X6(o),b=await yy(()=>this.chainManager.chatModelManager.getChatModel().stream(u,{signal:n.signal}));for await(let g of b){if(n.signal.aborted){ie("CopilotPlus multimodal stream iteration aborted",{reason:n.signal.reason});break}h.processChunk(g)}return h.close()}async run(e,r,n,o,i){let{updateLoadingMessage:a}=i,s="",u=[],l="",c=d=>{l=d,n(d)};try{if(this.isYoutubeOnlyMessage(e.message)){let S=Qhe(e.message),x="Transcript not available. Only videos with the auto transcript option turned on are supported at the moment.";if(S)try{let O=await Fi.getInstance().youtube4llm(S);return O.response.transcript?this.handleResponse(O.response.transcript,e,r,o,n):this.handleResponse(x,e,r,o,n)}catch(O){return fe("Error processing YouTube video:",O),this.handleResponse(x,e,r,o,n)}}ie("==== Step 1: Analyzing intent ====");let d,f=e.originalMessage||e.message;try{d=await IN.analyzeIntent(f)}catch(S){return this.handleResponse(cVe(S),e,r,o,n)}let p=e.message.split(" ").filter(S=>!Z6.includes(S.toLowerCase())).join(" ").trim(),m=await this.executeToolCalls(d,a),h=m.find(S=>S.tool==="localSearch"&&S.output&&S.output.length>0),g=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),y=DR(g);if(h){ie("==== Step 2: Processing local search results ====");let S=JSON.parse(h.output);ie("==== Step 3: Condensing Question ====");let x=await die(p,y);ie("Condensed standalone question: ",x),ie("==== Step 4: Preparing context ====");let O=this.getTimeExpression(d),P=this.prepareLocalSearchResult(S,O),E=m.filter(R=>R.tool==="getCurrentTime"),A=this.prepareEnhancedUserMessage(x,E);ie(P),ie("==== Step 5: Invoking QA Chain ====");let I=await this.chainManager.promptManager.getQAPrompt({question:A,context:P,systemMessage:""});s=await this.streamMultimodalResponse(I,e,r,c),u=this.getSources(S)}else{let S=this.prepareEnhancedUserMessage(p,m);ie("No local search results. Using standard LLM Chain."),s=await this.streamMultimodalResponse(S,e,r,c)}}catch(d){a?.(t_.DEFAULT),d.name==="AbortError"||r.signal.aborted?ie("CopilotPlus stream aborted by user",{reason:r.signal.reason}):await this.handleError(d,o,n)}return r.signal.aborted&&r.signal.reason==="new-chat"?(n(""),""):(r.signal.aborted&&l&&(s=l),this.handleResponse(s,e,r,o,n,u))}getSources(e){return!e||!Array.isArray(e)?(Mh("No valid documents provided to getSources"),[]):this.sortUniqueDocsByScore(e)}sortUniqueDocsByScore(e){let r=new Map;for(let n of e){if(!n.title||!n?.score&&!n?.rerank_score){Mh("Invalid document structure:",n);continue}let o=r.get(n.title),i=n&&"rerank_score"in n,a=i?n.rerank_score:n.score;(!o||a>(o.score??0))&&r.set(n.title,{title:n.title,score:a,isReranked:i})}return Array.from(r.values()).sort((n,o)=>(o.score??0)-(n.score??0))}async executeToolCalls(e,r){let n=[];for(let o of e){ie(`==== Step 2: Calling tool: ${o.tool.name} ====`),o.tool.name==="localSearch"?r?.(t_.READING_FILES):o.tool.name==="webSearch"?r?.(t_.SEARCHING_WEB):o.tool.name==="getFileTree"&&r?.(t_.READING_FILE_TREE);let i=await Pq.callTool(o.tool,o.args);n.push({tool:o.tool.name,output:i})}return n}prepareEnhancedUserMessage(e,r){let n="";if(r.length>0){let o=r.filter(i=>i.output!=null);o.length>0&&(n=`
`,u);let h=new Q6(o),b=await yy(()=>this.chainManager.chatModelManager.getChatModel().stream(u,{signal:n.signal}));for await(let g of b){if(n.signal.aborted){ie("CopilotPlus multimodal stream iteration aborted",{reason:n.signal.reason});break}h.processChunk(g)}return h.close()}async run(e,r,n,o,i){let{updateLoadingMessage:a}=i,s="",u=[],l="",c=d=>{l=d,n(d)};try{if(this.isYoutubeOnlyMessage(e.message)){let S=rge(e.message),x="Transcript not available. Only videos with the auto transcript option turned on are supported at the moment.";if(S)try{let O=await Fi.getInstance().youtube4llm(S);return O.response.transcript?this.handleResponse(O.response.transcript,e,r,o,n):this.handleResponse(x,e,r,o,n)}catch(O){return fe("Error processing YouTube video:",O),this.handleResponse(x,e,r,o,n)}}ie("==== Step 1: Analyzing intent ====");let d,f=e.originalMessage||e.message;try{d=await MN.analyzeIntent(f)}catch(S){return this.handleResponse(fVe(S),e,r,o,n)}let p=e.message.split(" ").filter(S=>!X6.includes(S.toLowerCase())).join(" ").trim(),m=await this.executeToolCalls(d,a),h=m.find(S=>S.tool==="localSearch"&&S.output&&S.output.length>0),g=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),y=LR(g);if(h){ie("==== Step 2: Processing local search results ====");let S=JSON.parse(h.output);ie("==== Step 3: Condensing Question ====");let x=await mie(p,y);ie("Condensed standalone question: ",x),ie("==== Step 4: Preparing context ====");let O=this.getTimeExpression(d),P=this.prepareLocalSearchResult(S,O),E=m.filter(R=>R.tool==="getCurrentTime"),A=this.prepareEnhancedUserMessage(x,E);ie(P),ie("==== Step 5: Invoking QA Chain ====");let I=await this.chainManager.promptManager.getQAPrompt({question:A,context:P,systemMessage:""});s=await this.streamMultimodalResponse(I,e,r,c),u=this.getSources(S)}else{let S=this.prepareEnhancedUserMessage(p,m);ie("No local search results. Using standard LLM Chain."),s=await this.streamMultimodalResponse(S,e,r,c)}}catch(d){a?.(t_.DEFAULT),d.name==="AbortError"||r.signal.aborted?ie("CopilotPlus stream aborted by user",{reason:r.signal.reason}):await this.handleError(d,o,n)}return r.signal.aborted&&r.signal.reason==="new-chat"?(n(""),""):(r.signal.aborted&&l&&(s=l),this.handleResponse(s,e,r,o,n,u))}getSources(e){return!e||!Array.isArray(e)?(Mh("No valid documents provided to getSources"),[]):this.sortUniqueDocsByScore(e)}sortUniqueDocsByScore(e){let r=new Map;for(let n of e){if(!n.title||!n?.score&&!n?.rerank_score){Mh("Invalid document structure:",n);continue}let o=r.get(n.title),i=n&&"rerank_score"in n,a=i?n.rerank_score:n.score;(!o||a>(o.score??0))&&r.set(n.title,{title:n.title,score:a,isReranked:i})}return Array.from(r.values()).sort((n,o)=>(o.score??0)-(n.score??0))}async executeToolCalls(e,r){let n=[];for(let o of e){ie(`==== Step 2: Calling tool: ${o.tool.name} ====`),o.tool.name==="localSearch"?r?.(t_.READING_FILES):o.tool.name==="webSearch"?r?.(t_.SEARCHING_WEB):o.tool.name==="getFileTree"&&r?.(t_.READING_FILE_TREE);let i=await Eq.callTool(o.tool,o.args);n.push({tool:o.tool.name,output:i})}return n}prepareEnhancedUserMessage(e,r){let n="";if(r.length>0){let o=r.filter(i=>i.output!=null);o.length>0&&(n=`
# Additional context:
@@ -630,11 +630,11 @@ IMPORTANT: Maintain consistency with previous responses in the conversation. If
${typeof i.output!="string"?JSON.stringify(i.output):i.output}
</${i.tool}>`).join(`
`))}return`${e}${n}`}getTimeExpression(e){let r=e.find(n=>n.tool.name==="getTimeRangeMs");return r?r.args.timeExpression:""}prepareLocalSearchResult(e,r){let n=e.filter(s=>s.includeInContext),o=n.reduce((s,u)=>s+u.content.length,0),i=n;if(o>oge){let s=oge/o;ie("Truncating documents to fit context length. Truncation ratio:",s),i=n.map(u=>({...u,content:u.content.slice(0,Math.floor(u.content.length*s))}))}let a=i.map(s=>`Note in Vault: ${s.content}`).join(`
`))}return`${e}${n}`}getTimeExpression(e){let r=e.find(n=>n.tool.name==="getTimeRangeMs");return r?r.args.timeExpression:""}prepareLocalSearchResult(e,r){let n=e.filter(s=>s.includeInContext),o=n.reduce((s,u)=>s+u.content.length,0),i=n;if(o>sge){let s=sge/o;ie("Truncating documents to fit context length. Truncation ratio:",s),i=n.map(u=>({...u,content:u.content.slice(0,Math.floor(u.content.length*s))}))}let a=i.map(s=>`Note in Vault: ${s.content}`).join(`
`);return r?`Local Search Result for ${r}:
${a}`:`Local Search Result:
${a}`}async getSystemPrompt(){return Yb()}},zie=class extends e5{async getSystemPrompt(){let e=Yb(),r=Mc();if(!r)return e;let n=await ac.instance.getProjectContext(r.id);return e=`${e}
${a}`}async getSystemPrompt(){return Yb()}},Wie=class extends t5{async getSystemPrompt(){let e=Yb(),r=Mc();if(!r)return e;let n=await ac.instance.getProjectContext(r.id);return e=`${e}
<project_system_prompt>
${r.systemPrompt}
@@ -642,65 +642,65 @@ ${r.systemPrompt}
<project_context>
${n}
</project_context>`),e}};yo();nr();Cn();qE();var Wle=require("obsidian");Cl();$r();BR();yo();nr();Cn();s8();var MN="0.39.0";var zNt=!1,RN,ije,KYr,GYr,JYr,HNt,YYr,Hie,aje,VNt,sje,Vie,WNt;function KNt(t,e={auto:!1}){if(zNt)throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${t.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(RN)throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${t.kind}'\` after \`import '@anthropic-ai/sdk/shims/${RN}'\``);zNt=e.auto,RN=t.kind,ije=t.fetch,KYr=t.Request,GYr=t.Response,JYr=t.Headers,HNt=t.FormData,YYr=t.Blob,Hie=t.File,aje=t.ReadableStream,VNt=t.getMultipartRequestOptions,sje=t.getDefaultAgent,Vie=t.fileFromPath,WNt=t.isFsReadStream}var Wie=class{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}};function GNt({manuallyImported:t}={}){let e=t?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from '@anthropic-ai/sdk'`:\n- `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)\n- `import '@anthropic-ai/sdk/shims/web'` (otherwise)\n",r,n,o,i;try{r=fetch,n=Request,o=Response,i=Headers}catch(a){throw new Error(`this environment is missing the following Web Fetch API type: ${a.message}. ${e}`)}return{kind:"web",fetch:r,Request:n,Response:o,Headers:i,FormData:typeof FormData<"u"?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${e}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${e}`)}},File:typeof File<"u"?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${e}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${e}`)}},getMultipartRequestOptions:async(a,s)=>({...s,body:new Wie(a)}),getDefaultAgent:a=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/anthropics/anthropic-sdk-typescript#file-uploads")},isFsReadStream:a=>!1}}RN||KNt(GNt(),{auto:!0});var Or=class extends Error{},cc=class t extends Or{constructor(e,r,n,o){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=o,this.request_id=o?.["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 wI({message:n,cause:Kie(r)});let i=r;return e===400?new t5(e,i,n,o):e===401?new r5(e,i,n,o):e===403?new n5(e,i,n,o):e===404?new o5(e,i,n,o):e===409?new i5(e,i,n,o):e===422?new a5(e,i,n,o):e===429?new s5(e,i,n,o):e>=500?new u5(e,i,n,o):new t(e,i,n,o)}},ed=class extends cc{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},wI=class extends cc{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Yq=class extends wI{constructor({message:e}={}){super({message:e??"Request timed out."})}},t5=class extends cc{},r5=class extends cc{},n5=class extends cc{},o5=class extends cc{},i5=class extends cc{},a5=class extends cc{},s5=class extends cc{},u5=class extends cc{};var Gie=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},jN=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)},nh,uP=class{constructor(){nh.set(this,void 0),this.buffer=new Uint8Array,Gie(this,nh,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?new TextEncoder().encode(e):e,n=new Uint8Array(this.buffer.length+r.length);n.set(this.buffer),n.set(r,this.buffer.length),this.buffer=n;let o=[],i;for(;(i=QYr(this.buffer,jN(this,nh,"f")))!=null;){if(i.carriage&&jN(this,nh,"f")==null){Gie(this,nh,i.index,"f");continue}if(jN(this,nh,"f")!=null&&(i.index!==jN(this,nh,"f")+1||i.carriage)){o.push(this.decodeText(this.buffer.slice(0,jN(this,nh,"f")-1))),this.buffer=this.buffer.slice(jN(this,nh,"f")),Gie(this,nh,null,"f");continue}let a=jN(this,nh,"f")!==null?i.preceding-1:i.preceding,s=this.decodeText(this.buffer.slice(0,a));o.push(s),this.buffer=this.buffer.slice(i.index),Gie(this,nh,null,"f")}return o}decLine truncated
</project_context>`),e}};yo();nr();yn();qE();var Jle=require("obsidian");Cl();$r();qR();yo();nr();yn();u8();var RN="0.39.0";var GNt=!1,jN,sje,XYr,QYr,eZr,JNt,tZr,Kie,uje,YNt,lje,Gie,ZNt;function XNt(t,e={auto:!1}){if(GNt)throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${t.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(jN)throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${t.kind}'\` after \`import '@anthropic-ai/sdk/shims/${jN}'\``);GNt=e.auto,jN=t.kind,sje=t.fetch,XYr=t.Request,QYr=t.Response,eZr=t.Headers,JNt=t.FormData,tZr=t.Blob,Kie=t.File,uje=t.ReadableStream,YNt=t.getMultipartRequestOptions,lje=t.getDefaultAgent,Gie=t.fileFromPath,ZNt=t.isFsReadStream}var Jie=class{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}};function QNt({manuallyImported:t}={}){let e=t?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from '@anthropic-ai/sdk'`:\n- `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)\n- `import '@anthropic-ai/sdk/shims/web'` (otherwise)\n",r,n,o,i;try{r=fetch,n=Request,o=Response,i=Headers}catch(a){throw new Error(`this environment is missing the following Web Fetch API type: ${a.message}. ${e}`)}return{kind:"web",fetch:r,Request:n,Response:o,Headers:i,FormData:typeof FormData<"u"?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${e}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${e}`)}},File:typeof File<"u"?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${e}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${e}`)}},getMultipartRequestOptions:async(a,s)=>({...s,body:new Jie(a)}),getDefaultAgent:a=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/anthropics/anthropic-sdk-typescript#file-uploads")},isFsReadStream:a=>!1}}jN||XNt(QNt(),{auto:!0});var Or=class extends Error{},cc=class t extends Or{constructor(e,r,n,o){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=o,this.request_id=o?.["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 wI({message:n,cause:Yie(r)});let i=r;return e===400?new r5(e,i,n,o):e===401?new n5(e,i,n,o):e===403?new o5(e,i,n,o):e===404?new i5(e,i,n,o):e===409?new a5(e,i,n,o):e===422?new s5(e,i,n,o):e===429?new u5(e,i,n,o):e>=500?new l5(e,i,n,o):new t(e,i,n,o)}},ed=class extends cc{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},wI=class extends cc{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Zq=class extends wI{constructor({message:e}={}){super({message:e??"Request timed out."})}},r5=class extends cc{},n5=class extends cc{},o5=class extends cc{},i5=class extends cc{},a5=class extends cc{},s5=class extends cc{},u5=class extends cc{},l5=class extends cc{};var Zie=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},NN=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)},nh,uP=class{constructor(){nh.set(this,void 0),this.buffer=new Uint8Array,Zie(this,nh,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?new TextEncoder().encode(e):e,n=new Uint8Array(this.buffer.length+r.length);n.set(this.buffer),n.set(r,this.buffer.length),this.buffer=n;let o=[],i;for(;(i=oZr(this.buffer,NN(this,nh,"f")))!=null;){if(i.carriage&&NN(this,nh,"f")==null){Zie(this,nh,i.index,"f");continue}if(NN(this,nh,"f")!=null&&(i.index!==NN(this,nh,"f")+1||i.carriage)){o.push(this.decodeText(this.buffer.slice(0,NN(this,nh,"f")-1))),this.buffer=this.buffer.slice(NN(this,nh,"f")),Zie(this,nh,null,"f");continue}let a=NN(this,nh,"f")!==null?i.preceding-1:i.preceding,s=this.decodeText(this.buffer.slice(0,a));o.push(s),this.buffer=this.buffer.slice(i.index),Zie(this,nh,null,"f")}return o}decLine truncated
`):[]}};nh=new WeakMap;uP.NEWLINE_CHARS=new Set([`
`,"\r"]);uP.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function QYr(t,e){for(let o=e??0;o<t.length;o++){if(t[o]===10)return{preceding:o,index:o+1,carriage:!1};if(t[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function JNt(t){for(let n=0;n<t.length-1;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}function l5(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 jx=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 eZr(e,r)){if(a.event==="completion")try{yield JSON.parse(a.data)}catch(s){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),s}if(a.event==="message_start"||a.event==="message_delta"||a.event==="message_stop"||a.event==="content_block_start"||a.event==="content_block_delta"||a.event==="content_block_stop")try{yield JSON.parse(a.data)}catch(s){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),s}if(a.event!=="ping"&&a.event==="error")throw cc.generate(void 0,`SSE Error: ${a.data}`,a.data,lje(e.headers))}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 uP,s=l5(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 aje({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?.()}})}};async function*eZr(t,e){if(!t.body)throw e.abort(),new Or("Attempted to iterate over a response with no body");let r=new uje,n=new uP,o=l5(t.body);for await(let i of tZr(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*tZr(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=JNt(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}var uje=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]=rZr(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}};function rZr(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var nZr=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",oZr=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&c5(t),c5=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";async function YNt(t,e,r){if(t=await t,oZr(t))return t;if(nZr(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=c5(o)?[await o.arrayBuffer()]:[o];return new Hie(i,e,r)}let n=await iZr(t);if(e||(e=sZr(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new Hie(n,e,r)}async function iZr(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(c5(t))e.push(await t.arrayBuffer());else if(uZr(t))for await(let r of t)e.push(r);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${aZr(t)}`);return e}function aZr(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function sZr(t){return cje(t.name)||cje(t.filename)||cje(t.path)?.split(/[\\/]/).pop()}var cje=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},uZr=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",dje=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody";var cZr=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},dZr=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)},Jie;async function tDt(t){let{response:e}=t;if(t.options.stream)return Zq("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):jx.fromSSEResponse(e,t.controller);if(e.status===204)return null;if(t.options.__binaryResponse)return e;let r=e.headers.get("content-type");if(r?.includes("application/json")||r?.includes("application/vnd.api+json")){let i=await e.json();return Zq("response",e.status,e.url,e.headers,i),rDt(i,e)}let o=await e.text();return Zq("response",e.status,e.url,e.headers,o),o}function rDt(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 Zie=class t extends Promise{constructor(e,r=tDt){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=r}_thenUnwrap(e){return new t(this.responsePromise,async r=>rDt(e(await this.parseResponse(r),r),r.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(this.parseResponse)),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)}},Xie=class{constructor({baseURL:e,maxRetries:r=2,timeout:n=6e5,httpAgent:o,fetch:i}){this.baseURL=e,this.maxRetries=fje("maxRetries",r),this.timeout=fje("timeout",n),this.httpAgent=o,this.fetch=i??ije}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...hZr(),...this.authHeaders(e)}}validateHeaders(e,r){}defaultIdempotencyKey(){return`stainless-node-retry-${vZr()}`}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(async o=>{let i=o&&c5(o?.body)?new DataView(await o.body.arrayBuffer()):o?.body instanceof DataView?o.body:o?.body instanceof ArrayBuffer?new DataView(o.body):o&&ArrayBuffer.isView(o?.body)?new DataView(o.body.buffer):o?.body;return{method:e,path:r,...o,body:i}}))}getAPIList(e,r,n){return this.requestAPIList(r,{method:"get", Line truncated
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages?beta=true",{body:o,timeout:this._client._options.timeout??(o.stream?6e5:this._client._calculateNonstreamingTimeout(o.max_tokens)),...r,headers:{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...r?.headers},stream:e.stream??!1})}stream(e,r){return uae.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:{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString(),...r?.headers}})}};xI.Batches=DN;xI.BetaMessageBatchesPage=eU;var Dx=class extends dc{constructor(){super(...arguments),this.models=new NN(this._client),this.messages=new xI(this._client)}};Dx.Models=NN;Dx.BetaModelInfosPage=Xq;Dx.Messages=xI;var LN=class extends dc{create(e,r){return this._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...r,stream:e.stream??!1})}};var FN=class extends dc{create(e,r){return this._client.post("/v1/messages/batches",{body:e,...r})}retrieve(e,r){return this._client.get(`/v1/messages/batches/${e}`,r)}list(e={},r){return Pg(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",nU,{query:e,...r})}delete(e,r){return this._client.delete(`/v1/messages/batches/${e}`,r)}cancel(e,r){return this._client.post(`/v1/messages/batches/${e}/cancel`,r)}async results(e,r){let n=await this.retrieve(e);if(!n.results_url)throw new Or(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...r,headers:{Accept:"application/binary",...r?.headers},__binaryResponse:!0})._thenUnwrap((o,i)=>Qq.fromResponse(i.response,i.controller))}},nU=class extends Nx{};FN.MessageBatchesPage=nU;var af=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},_n=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)},Tg,CI,y5,lae,b5,_5,cae,v5,cP,w5,dae,fae,oU,pae,mae,_je,lDt,vje,wje,Sje,xje,cDt,dDt="__json_buf",hae=class t{constructor(){Tg.add(this),this.messages=[],this.receivedMessages=[],CI.set(this,void 0),this.controller=new AbortController,y5.set(this,void 0),lae.set(this,()=>{}),b5.set(this,()=>{}),_5.set(this,void 0),cae.set(this,()=>{}),v5.set(this,()=>{}),cP.set(this,{}),w5.set(this,!1),dae.set(this,!1),fae.set(this,!1),oU.set(this,!1),pae.set(this,void 0),mae.set(this,void 0),vje.set(this,e=>{if(af(this,dae,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new ed),e instanceof ed)return af(this,fae,!0,"f"),this._emit("abort",e);if(e instanceof Or)return this._emit("error",e);if(e instanceof Error){let r=new Or(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new Or(String(e)))}),af(this,y5,new Promise((e,r)=>{af(this,lae,e,"f"),af(this,b5,r,"f")}),"f"),af(this,_5,new Promise((e,r)=>{af(this,cae,e,"f"),af(this,v5,r,"f")}),"f"),_n(this,y5,"f").catch(()=>{}),_n(this,_5,"f").catch(()=>{})}get response(){return _n(this,pae,"f")}get request_id(){return _n(this,mae,"f")}async withResponse(){let e=await _n(this,y5,"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")},_n(this,vje,"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;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),_n(this,Tg,"m",wje).call(this);let{response:i,data:a}=await e.create({...r,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(i);for await(let s of a)_n(this,Tg,"m",Sje).call(this,s);if(a.controller.signal?.aborted)throw new ed;_n(this,Tg,"m",xje).call(this)}_connected(e){this.ended||(af(this,pae,e,"f"),af(this,mae,e?.headers.get("request-id"),"f"),_n(this,lae,"f").call(this,e),this._emit("connect"))}get ended(){return _n(this,w5,"f")}get errored(){return _n(this,dae,"f")}get aborted(){return _n(this,fae,"f")}abort() Line truncated
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages",{body:e,timeout:this._client._options.timeout??(e.stream?6e5:this._client._calculateNonstreamingTimeout(e.max_tokens)),...r,stream:e.stream??!1})}stream(e,r){return hae.createMessage(this,e,r)}countTokens(e,r){return this._client.post("/v1/messages/count_tokens",{body:e,...r})}},fDt={"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-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};dP.Batches=FN;dP.MessageBatchesPage=nU;var OI=class extends dc{retrieve(e,r){return this._client.get(`/v1/models/${e}`,r)}list(e={},r){return Pg(e)?this.list({},e):this._client.getAPIList("/v1/models",kN,{query:e,...r})}},kN=class extends Nx{};OI.ModelInfosPage=kN;var pDt,mi=class extends Xie{constructor({baseURL:e=eae("ANTHROPIC_BASE_URL"),apiKey:r=eae("ANTHROPIC_API_KEY")??null,authToken:n=eae("ANTHROPIC_AUTH_TOKEN")??null,...o}={}){let i={apiKey:r,authToken:n,...o,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&oDt())throw new Or(`It looks like you're running in a browser-like environment.
`,"\r"]);uP.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function oZr(t,e){for(let o=e??0;o<t.length;o++){if(t[o]===10)return{preceding:o,index:o+1,carriage:!1};if(t[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function eDt(t){for(let n=0;n<t.length-1;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}function c5(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 Nx=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 iZr(e,r)){if(a.event==="completion")try{yield JSON.parse(a.data)}catch(s){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),s}if(a.event==="message_start"||a.event==="message_delta"||a.event==="message_stop"||a.event==="content_block_start"||a.event==="content_block_delta"||a.event==="content_block_stop")try{yield JSON.parse(a.data)}catch(s){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),s}if(a.event!=="ping"&&a.event==="error")throw cc.generate(void 0,`SSE Error: ${a.data}`,a.data,dje(e.headers))}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 uP,s=c5(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 uje({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?.()}})}};async function*iZr(t,e){if(!t.body)throw e.abort(),new Or("Attempted to iterate over a response with no body");let r=new cje,n=new uP,o=c5(t.body);for await(let i of aZr(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*aZr(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=eDt(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}var cje=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]=sZr(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}};function sZr(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var uZr=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",lZr=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&d5(t),d5=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";async function tDt(t,e,r){if(t=await t,lZr(t))return t;if(uZr(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=d5(o)?[await o.arrayBuffer()]:[o];return new Kie(i,e,r)}let n=await cZr(t);if(e||(e=fZr(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new Kie(n,e,r)}async function cZr(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(d5(t))e.push(await t.arrayBuffer());else if(pZr(t))for await(let r of t)e.push(r);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${dZr(t)}`);return e}function dZr(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function fZr(t){return fje(t.name)||fje(t.filename)||fje(t.path)?.split(/[\\/]/).pop()}var fje=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},pZr=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",pje=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody";var hZr=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},gZr=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)},Xie;async function aDt(t){let{response:e}=t;if(t.options.stream)return Xq("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):Nx.fromSSEResponse(e,t.controller);if(e.status===204)return null;if(t.options.__binaryResponse)return e;let r=e.headers.get("content-type");if(r?.includes("application/json")||r?.includes("application/vnd.api+json")){let i=await e.json();return Xq("response",e.status,e.url,e.headers,i),sDt(i,e)}let o=await e.text();return Xq("response",e.status,e.url,e.headers,o),o}function sDt(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 eae=class t extends Promise{constructor(e,r=aDt){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=r}_thenUnwrap(e){return new t(this.responsePromise,async r=>sDt(e(await this.parseResponse(r),r),r.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(this.parseResponse)),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)}},tae=class{constructor({baseURL:e,maxRetries:r=2,timeout:n=6e5,httpAgent:o,fetch:i}){this.baseURL=e,this.maxRetries=mje("maxRetries",r),this.timeout=mje("timeout",n),this.httpAgent=o,this.fetch=i??sje}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...vZr(),...this.authHeaders(e)}}validateHeaders(e,r){}defaultIdempotencyKey(){return`stainless-node-retry-${OZr()}`}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(async o=>{let i=o&&d5(o?.body)?new DataView(await o.body.arrayBuffer()):o?.body instanceof DataView?o.body:o?.body instanceof ArrayBuffer?new DataView(o.body):o&&ArrayBuffer.isView(o?.body)?new DataView(o.body.buffer):o?.body;return{method:e,path:r,...o,body:i}}))}getAPIList(e,r,n){return this.requestAPIList(r,{method:"get", Line truncated
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages?beta=true",{body:o,timeout:this._client._options.timeout??(o.stream?6e5:this._client._calculateNonstreamingTimeout(o.max_tokens)),...r,headers:{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...r?.headers},stream:e.stream??!1})}stream(e,r){return dae.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:{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString(),...r?.headers}})}};xI.Batches=LN;xI.BetaMessageBatchesPage=tU;var Lx=class extends dc{constructor(){super(...arguments),this.models=new DN(this._client),this.messages=new xI(this._client)}};Lx.Models=DN;Lx.BetaModelInfosPage=Qq;Lx.Messages=xI;var FN=class extends dc{create(e,r){return this._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...r,stream:e.stream??!1})}};var kN=class extends dc{create(e,r){return this._client.post("/v1/messages/batches",{body:e,...r})}retrieve(e,r){return this._client.get(`/v1/messages/batches/${e}`,r)}list(e={},r){return Pg(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",oU,{query:e,...r})}delete(e,r){return this._client.delete(`/v1/messages/batches/${e}`,r)}cancel(e,r){return this._client.post(`/v1/messages/batches/${e}/cancel`,r)}async results(e,r){let n=await this.retrieve(e);if(!n.results_url)throw new Or(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...r,headers:{Accept:"application/binary",...r?.headers},__binaryResponse:!0})._thenUnwrap((o,i)=>eU.fromResponse(i.response,i.controller))}},oU=class extends Dx{};kN.MessageBatchesPage=oU;var af=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},vn=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)},Tg,CI,b5,fae,_5,v5,pae,w5,cP,S5,mae,hae,iU,gae,yae,wje,mDt,Sje,xje,Cje,Oje,hDt,gDt="__json_buf",bae=class t{constructor(){Tg.add(this),this.messages=[],this.receivedMessages=[],CI.set(this,void 0),this.controller=new AbortController,b5.set(this,void 0),fae.set(this,()=>{}),_5.set(this,()=>{}),v5.set(this,void 0),pae.set(this,()=>{}),w5.set(this,()=>{}),cP.set(this,{}),S5.set(this,!1),mae.set(this,!1),hae.set(this,!1),iU.set(this,!1),gae.set(this,void 0),yae.set(this,void 0),Sje.set(this,e=>{if(af(this,mae,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new ed),e instanceof ed)return af(this,hae,!0,"f"),this._emit("abort",e);if(e instanceof Or)return this._emit("error",e);if(e instanceof Error){let r=new Or(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new Or(String(e)))}),af(this,b5,new Promise((e,r)=>{af(this,fae,e,"f"),af(this,_5,r,"f")}),"f"),af(this,v5,new Promise((e,r)=>{af(this,pae,e,"f"),af(this,w5,r,"f")}),"f"),vn(this,b5,"f").catch(()=>{}),vn(this,v5,"f").catch(()=>{})}get response(){return vn(this,gae,"f")}get request_id(){return vn(this,yae,"f")}async withResponse(){let e=await vn(this,b5,"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")},vn(this,Sje,"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;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),vn(this,Tg,"m",xje).call(this);let{response:i,data:a}=await e.create({...r,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(i);for await(let s of a)vn(this,Tg,"m",Cje).call(this,s);if(a.controller.signal?.aborted)throw new ed;vn(this,Tg,"m",Oje).call(this)}_connected(e){this.ended||(af(this,gae,e,"f"),af(this,yae,e?.headers.get("request-id"),"f"),vn(this,fae,"f").call(this,e),this._emit("connect"))}get ended(){return vn(this,S5,"f")}get errored(){return vn(this,mae,"f")}get aborted(){return vn(this,hae,"f")}abort() Line truncated
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages",{body:e,timeout:this._client._options.timeout??(e.stream?6e5:this._client._calculateNonstreamingTimeout(e.max_tokens)),...r,stream:e.stream??!1})}stream(e,r){return bae.createMessage(this,e,r)}countTokens(e,r){return this._client.post("/v1/messages/count_tokens",{body:e,...r})}},yDt={"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-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};dP.Batches=kN;dP.MessageBatchesPage=oU;var OI=class extends dc{retrieve(e,r){return this._client.get(`/v1/models/${e}`,r)}list(e={},r){return Pg(e)?this.list({},e):this._client.getAPIList("/v1/models",$N,{query:e,...r})}},$N=class extends Dx{};OI.ModelInfosPage=$N;var bDt,mi=class extends tae{constructor({baseURL:e=nae("ANTHROPIC_BASE_URL"),apiKey:r=nae("ANTHROPIC_API_KEY")??null,authToken:n=nae("ANTHROPIC_AUTH_TOKEN")??null,...o}={}){let i={apiKey:r,authToken:n,...o,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&lDt())throw new Or(`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 });
`);super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new LN(this),this.messages=new dP(this),this.models=new OI(this),this.beta=new Dx(this),this._options=i,this.apiKey=r,this.authToken=n}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01",...this._options.defaultHeaders}}validateHeaders(e,r){if(!(this.apiKey&&e["x-api-key"])&&r["x-api-key"]!==null&&!(this.authToken&&e.authorization)&&r.authorization!==null)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')}authHeaders(e){let r=this.apiKeyAuth(e),n=this.bearerAuth(e);return r!=null&&!d5(r)?r:n!=null&&!d5(n)?n:{}}apiKeyAuth(e){return this.apiKey==null?{}:{"X-Api-Key":this.apiKey}}bearerAuth(e){return this.authToken==null?{}:{Authorization:`Bearer ${this.authToken}`}}};pDt=mi;mi.Anthropic=pDt;mi.HUMAN_PROMPT=`
`);super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new FN(this),this.messages=new dP(this),this.models=new OI(this),this.beta=new Lx(this),this._options=i,this.apiKey=r,this.authToken=n}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01",...this._options.defaultHeaders}}validateHeaders(e,r){if(!(this.apiKey&&e["x-api-key"])&&r["x-api-key"]!==null&&!(this.authToken&&e.authorization)&&r.authorization!==null)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')}authHeaders(e){let r=this.apiKeyAuth(e),n=this.bearerAuth(e);return r!=null&&!f5(r)?r:n!=null&&!f5(n)?n:{}}apiKeyAuth(e){return this.apiKey==null?{}:{"X-Api-Key":this.apiKey}}bearerAuth(e){return this.authToken==null?{}:{Authorization:`Bearer ${this.authToken}`}}};bDt=mi;mi.Anthropic=bDt;mi.HUMAN_PROMPT=`
Human:`;mi.AI_PROMPT=`
Assistant:`;mi.DEFAULT_TIMEOUT=6e5;mi.AnthropicError=Or;mi.APIError=cc;mi.APIConnectionError=wI;mi.APIConnectionTimeoutError=Yq;mi.APIUserAbortError=ed;mi.NotFoundError=o5;mi.ConflictError=i5;mi.RateLimitError=s5;mi.BadRequestError=t5;mi.AuthenticationError=r5;mi.InternalServerError=u5;mi.PermissionDeniedError=n5;mi.UnprocessableEntityError=a5;mi.toFile=YNt;mi.fileFromPath=Vie;mi.Completions=LN;mi.Messages=dP;mi.Models=OI;mi.ModelInfosPage=kN;mi.Beta=Dx;var{HUMAN_PROMPT:lWo,AI_PROMPT:cWo}=mi;gs();Qd();Dn();fx();Wm();Ec();Sm();pB();Km();gy();var S5=class extends PR{static lc_name(){return"AnthropicToolsOutputParser"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","anthropic","output_parsers"]}),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"keyName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"returnSingle",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"zodSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){let r=e;if(typeof e=="string")try{r=JSON.parse(e)}catch(o){throw new vm(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(o.message)}`,e)}else r=e;if(this.zodSchema===void 0)return r;let n=await this.zodSchema.safeParseAsync(r);if(n.success)return n.data;throw new vm(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.errors)}`,JSON.stringify(r,null,2))}async parseResult(e){let r=e.flatMap(i=>{let{message:a}=i;return Array.isArray(a.content)?Cje(a.content)[0]:[]});if(r[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");let[n]=r;return await this._validateResult(n.args)}};function Cje(t){let e=[];for(let r of t)r.type==="tool_use"&&e.push({name:r.name,args:r.input,id:r.id,type:"tool_call"});return e}function mDt(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:typeof t=="string"?{type:"tool",name:t}:t}gs();function hDt(t){return t==null||typeof t!="object"||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}function gDt(t){let e=ame({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let r;try{r=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
Assistant:`;mi.DEFAULT_TIMEOUT=6e5;mi.AnthropicError=Or;mi.APIError=cc;mi.APIConnectionError=wI;mi.APIConnectionTimeoutError=Zq;mi.APIUserAbortError=ed;mi.NotFoundError=i5;mi.ConflictError=a5;mi.RateLimitError=u5;mi.BadRequestError=r5;mi.AuthenticationError=n5;mi.InternalServerError=l5;mi.PermissionDeniedError=o5;mi.UnprocessableEntityError=s5;mi.toFile=tDt;mi.fileFromPath=Gie;mi.Completions=FN;mi.Messages=dP;mi.Models=OI;mi.ModelInfosPage=$N;mi.Beta=Lx;var{HUMAN_PROMPT:yWo,AI_PROMPT:bWo}=mi;gs();Qd();Dn();fx();Wm();Ec();Sm();mB();Km();gy();var x5=class extends PR{static lc_name(){return"AnthropicToolsOutputParser"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","anthropic","output_parsers"]}),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"keyName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"returnSingle",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"zodSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){let r=e;if(typeof e=="string")try{r=JSON.parse(e)}catch(o){throw new vm(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(o.message)}`,e)}else r=e;if(this.zodSchema===void 0)return r;let n=await this.zodSchema.safeParseAsync(r);if(n.success)return n.data;throw new vm(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.errors)}`,JSON.stringify(r,null,2))}async parseResult(e){let r=e.flatMap(i=>{let{message:a}=i;return Array.isArray(a.content)?Pje(a.content)[0]:[]});if(r[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");let[n]=r;return await this._validateResult(n.args)}};function Pje(t){let e=[];for(let r of t)r.type==="tool_use"&&e.push({name:r.name,args:r.input,id:r.id,type:"tool_call"});return e}function _Dt(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:typeof t=="string"?{type:"tool",name:t}:t}gs();function vDt(t){return t==null||typeof t!="object"||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}function wDt(t){let e=lme({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let r;try{r=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
`))}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 MZr(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 Os({content:[{type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}]}))}else e.push(new Os({content:[{type:"tool_result",content:Oje(r.content),tool_use_id:r.tool_call_id}]}));else e.push(r);return e}function yDt(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}}var RZr={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){let e=ame({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){let e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}};function Oje(t){let e=["tool_use","tool_result","input_json_delta"],r=["text","text_delta"];return typeof t=="string"?t:t.map(o=>{if(jE(o))return H4e(o,RZr);let i="cache_control"in o?o.cache_control:void 0;if(o.type==="image_url"){let a;return typeof o.image_url=="string"?a=gDt(o.image_url):a=gDt(o.image_url.url),{type:"image",source:a,...i?{cache_control:i}:{}}}else{if(hDt(o))return o;if(o.type==="document")return{...o,...i?{cache_control:i}:{}};if(o.type==="thinking")return{type:"thinking",thinking:o.thinking,signature:o.signature,...i?{cache_control:i}:{}};if(o.type==="redacted_thinking")return{type:"redacted_thinking",data:o.data,...i?{cache_control:i}:{}};if(r.find(a=>a===o.type)&&"text"in o)return{type:"text",text:o.text,...i?{cache_control:i}:{}};if(e.find(a=>a===o.type)){let a={...o};if("index"in a&&delete a.index,a.type==="input_json_delta"&&(a.type="tool_use"),"input"in a&&typeof a.input=="string")try{a.input=JSON.parse(a.input)}catch{a.input={}}return{...a,...i?{cache_control:i}:{}}}else throw new Error("Unsupported message content format")}})}function gae(t){let e=MZr(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._ge Line truncated
`))}function LZr(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 Os({content:[{type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}]}))}else e.push(new Os({content:[{type:"tool_result",content:Eje(r.content),tool_use_id:r.tool_call_id}]}));else e.push(r);return e}function SDt(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}}var FZr={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){let e=lme({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){let e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}};function Eje(t){let e=["tool_use","tool_result","input_json_delta"],r=["text","text_delta"];return typeof t=="string"?t:t.map(o=>{if(jE(o))return W4e(o,FZr);let i="cache_control"in o?o.cache_control:void 0;if(o.type==="image_url"){let a;return typeof o.image_url=="string"?a=wDt(o.image_url):a=wDt(o.image_url.url),{type:"image",source:a,...i?{cache_control:i}:{}}}else{if(vDt(o))return o;if(o.type==="document")return{...o,...i?{cache_control:i}:{}};if(o.type==="thinking")return{type:"thinking",thinking:o.thinking,signature:o.signature,...i?{cache_control:i}:{}};if(o.type==="redacted_thinking")return{type:"redacted_thinking",data:o.data,...i?{cache_control:i}:{}};if(r.find(a=>a===o.type)&&"text"in o)return{type:"text",text:o.text,...i?{cache_control:i}:{}};if(e.find(a=>a===o.type)){let a={...o};if("index"in a&&delete a.index,a.type==="input_json_delta"&&(a.type="tool_use"),"input"in a&&typeof a.input=="string")try{a.input=JSON.parse(a.input)}catch{a.input={}}return{...a,...i?{cache_control:i}:{}}}else throw new Error("Unsupported message content format")}})}function _ae(t){let e=LZr(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._ge Line truncated
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
`,t}function Pje(t){let e;return t.status===400&&t.message.includes("tool")?e=yae(t,"INVALID_TOOL_RESULTS"):t.status===401?e=yae(t,"MODEL_AUTHENTICATION"):t.status===404?e=yae(t,"MODEL_NOT_FOUND"):t.status===429?e=yae(t,"MODEL_RATE_LIMIT"):e=t,e}function NZr(t){return!!(t.tools&&t.tools.length>0)}function DZr(t){for(let e of t.messages??[])if(typeof e.content!="string"){for(let r of e.content??[])if(typeof r=="object"&&r!=null&&r.type==="document"&&typeof r.citations=="object"&&r.citations.enabled)return!0}return!1}function LZr(t){return!!(t.thinking&&t.thinking.type==="enabled")}function FZr(t){return"input_schema"in t}function kZr(t){if(typeof t.content=="string")return t.content;if(Array.isArray(t.content)&&t.content.length>=1&&"input"in t.content[0])return typeof t.content[0].input=="string"?t.content[0].input:JSON.stringify(t.content[0].input);if(Array.isArray(t.content)&&t.content.length>=1&&"text"in t.content[0])return t.content[0].text}var Eje=class extends Js{static lc_name(){return"ChatAnthropic"}get lc_secrets(){return{anthropicApiKey:"ANTHROPIC_API_KEY",apiKey:"ANTHROPIC_API_KEY"}}get lc_aliases(){return{modelName:"model"}}constructor(e){if(super(e??{}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"anthropicApiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"topK",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:2048}),Object.defineProperty(this,"modelName",{enumerable:!0,configurable:!0,writable:!0,value:"claude-2.1"}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"claude-2.1"}),Object.defineProperty(this,"invocationKwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stopSequences",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"clientOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"thinking",{enumerable:!0,configurable:!0,writable:!0,value:{type:"disabled"}}),Object.defineProperty(this,"batchClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streamingClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streamUsage",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"createClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.anthropicApiKey=e?.apiKey??e?.anthropicApiKey??ot("ANTHROPIC_API_KEY"),!this.anthropicApiKey&&!e?.createClient)throw new Error("Anthropic API key not found");this.clientOptions=e?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=e?.anthropicApiUrl,this.modelName=e?.model??e?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=e?.invocationKwargs??{},this.temperature=e?.temperature??this.temperature,this.topK=e?.topK??this.topK,this.topP=e?.topP??this.topP,this.maxTokens=e?.maxTokensToSample??e?.maxTokens??this.maxTokens,this.stopSequences=e?.stopSequences??this.stopSequences,this.streaming=e?.streaming??!1,this.streamUsage=e?.streamUsage??this.streamUsage,this.thinking=e?.thinking??this.thinking,this.createClient=e?.createClient??(r=>new mi(r))}getLsParams(e){let r=this.invocationParams(e);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:r.temperature??void 0,ls_max_tokens:r.max_tokens??void 0,ls_stop:e.stop}}formatStructuredToolToAnthropic(e){if(!(!e||!e.length))return e.map(r=>{if(FZr(r))return r;if(Wc(r))return{name:r.function.name,description:r.function.description,input_schema:r.function.parameters};if(rc(r))return{name:r.name,description:r.description,input_schema:Gs(r.schema)?So(r.schema):r.schema};throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(r,null,2)}`)})}bindTools(e,r){return this.bind({tools:this.formatStructuredToolToAnthropic(e),...r})}invocationParams(e){let r=mDt(e?.tool_choice);if(this.thinking.type==="enabled"){if(this.topK!==-1)throw new Error("topK is not supported when thinking is enabled");if(this.topP!==-1)throw new Error("topP is not supported when thinking is enabled");if(this.temperature!==1)throw new Error("temperature is not supported when thinking is enabled");return{model:this.model,stop_sequences:e?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this. Line truncated
`,t}function Tje(t){let e;return t.status===400&&t.message.includes("tool")?e=vae(t,"INVALID_TOOL_RESULTS"):t.status===401?e=vae(t,"MODEL_AUTHENTICATION"):t.status===404?e=vae(t,"MODEL_NOT_FOUND"):t.status===429?e=vae(t,"MODEL_RATE_LIMIT"):e=t,e}function $Zr(t){return!!(t.tools&&t.tools.length>0)}function BZr(t){for(let e of t.messages??[])if(typeof e.content!="string"){for(let r of e.content??[])if(typeof r=="object"&&r!=null&&r.type==="document"&&typeof r.citations=="object"&&r.citations.enabled)return!0}return!1}function qZr(t){return!!(t.thinking&&t.thinking.type==="enabled")}function UZr(t){return"input_schema"in t}function zZr(t){if(typeof t.content=="string")return t.content;if(Array.isArray(t.content)&&t.content.length>=1&&"input"in t.content[0])return typeof t.content[0].input=="string"?t.content[0].input:JSON.stringify(t.content[0].input);if(Array.isArray(t.content)&&t.content.length>=1&&"text"in t.content[0])return t.content[0].text}var Aje=class extends Js{static lc_name(){return"ChatAnthropic"}get lc_secrets(){return{anthropicApiKey:"ANTHROPIC_API_KEY",apiKey:"ANTHROPIC_API_KEY"}}get lc_aliases(){return{modelName:"model"}}constructor(e){if(super(e??{}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"anthropicApiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"topK",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:2048}),Object.defineProperty(this,"modelName",{enumerable:!0,configurable:!0,writable:!0,value:"claude-2.1"}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"claude-2.1"}),Object.defineProperty(this,"invocationKwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stopSequences",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"clientOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"thinking",{enumerable:!0,configurable:!0,writable:!0,value:{type:"disabled"}}),Object.defineProperty(this,"batchClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streamingClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streamUsage",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"createClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.anthropicApiKey=e?.apiKey??e?.anthropicApiKey??ot("ANTHROPIC_API_KEY"),!this.anthropicApiKey&&!e?.createClient)throw new Error("Anthropic API key not found");this.clientOptions=e?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=e?.anthropicApiUrl,this.modelName=e?.model??e?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=e?.invocationKwargs??{},this.temperature=e?.temperature??this.temperature,this.topK=e?.topK??this.topK,this.topP=e?.topP??this.topP,this.maxTokens=e?.maxTokensToSample??e?.maxTokens??this.maxTokens,this.stopSequences=e?.stopSequences??this.stopSequences,this.streaming=e?.streaming??!1,this.streamUsage=e?.streamUsage??this.streamUsage,this.thinking=e?.thinking??this.thinking,this.createClient=e?.createClient??(r=>new mi(r))}getLsParams(e){let r=this.invocationParams(e);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:r.temperature??void 0,ls_max_tokens:r.max_tokens??void 0,ls_stop:e.stop}}formatStructuredToolToAnthropic(e){if(!(!e||!e.length))return e.map(r=>{if(UZr(r))return r;if(Wc(r))return{name:r.function.name,description:r.function.description,input_schema:r.function.parameters};if(rc(r))return{name:r.name,description:r.description,input_schema:Gs(r.schema)?So(r.schema):r.schema};throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(r,null,2)}`)})}bindTools(e,r){return this.bind({tools:this.formatStructuredToolToAnthropic(e),...r})}invocationParams(e){let r=_Dt(e?.tool_choice);if(this.thinking.type==="enabled"){if(this.topK!==-1)throw new Error("topK is not supported when thinking is enabled");if(this.topP!==-1)throw new Error("topP is not supported when thinking is enabled");if(this.temperature!==1)throw new Error("temperature is not supported when thinking is enabled");return{model:this.model,stop_sequences:e?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this. Line truncated
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
`,t}function BN(t){let e;return t.constructor.name===Xf.name?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===Li.name?(e=new Error(t.message),e.name="AbortError"):t.status===400&&t.message.includes("tool_calls")?e=x5(t,"INVALID_TOOL_RESULTS"):t.status===401?e=x5(t,"MODEL_AUTHENTICATION"):t.status===429?e=x5(t,"MODEL_RATE_LIMIT"):t.status===404?e=x5(t,"MODEL_NOT_FOUND"):e=t,e}function Tje(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 $Zr(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function vDt(t){let e=["namespace functions {",""];for(let r of t)r.description&&e.push(`// ${r.description}`),Object.keys(r.parameters.properties??{}).length>0?(e.push(`type ${r.name} = (_: {`),e.push(wDt(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
`)}function wDt(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}: ${_ae(o,e)},`):r.push(`${n}?: ${_ae(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
`)}function _ae(t,e){if($Zr(t))return t.anyOf.map(r=>_ae(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["{",wDt(t,e+2),"}"].join(`
`);case"array":return t.items?`${_ae(t.items,e)}[]`:"any[]";default:return""}}Km();sq();function SDt(t,e){let r;if(rc(t)){let n=$ne({name:t.name,parameters:t.schema,description:t.description});n.function.parameters?r={type:n.type,function:{name:n.function.name,description:n.function.description,parameters:n.function.parameters,...e?.strict!==void 0?{strict:e.strict}:{}}}:r={type:"function",function:TA(t,e)}}else r=t;return e?.strict!==void 0&&(r.function.strict=e.strict),r}function BZr(t){return t.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}function Mje(t){let e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":{if(!Cs.isInstance(t))throw new Error("Invalid generic chat message");return BZr(t)}default:throw new Error(`Unknown message type: ${e}`)}}function Ije(t,e){return t.flatMap(r=>{let n=Mje(r);n==="system"&&Rje(e)&&(n="developer");let o={role:n,content:r.content};if(r.name!=null&&(o.name=r.name),r.additional_kwargs.function_call!=null&&(o.function_call=r.additional_kwargs.function_call,o.content=""),Oi(r)&&r.tool_calls?.length?(o.tool_calls=r.tool_calls.map(Ox),o.content=""):(r.additional_kwargs.tool_calls!=null&&(o.tool_calls=r.additional_kwargs.tool_calls),r.tool_call_id!=null&&(o.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio){let i={role:"assistant",audio:{id:r.additional_kwargs.audio.id}};return[o,i]}return o})}var iU="__openai_function_call_ids__";function xDt(t,e){return t.flatMap(r=>{let n=Mje(r);if(n==="system"&&Rje(e)&&(n="developer"),n==="function")throw new Error("Function messages are not supported in Responses API");if(n==="tool"){let o=r;return o.additional_kwargs?.type==="computer_call_output"?{type:"computer_call_output",output:(()=>{if(typeof o.content=="string")return{type:"computer_screenshot",image_url:o.content};if(Array.isArray(o.content)){let a=o.content.find(u=>u.type==="computer_screenshot");if(a)return a;let s=o.content.find(u=>u.type==="image_url");if(s)return{type:"computer_screenshot",image_url:typeof s.image_url=="string"?s.image_url:s.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:o.tool_call_id}:{type:"function_call_output",call_id:o.tool_call_id,id:o.id,output:typeof o.content!="string"?JSON.stringify(o.content):o.content}}if(n==="assistant"){let o=[];r.additional_kwargs.reasoning!=null&&(u=>typeof u=="object"&&u!=null&&"type"in u&&u.type==="reasoning")(r.additional_kwargs.reasoning)&&o.push(r.additional_kwargs.reasoning);let{content:i}=r;r.additional_kwargs.refusal!=null&&(typeof i=="string"&&(i=[{type:"output_text",text:i,annotations:[]}]),i=[...i,{type:"refusal",refusal:r.additional_kwargs.refusal}]),o.push({type:"message",role:"assistant",content:typeof i=="string"?i:i.flatMap(s=>s.type==="text"?{type:"output_text",text:s.text,annotations:s.annotations??[]}:s.type==="output_text"||s.type==="refusal"?s:[])});let a=r.additional_kwargs[iU];if(Oi(r)&&r.tool_calls?.length?o.push(...r.tool_calls.map(s=>({type:"function_call",name:s.name,arguments:JSON.stringify(s.args),call_id:s.id,id:a?.[s.id]}))):r.additional_kwargs.tool_calls!=null&&o.push(...r.additional_kwargs.tool_calls.map(s=>({type:"function_call",name:s.function.name,call_id:s.id,id:a?.[s.id],arguments:s.function.arguments}))),r.additional_kwargs.tool_outputs!=null){let u=r.additional_kwargs.tool_outputs?.filter(l=>l.type==="computer_call");u.length>0&&o.push(...u)}return o}return n==="user"?{type:"message",role:"user",content:typeof r.content=="string"?r.content:r.content.flatMap(o=>{if(o.type==="text")return{type:"input_text",text:o.text};if(o.type==="image_url"){let i=typeof o.image_url=="string"?o.image_url:o.image_url.url,a=typeof o.image_url=="string"?"auto":o.image_url.detail;return{type:"input_image",image_url:i,detail:a}}return o.type==="input_text"||o.type==="input_image"||o.type==="input_file"?o:[]})}:[]})}function ODt(t){if(t.error){let a=new Error(t.error.message);throw a.name=t.error.code,a}let e=[],r=[],n=[],o={model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,status:t.status,user:t.user,model_name:t.model},i={};for(let a of t.output)if(a.type==="message")e.push(...a.content.flatMap(s=>s.type==="output_text"?("parsed"in s&&s.parsed!=null&&(i.parsed=s.parsed),{type:"text",text:s.text,annotations:s.annotations}):s.type==="refusal"?(i.refusal=s.refusal,[]):s));else if(a.type==="function_call"){let s={function:{name:a.name,arguments:a.arguments},id:a.call_id};try{r.push(Jp(s,{returnId:!0}))}catch(u){let l;typeof u=="object"&&u!=null&&"message"in u&&typeof u.message=="string"&&(l=u.message),n.push(Xm(s,l))}i[iU]??(i[iU]={}),i[iU][a.call_id]=a.id}else a.type==="reasoning"?i Line truncated
`);o.enqueue(s)}catch(i){o.error(i)}},async cancel(){await r.return?.()}})}},qje=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]=JZr(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},mU=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 fc(`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 fc(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new fc("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}};mU.NEWLINE_CHARS=new Set([`
`,"\r","\v","\f","","","","\x85","\u2028","\u2029"]);mU.NEWLINE_REGEXP=/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g;function JZr(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}function ADt(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 IDt=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",MDt=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Eae(t),Eae=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",YZr=t=>MDt(t)||IDt(t)||$je(t);async function Hje(t,e,r){if(t=await t,r??(r=MDt(t)?{lastModified:t.lastModified,type:t.type}:{}),IDt(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file"),new Sae([o],e,r)}let n=await ZZr(t);if(e||(e=QZr(t)??"unknown_file"),!r.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new Sae(n,e,r)}async function ZZr(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Eae(t))e.push(await t.arrayBuffer());else if(eXr(t))for await(let r of t)e.push(r);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${XZr(t)}`);return e}function XZr(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function QZr(t){return Uje(t.name)||Uje(t.filename)||Uje(t.path)?.split(/[\\/]/).pop()}var Uje=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},eXr=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Vje=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody";var O5=async t=>{let e=await RDt(t.body);return Fje(e,t)},RDt=async t=>{let e=new Dje;return await Promise.all(Object.entries(t||{}).map(([r,n])=>zje(e,r,n))),e};var zje=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(YZr(r)){let n=await Hje(r);t.append(e,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>zje(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>zje(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`)}};var rXr=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},nXr=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)},Tae;async function kDt(t){let{response:e}=t;if(t.options.stream)return hU("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):Pae.fromSSEResponse(e,t.controller);if(e.status===204)return null;if(t.options.__binaryResponse)return e;let r=e.headers.get("content-type");if(r?.includes("application/json")||r?.includes("application/vnd.api+json")){let i=await e.json();return hU("response",e.status,e.url,e.headers,i),i}let o=await e.text();return hU("response",e.status,e.url,e.headers,o),o}var Aae=class t extends Promise{constructor(e,r=kDt){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=r}_thenUnwrap(e){return new t(this.responsePromise,async r=>e(await this.parseResponse(r)))}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}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),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)}},Iae=class{constructor({baseURL:e,maxRetries:r=2,timeout:n=6e4,httpAgent:o,fetch:i}){this.baseURL=e,this.maxRetries=Wje("maxRetries",r),this.timeout=Wje("timeout",n),this.httpAgent=o,this.fetch=i??Nje}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.get Line truncated
`,t}function qN(t){let e;return t.constructor.name===Xf.name?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===Li.name?(e=new Error(t.message),e.name="AbortError"):t.status===400&&t.message.includes("tool_calls")?e=C5(t,"INVALID_TOOL_RESULTS"):t.status===401?e=C5(t,"MODEL_AUTHENTICATION"):t.status===429?e=C5(t,"MODEL_RATE_LIMIT"):t.status===404?e=C5(t,"MODEL_NOT_FOUND"):e=t,e}function Ije(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 HZr(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function ODt(t){let e=["namespace functions {",""];for(let r of t)r.description&&e.push(`// ${r.description}`),Object.keys(r.parameters.properties??{}).length>0?(e.push(`type ${r.name} = (_: {`),e.push(PDt(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
`)}function PDt(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}: ${Sae(o,e)},`):r.push(`${n}?: ${Sae(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
`)}function Sae(t,e){if(HZr(t))return t.anyOf.map(r=>Sae(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["{",PDt(t,e+2),"}"].join(`
`);case"array":return t.items?`${Sae(t.items,e)}[]`:"any[]";default:return""}}Km();uq();function EDt(t,e){let r;if(rc(t)){let n=Bne({name:t.name,parameters:t.schema,description:t.description});n.function.parameters?r={type:n.type,function:{name:n.function.name,description:n.function.description,parameters:n.function.parameters,...e?.strict!==void 0?{strict:e.strict}:{}}}:r={type:"function",function:TA(t,e)}}else r=t;return e?.strict!==void 0&&(r.function.strict=e.strict),r}function VZr(t){return t.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}function jje(t){let e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":{if(!Cs.isInstance(t))throw new Error("Invalid generic chat message");return VZr(t)}default:throw new Error(`Unknown message type: ${e}`)}}function Rje(t,e){return t.flatMap(r=>{let n=jje(r);n==="system"&&Nje(e)&&(n="developer");let o={role:n,content:r.content};if(r.name!=null&&(o.name=r.name),r.additional_kwargs.function_call!=null&&(o.function_call=r.additional_kwargs.function_call,o.content=""),Oi(r)&&r.tool_calls?.length?(o.tool_calls=r.tool_calls.map(Ox),o.content=""):(r.additional_kwargs.tool_calls!=null&&(o.tool_calls=r.additional_kwargs.tool_calls),r.tool_call_id!=null&&(o.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio){let i={role:"assistant",audio:{id:r.additional_kwargs.audio.id}};return[o,i]}return o})}var aU="__openai_function_call_ids__";function TDt(t,e){return t.flatMap(r=>{let n=jje(r);if(n==="system"&&Nje(e)&&(n="developer"),n==="function")throw new Error("Function messages are not supported in Responses API");if(n==="tool"){let o=r;return o.additional_kwargs?.type==="computer_call_output"?{type:"computer_call_output",output:(()=>{if(typeof o.content=="string")return{type:"computer_screenshot",image_url:o.content};if(Array.isArray(o.content)){let a=o.content.find(u=>u.type==="computer_screenshot");if(a)return a;let s=o.content.find(u=>u.type==="image_url");if(s)return{type:"computer_screenshot",image_url:typeof s.image_url=="string"?s.image_url:s.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:o.tool_call_id}:{type:"function_call_output",call_id:o.tool_call_id,id:o.id,output:typeof o.content!="string"?JSON.stringify(o.content):o.content}}if(n==="assistant"){let o=[];r.additional_kwargs.reasoning!=null&&(u=>typeof u=="object"&&u!=null&&"type"in u&&u.type==="reasoning")(r.additional_kwargs.reasoning)&&o.push(r.additional_kwargs.reasoning);let{content:i}=r;r.additional_kwargs.refusal!=null&&(typeof i=="string"&&(i=[{type:"output_text",text:i,annotations:[]}]),i=[...i,{type:"refusal",refusal:r.additional_kwargs.refusal}]),o.push({type:"message",role:"assistant",content:typeof i=="string"?i:i.flatMap(s=>s.type==="text"?{type:"output_text",text:s.text,annotations:s.annotations??[]}:s.type==="output_text"||s.type==="refusal"?s:[])});let a=r.additional_kwargs[aU];if(Oi(r)&&r.tool_calls?.length?o.push(...r.tool_calls.map(s=>({type:"function_call",name:s.name,arguments:JSON.stringify(s.args),call_id:s.id,id:a?.[s.id]}))):r.additional_kwargs.tool_calls!=null&&o.push(...r.additional_kwargs.tool_calls.map(s=>({type:"function_call",name:s.function.name,call_id:s.id,id:a?.[s.id],arguments:s.function.arguments}))),r.additional_kwargs.tool_outputs!=null){let u=r.additional_kwargs.tool_outputs?.filter(l=>l.type==="computer_call");u.length>0&&o.push(...u)}return o}return n==="user"?{type:"message",role:"user",content:typeof r.content=="string"?r.content:r.content.flatMap(o=>{if(o.type==="text")return{type:"input_text",text:o.text};if(o.type==="image_url"){let i=typeof o.image_url=="string"?o.image_url:o.image_url.url,a=typeof o.image_url=="string"?"auto":o.image_url.detail;return{type:"input_image",image_url:i,detail:a}}return o.type==="input_text"||o.type==="input_image"||o.type==="input_file"?o:[]})}:[]})}function IDt(t){if(t.error){let a=new Error(t.error.message);throw a.name=t.error.code,a}let e=[],r=[],n=[],o={model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,status:t.status,user:t.user,model_name:t.model},i={};for(let a of t.output)if(a.type==="message")e.push(...a.content.flatMap(s=>s.type==="output_text"?("parsed"in s&&s.parsed!=null&&(i.parsed=s.parsed),{type:"text",text:s.text,annotations:s.annotations}):s.type==="refusal"?(i.refusal=s.refusal,[]):s));else if(a.type==="function_call"){let s={function:{name:a.name,arguments:a.arguments},id:a.call_id};try{r.push(Jp(s,{returnId:!0}))}catch(u){let l;typeof u=="object"&&u!=null&&"message"in u&&typeof u.message=="string"&&(l=u.message),n.push(Xm(s,l))}i[aU]??(i[aU]={}),i[aU][a.call_id]=a.id}else a.type==="reasoning"?i Line truncated
`);o.enqueue(s)}catch(i){o.error(i)}},async cancel(){await r.return?.()}})}},zje=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]=eXr(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},hU=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 fc(`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 fc(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new fc("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}};hU.NEWLINE_CHARS=new Set([`
`,"\r","\v","\f","","","","\x85","\u2028","\u2029"]);hU.NEWLINE_REGEXP=/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g;function eXr(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}function NDt(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 DDt=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",LDt=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Iae(t),Iae=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",tXr=t=>LDt(t)||DDt(t)||qje(t);async function Wje(t,e,r){if(t=await t,r??(r=LDt(t)?{lastModified:t.lastModified,type:t.type}:{}),DDt(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file"),new Oae([o],e,r)}let n=await rXr(t);if(e||(e=oXr(t)??"unknown_file"),!r.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new Oae(n,e,r)}async function rXr(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Iae(t))e.push(await t.arrayBuffer());else if(iXr(t))for await(let r of t)e.push(r);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${nXr(t)}`);return e}function nXr(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function oXr(t){return Hje(t.name)||Hje(t.filename)||Hje(t.path)?.split(/[\\/]/).pop()}var Hje=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},iXr=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Kje=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody";var P5=async t=>{let e=await FDt(t.body);return $je(e,t)},FDt=async t=>{let e=new Fje;return await Promise.all(Object.entries(t||{}).map(([r,n])=>Vje(e,r,n))),e};var Vje=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(tXr(r)){let n=await Wje(r);t.append(e,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>Vje(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>Vje(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`)}};var sXr=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},uXr=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)},Mae;async function zDt(t){let{response:e}=t;if(t.options.stream)return gU("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):Aae.fromSSEResponse(e,t.controller);if(e.status===204)return null;if(t.options.__binaryResponse)return e;let r=e.headers.get("content-type");if(r?.includes("application/json")||r?.includes("application/vnd.api+json")){let i=await e.json();return gU("response",e.status,e.url,e.headers,i),i}let o=await e.text();return gU("response",e.status,e.url,e.headers,o),o}var Rae=class t extends Promise{constructor(e,r=zDt){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=r}_thenUnwrap(e){return new t(this.responsePromise,async r=>e(await this.parseResponse(r)))}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}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),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)}},jae=class{constructor({baseURL:e,maxRetries:r=2,timeout:n=6e4,httpAgent:o,fetch:i}){this.baseURL=e,this.maxRetries=Gje("maxRetries",r),this.timeout=Gje("timeout",n),this.httpAgent=o,this.fetch=i??Lje}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.get Line truncated
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 AI(this),this.chat=new TI(this),this.embeddings=new II(this),this.audio=new EI(this),this.models=new MI(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}`}}};BDt=bs;bs.Groq=BDt;bs.GroqError=fc;bs.APIError=Fl;bs.APIConnectionError=fP;bs.APIConnectionTimeoutError=zN;bs.APIUserAbortError=PI;bs.NotFoundError=lU;bs.ConflictError=cU;bs.RateLimitError=fU;bs.BadRequestError=aU;bs.AuthenticationError=sU;bs.InternalServerError=pU;bs.PermissionDeniedError=uU;bs.UnprocessableEntityError=dU;bs.toFile=Hje;bs.fileFromPath=xae;var{GroqError:bGo,APIError:_Go,APIConnectionError:vGo,APIConnectionTimeoutError:wGo,APIUserAbortError:SGo,NotFoundError:xGo,ConflictError:CGo,RateLimitError:OGo,BadRequestError:PGo,AuthenticationError:EGo,InternalServerError:TGo,PermissionDeniedError:AGo,UnprocessableEntityError:IGo}=Bje;(function(t){t.Completions=AI,t.Chat=TI,t.Embeddings=II,t.Audio=EI,t.Models=MI})(bs||(bs={}));var qDt=bs;Sm();gy();iq();Km();function vXr(t){let e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";default:throw new Error(`Unknown message type: ${e}`)}}function UDt(t){return t.map(e=>{if(typeof e.content!="string")throw new Error("Non string message content not supported");let r={role:vXr(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 Oi(e)&&e.tool_calls?.length?r.tool_calls=e.tool_calls.map(Ox):(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 wXr(t,e){let r=t.tool_calls;switch(t.role){case"assistant":{let n=[],o=[];for(let i of r??[])try{n.push(Jp(i,{returnId:!0}))}catch(a){o.push(Xm(i,a.message))}return new gn({content:t.content||"",additional_kwargs:{tool_calls:r},tool_calls:n,invalid_tool_calls:o,usage_metadata:e})}default:return new Cs(t.content||"",t.role??"unknown")}}function SXr(t,e){if(t?.length)return t.map(r=>({id:r.id,name:r.function?.name,args:r.function?.arguments,type:"tool_call_chunk",index:e}))}function xXr(t,e,r){let{role:n}=t,o=t.content??"",i;t.function_call?i={function_call:t.function_call}:t.tool_calls?i={tool_calls:t.tool_calls}:i={};let a,s;if(r?.usage&&(a={input_tokens:r.usage.prompt_tokens,output_tokens:r.usage.completion_tokens,total_tokens:r.usage.total_tokens},s=r.id),n==="user")return{message:new Mf({content:o})};if(n==="assistant"){let u=SXr(t.tool_calls,e);return{message:new dr({content:o,additional_kwargs:i,tool_call_chunks:u?u.map(l=>({type:l.type,args:l.args,index:l.index})):void 0,usage_metadata:a,id:s}),toolCallData:u?u.map(l=>({id:l.id??"",name:l.name??"",index:l.index??e,type:"tool_call_chunk"})):void 0}}else return n==="system"?{message:new Rd({content:o})}:{message:new If({content:o,role:n})}}var Mae=class extends Js{static lc_name(){return"ChatGroq"}_llmType(){return"groq"}get lc_secrets(){return{apiKey:"GROQ_API_KEY"}}constructor(e){super(e??{}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","chat_models","groq"]}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"modelName",{enumerable:!0,configurable:!0,writable:!0,value:"mixtral-8x7b-32768"}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"mixtral-8x7b-32768"}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:.7}),Object.defineProperty(this,"stop",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stopSequences",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0});let r=e?.apiKey||ot("GROQ_API_KEY");if(!r)throw new Error('Groq API key not found. Please set the GROQ_API_KEY environment variable or provide the key into "apiKey"');this.client=new qDt({apiKey:r,dangerouslyAllowBrowser:!0}),this.apiKey=r,this.temperature=e?.temperature??this.temperature,this.modelName=e?.model??e?.modelName??this.model,this.model=this.modelName,this.streaming=e?.streaming??this.streaming,this.stop=e?.stopSequences??(typeof e?.stop=="string"?[e.stop]: Line truncated
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 AI(this),this.chat=new TI(this),this.embeddings=new II(this),this.audio=new EI(this),this.models=new MI(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}`}}};VDt=bs;bs.Groq=VDt;bs.GroqError=fc;bs.APIError=Fl;bs.APIConnectionError=fP;bs.APIConnectionTimeoutError=HN;bs.APIUserAbortError=PI;bs.NotFoundError=cU;bs.ConflictError=dU;bs.RateLimitError=pU;bs.BadRequestError=sU;bs.AuthenticationError=uU;bs.InternalServerError=mU;bs.PermissionDeniedError=lU;bs.UnprocessableEntityError=fU;bs.toFile=Wje;bs.fileFromPath=Pae;var{GroqError:PGo,APIError:EGo,APIConnectionError:TGo,APIConnectionTimeoutError:AGo,APIUserAbortError:IGo,NotFoundError:MGo,ConflictError:RGo,RateLimitError:jGo,BadRequestError:NGo,AuthenticationError:DGo,InternalServerError:LGo,PermissionDeniedError:FGo,UnprocessableEntityError:kGo}=Uje;(function(t){t.Completions=AI,t.Chat=TI,t.Embeddings=II,t.Audio=EI,t.Models=MI})(bs||(bs={}));var WDt=bs;Sm();gy();aq();Km();function OXr(t){let e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";default:throw new Error(`Unknown message type: ${e}`)}}function KDt(t){return t.map(e=>{if(typeof e.content!="string")throw new Error("Non string message content not supported");let r={role:OXr(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 Oi(e)&&e.tool_calls?.length?r.tool_calls=e.tool_calls.map(Ox):(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 PXr(t,e){let r=t.tool_calls;switch(t.role){case"assistant":{let n=[],o=[];for(let i of r??[])try{n.push(Jp(i,{returnId:!0}))}catch(a){o.push(Xm(i,a.message))}return new gn({content:t.content||"",additional_kwargs:{tool_calls:r},tool_calls:n,invalid_tool_calls:o,usage_metadata:e})}default:return new Cs(t.content||"",t.role??"unknown")}}function EXr(t,e){if(t?.length)return t.map(r=>({id:r.id,name:r.function?.name,args:r.function?.arguments,type:"tool_call_chunk",index:e}))}function TXr(t,e,r){let{role:n}=t,o=t.content??"",i;t.function_call?i={function_call:t.function_call}:t.tool_calls?i={tool_calls:t.tool_calls}:i={};let a,s;if(r?.usage&&(a={input_tokens:r.usage.prompt_tokens,output_tokens:r.usage.completion_tokens,total_tokens:r.usage.total_tokens},s=r.id),n==="user")return{message:new Mf({content:o})};if(n==="assistant"){let u=EXr(t.tool_calls,e);return{message:new dr({content:o,additional_kwargs:i,tool_call_chunks:u?u.map(l=>({type:l.type,args:l.args,index:l.index})):void 0,usage_metadata:a,id:s}),toolCallData:u?u.map(l=>({id:l.id??"",name:l.name??"",index:l.index??e,type:"tool_call_chunk"})):void 0}}else return n==="system"?{message:new Rd({content:o})}:{message:new If({content:o,role:n})}}var Nae=class extends Js{static lc_name(){return"ChatGroq"}_llmType(){return"groq"}get lc_secrets(){return{apiKey:"GROQ_API_KEY"}}constructor(e){super(e??{}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","chat_models","groq"]}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"modelName",{enumerable:!0,configurable:!0,writable:!0,value:"mixtral-8x7b-32768"}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"mixtral-8x7b-32768"}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:.7}),Object.defineProperty(this,"stop",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stopSequences",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0});let r=e?.apiKey||ot("GROQ_API_KEY");if(!r)throw new Error('Groq API key not found. Please set the GROQ_API_KEY environment variable or provide the key into "apiKey"');this.client=new WDt({apiKey:r,dangerouslyAllowBrowser:!0}),this.apiKey=r,this.temperature=e?.temperature??this.temperature,this.modelName=e?.model??e?.modelName??this.model,this.model=this.modelName,this.streaming=e?.streaming??this.streaming,this.stop=e?.stopSequences??(typeof e?.stop=="string"?[e.stop]: Line truncated
Received: ${JSON.stringify(o,null,2)}`)};if(typeof o=="string")return o;if(Array.isArray(o)){let s=e(i),u=[];return o.forEach(l=>{if(l.type==="text"||l.type==="image_url")u.push(a(l,s));else throw new Error('Mistral only supports types "text" or "image_url" for complex message types.')}),u}throw new Error(`Message content must be a string or an array.
Received: ${JSON.stringify(o,null,2)}`)},n=o=>{if(Oi(o)&&o.tool_calls?.length)return o.tool_calls.map(i=>({...i,id:DLe(i.id??"")})).map(Ox)};return t.map(o=>{let i=n(o),a=r(o.content,o.getType());return"tool_call_id"in o&&typeof o.tool_call_id=="string"?{role:e(o.getType()),content:a,name:o.name,toolCallId:DLe(o.tool_call_id)}:Oi(o)?i===void 0?{role:e(o.getType()),content:a}:{role:e(o.getType()),toolCalls:i}:{role:e(o.getType()),content:a}})}function Mwn(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=LLe(r.content);switch(r.role){case"assistant":{let i=[],a=[];for(let s of n)try{let u=Jp(s,{returnId:!0});i.push({...u,id:u.id??Nae().replace(/-/g,"")})}catch(u){a.push(Xm(s,u.message))}return new gn({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 Os({content:o})}}function Rwn(t,e){if(!t.content&&!t.toolCalls)return e?new dr({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??Nae().replace(/-/g,""),type:"function"})):void 0,n="assistant";t.role&&(n=t.role);let o=LLe(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 Mf({content:o}):n==="assistant"?new dr({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 Th({content:o,additional_kwargs:i,tool_call_id:r?.[0].id??""}):n==="function"?new ym({content:o,additional_kwargs:i}):new If({content:o,role:n})}function Z4t(t){return t.map(e=>{if("function"in e)return e;let r=e.description??`Tool: ${e.name}`;return{type:"function",function:{name:e.name,description:r,parameters:So(e.schema)}}})}var Ble=class extends Js{static lc_name(){return"ChatMistralAI"}constructor(e){super(e??{}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","chat_models","mistralai"]}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"mistral-small-latest"}),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"endpoint",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serverURL",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:.7}),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"safeMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"safePrompt",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"randomSeed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"seed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"streamUsage",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"beforeRequestHooks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"requestErrorHooks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"responseHooks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"httpClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"presencePenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"frequencyPenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"numCompletions",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let r=e?.apiKey??ot("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?. Line truncated
Received: ${JSON.stringify(o,null,2)}`)},n=o=>{if(Oi(o)&&o.tool_calls?.length)return o.tool_calls.map(i=>({...i,id:FLe(i.id??"")})).map(Ox)};return t.map(o=>{let i=n(o),a=r(o.content,o.getType());return"tool_call_id"in o&&typeof o.tool_call_id=="string"?{role:e(o.getType()),content:a,name:o.name,toolCallId:FLe(o.tool_call_id)}:Oi(o)?i===void 0?{role:e(o.getType()),content:a}:{role:e(o.getType()),toolCalls:i}:{role:e(o.getType()),content:a}})}function Lwn(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=kLe(r.content);switch(r.role){case"assistant":{let i=[],a=[];for(let s of n)try{let u=Jp(s,{returnId:!0});i.push({...u,id:u.id??Fae().replace(/-/g,"")})}catch(u){a.push(Xm(s,u.message))}return new gn({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 Os({content:o})}}function Fwn(t,e){if(!t.content&&!t.toolCalls)return e?new dr({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??Fae().replace(/-/g,""),type:"function"})):void 0,n="assistant";t.role&&(n=t.role);let o=kLe(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 Mf({content:o}):n==="assistant"?new dr({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 Th({content:o,additional_kwargs:i,tool_call_id:r?.[0].id??""}):n==="function"?new ym({content:o,additional_kwargs:i}):new If({content:o,role:n})}function r3t(t){return t.map(e=>{if("function"in e)return e;let r=e.description??`Tool: ${e.name}`;return{type:"function",function:{name:e.name,description:r,parameters:So(e.schema)}}})}var zle=class extends Js{static lc_name(){return"ChatMistralAI"}constructor(e){super(e??{}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","chat_models","mistralai"]}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"mistral-small-latest"}),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"endpoint",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serverURL",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:.7}),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"safeMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"safePrompt",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"randomSeed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"seed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"streamUsage",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"beforeRequestHooks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"requestErrorHooks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"responseHooks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"httpClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"presencePenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"frequencyPenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"numCompletions",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let r=e?.apiKey??ot("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?. Line truncated
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
`,t}function OD(t){let e;return t.constructor.name===Xf.name?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===Li.name?(e=new Error(t.message),e.name="AbortError"):t.status===400&&t.message.includes("tool_calls")?e=pW(t,"INVALID_TOOL_RESULTS"):t.status===401?e=pW(t,"MODEL_AUTHENTICATION"):t.status===429?e=pW(t,"MODEL_RATE_LIMIT"):t.status===404?e=pW(t,"MODEL_NOT_FOUND"):e=t,e}function FLe(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 jwn(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function t3t(t){let e=["namespace functions {",""];for(let r of t)r.description&&e.push(`// ${r.description}`),Object.keys(r.parameters.properties??{}).length>0?(e.push(`type ${r.name} = (_: {`),e.push(r3t(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
`)}function r3t(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}: ${qle(o,e)},`):r.push(`${n}?: ${qle(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
`)}function qle(t,e){if(jwn(t))return t.anyOf.map(r=>qle(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["{",r3t(t,e+2),"}"].join(`
`);case"array":return t.items?`${qle(t.items,e)}[]`:"any[]";default:return""}}Km();sq();function n3t(t,e){let r;if(rc(t)){let n=$ne({name:t.name,parameters:t.schema,description:t.description});n.function.parameters?r={type:n.type,function:{name:n.function.name,description:n.function.description,parameters:n.function.parameters,...e?.strict!==void 0?{strict:e.strict}:{}}}:r={type:"function",function:TA(t,e)}}else r=t;return e?.strict!==void 0&&(r.function.strict=e.strict),r}function Nwn(t){return t.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}function BLe(t){let e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":{if(!Cs.isInstance(t))throw new Error("Invalid generic chat message");return Nwn(t)}default:throw new Error(`Unknown message type: ${e}`)}}function $Le(t,e){return t.flatMap(r=>{let n=BLe(r);n==="system"&&qLe(e)&&(n="developer");let o={role:n,content:r.content};if(r.name!=null&&(o.name=r.name),r.additional_kwargs.function_call!=null&&(o.function_call=r.additional_kwargs.function_call,o.content=""),Oi(r)&&r.tool_calls?.length?(o.tool_calls=r.tool_calls.map(Ox),o.content=""):(r.additional_kwargs.tool_calls!=null&&(o.tool_calls=r.additional_kwargs.tool_calls),r.tool_call_id!=null&&(o.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio){let i={role:"assistant",audio:{id:r.additional_kwargs.audio.id}};return[o,i]}return o})}var zU="__openai_function_call_ids__";function o3t(t,e){return t.flatMap(r=>{let n=BLe(r);if(n==="system"&&qLe(e)&&(n="developer"),n==="function")throw new Error("Function messages are not supported in Responses API");if(n==="tool"){let o=r;return o.additional_kwargs?.type==="computer_call_output"?{type:"computer_call_output",output:(()=>{if(typeof o.content=="string")return{type:"computer_screenshot",image_url:o.content};if(Array.isArray(o.content)){let a=o.content.find(u=>u.type==="computer_screenshot");if(a)return a;let s=o.content.find(u=>u.type==="image_url");if(s)return{type:"computer_screenshot",image_url:typeof s.image_url=="string"?s.image_url:s.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:o.tool_call_id}:{type:"function_call_output",call_id:o.tool_call_id,id:o.id,output:typeof o.content!="string"?JSON.stringify(o.content):o.content}}if(n==="assistant"){let o=[];r.additional_kwargs.reasoning!=null&&(u=>typeof u=="object"&&u!=null&&"type"in u&&u.type==="reasoning")(r.additional_kwargs.reasoning)&&o.push(r.additional_kwargs.reasoning);let{content:i}=r;r.additional_kwargs.refusal!=null&&(typeof i=="string"&&(i=[{type:"output_text",text:i,annotations:[]}]),i=[...i,{type:"refusal",refusal:r.additional_kwargs.refusal}]),o.push({type:"message",role:"assistant",content:typeof i=="string"?i:i.flatMap(s=>s.type==="text"?{type:"output_text",text:s.text,annotations:s.annotations??[]}:s.type==="output_text"||s.type==="refusal"?s:[])});let a=r.additional_kwargs[zU];if(Oi(r)&&r.tool_calls?.length?o.push(...r.tool_calls.map(s=>({type:"function_call",name:s.name,arguments:JSON.stringify(s.args),call_id:s.id,id:a?.[s.id]}))):r.additional_kwargs.tool_calls!=null&&o.push(...r.additional_kwargs.tool_calls.map(s=>({type:"function_call",name:s.function.name,call_id:s.id,id:a?.[s.id],arguments:s.function.arguments}))),r.additional_kwargs.tool_outputs!=null){let u=r.additional_kwargs.tool_outputs?.filter(l=>l.type==="computer_call");u.length>0&&o.push(...u)}return o}return n==="user"?{type:"message",role:"user",content:typeof r.content=="string"?r.content:r.content.flatMap(o=>{if(o.type==="text")return{type:"input_text",text:o.text};if(o.type==="image_url"){let i=typeof o.image_url=="string"?o.image_url:o.image_url.url,a=typeof o.image_url=="string"?"auto":o.image_url.detail;return{type:"input_image",image_url:i,detail:a}}return o.type==="input_text"||o.type==="input_image"||o.type==="input_file"?o:[]})}:[]})}function a3t(t){if(t.error){let a=new Error(t.error.message);throw a.name=t.error.code,a}let e=[],r=[],n=[],o={model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,status:t.status,user:t.user,model_name:t.model},i={};for(let a of t.output)if(a.type==="message")e.push(...a.content.flatMap(s=>s.type==="output_text"?("parsed"in s&&s.parsed!=null&&(i.parsed=s.parsed),{type:"text",text:s.text,annotations:s.annotations}):s.type==="refusal"?(i.refusal=s.refusal,[]):s));else if(a.type==="function_call"){let s={function:{name:a.name,arguments:a.arguments},id:a.call_id};try{r.push(Jp(s,{returnId:!0}))}catch(u){let l;typeof u=="object"&&u!=null&&"message"in u&&typeof u.message=="string"&&(l=u.message),n.push(Xm(s,l))}i[zU]??(i[zU]={}),i[zU][a.call_id]=a.id}else a.type==="reasoning"?i Line truncated
`,t}function PD(t){let e;return t.constructor.name===Xf.name?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===Li.name?(e=new Error(t.message),e.name="AbortError"):t.status===400&&t.message.includes("tool_calls")?e=mW(t,"INVALID_TOOL_RESULTS"):t.status===401?e=mW(t,"MODEL_AUTHENTICATION"):t.status===429?e=mW(t,"MODEL_RATE_LIMIT"):t.status===404?e=mW(t,"MODEL_NOT_FOUND"):e=t,e}function $Le(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 kwn(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function a3t(t){let e=["namespace functions {",""];for(let r of t)r.description&&e.push(`// ${r.description}`),Object.keys(r.parameters.properties??{}).length>0?(e.push(`type ${r.name} = (_: {`),e.push(s3t(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
`)}function s3t(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}: ${Hle(o,e)},`):r.push(`${n}?: ${Hle(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
`)}function Hle(t,e){if(kwn(t))return t.anyOf.map(r=>Hle(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["{",s3t(t,e+2),"}"].join(`
`);case"array":return t.items?`${Hle(t.items,e)}[]`:"any[]";default:return""}}Km();uq();function u3t(t,e){let r;if(rc(t)){let n=Bne({name:t.name,parameters:t.schema,description:t.description});n.function.parameters?r={type:n.type,function:{name:n.function.name,description:n.function.description,parameters:n.function.parameters,...e?.strict!==void 0?{strict:e.strict}:{}}}:r={type:"function",function:TA(t,e)}}else r=t;return e?.strict!==void 0&&(r.function.strict=e.strict),r}function $wn(t){return t.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}function ULe(t){let e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":{if(!Cs.isInstance(t))throw new Error("Invalid generic chat message");return $wn(t)}default:throw new Error(`Unknown message type: ${e}`)}}function qLe(t,e){return t.flatMap(r=>{let n=ULe(r);n==="system"&&zLe(e)&&(n="developer");let o={role:n,content:r.content};if(r.name!=null&&(o.name=r.name),r.additional_kwargs.function_call!=null&&(o.function_call=r.additional_kwargs.function_call,o.content=""),Oi(r)&&r.tool_calls?.length?(o.tool_calls=r.tool_calls.map(Ox),o.content=""):(r.additional_kwargs.tool_calls!=null&&(o.tool_calls=r.additional_kwargs.tool_calls),r.tool_call_id!=null&&(o.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio){let i={role:"assistant",audio:{id:r.additional_kwargs.audio.id}};return[o,i]}return o})}var HU="__openai_function_call_ids__";function l3t(t,e){return t.flatMap(r=>{let n=ULe(r);if(n==="system"&&zLe(e)&&(n="developer"),n==="function")throw new Error("Function messages are not supported in Responses API");if(n==="tool"){let o=r;return o.additional_kwargs?.type==="computer_call_output"?{type:"computer_call_output",output:(()=>{if(typeof o.content=="string")return{type:"computer_screenshot",image_url:o.content};if(Array.isArray(o.content)){let a=o.content.find(u=>u.type==="computer_screenshot");if(a)return a;let s=o.content.find(u=>u.type==="image_url");if(s)return{type:"computer_screenshot",image_url:typeof s.image_url=="string"?s.image_url:s.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:o.tool_call_id}:{type:"function_call_output",call_id:o.tool_call_id,id:o.id,output:typeof o.content!="string"?JSON.stringify(o.content):o.content}}if(n==="assistant"){let o=[];r.additional_kwargs.reasoning!=null&&(u=>typeof u=="object"&&u!=null&&"type"in u&&u.type==="reasoning")(r.additional_kwargs.reasoning)&&o.push(r.additional_kwargs.reasoning);let{content:i}=r;r.additional_kwargs.refusal!=null&&(typeof i=="string"&&(i=[{type:"output_text",text:i,annotations:[]}]),i=[...i,{type:"refusal",refusal:r.additional_kwargs.refusal}]),o.push({type:"message",role:"assistant",content:typeof i=="string"?i:i.flatMap(s=>s.type==="text"?{type:"output_text",text:s.text,annotations:s.annotations??[]}:s.type==="output_text"||s.type==="refusal"?s:[])});let a=r.additional_kwargs[HU];if(Oi(r)&&r.tool_calls?.length?o.push(...r.tool_calls.map(s=>({type:"function_call",name:s.name,arguments:JSON.stringify(s.args),call_id:s.id,id:a?.[s.id]}))):r.additional_kwargs.tool_calls!=null&&o.push(...r.additional_kwargs.tool_calls.map(s=>({type:"function_call",name:s.function.name,call_id:s.id,id:a?.[s.id],arguments:s.function.arguments}))),r.additional_kwargs.tool_outputs!=null){let u=r.additional_kwargs.tool_outputs?.filter(l=>l.type==="computer_call");u.length>0&&o.push(...u)}return o}return n==="user"?{type:"message",role:"user",content:typeof r.content=="string"?r.content:r.content.flatMap(o=>{if(o.type==="text")return{type:"input_text",text:o.text};if(o.type==="image_url"){let i=typeof o.image_url=="string"?o.image_url:o.image_url.url,a=typeof o.image_url=="string"?"auto":o.image_url.detail;return{type:"input_image",image_url:i,detail:a}}return o.type==="input_text"||o.type==="input_image"||o.type==="input_file"?o:[]})}:[]})}function d3t(t){if(t.error){let a=new Error(t.error.message);throw a.name=t.error.code,a}let e=[],r=[],n=[],o={model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,status:t.status,user:t.user,model_name:t.model},i={};for(let a of t.output)if(a.type==="message")e.push(...a.content.flatMap(s=>s.type==="output_text"?("parsed"in s&&s.parsed!=null&&(i.parsed=s.parsed),{type:"text",text:s.text,annotations:s.annotations}):s.type==="refusal"?(i.refusal=s.refusal,[]):s));else if(a.type==="function_call"){let s={function:{name:a.name,arguments:a.arguments},id:a.call_id};try{r.push(Jp(s,{returnId:!0}))}catch(u){let l;typeof u=="object"&&u!=null&&"message"in u&&typeof u.message=="string"&&(l=u.message),n.push(Xm(s,l))}i[HU]??(i[HU]={}),i[HU][a.call_id]=a.id}else a.type==="reasoning"?i Line truncated
without CORS Error: `+ei(n)+`
with CORS Error: `+ei(o);throw new Error(i)}}}findModelByName(e){return ue().activeModels.find(n=>n.name===e)}};nr();gs();var HU=class{},s3t=(t,e)=>{if(e!==void 0)return t[e];let r=Object.keys(t);if(r.length===1)return t[r[0]]},Vle=(t,e)=>{let r=s3t(t,e);if(!r){let n=Object.keys(t);throw new Error(`input values have ${n.length} keys, you must specify an input key or pass only 1 key as input`)}return r},zLe=(t,e)=>{let r=s3t(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};yR();OR();var HLe=class extends gp{addUserMessage(e){return this.addMessage(new Os(e))}addAIChatMessage(e){return this.addMessage(new gn(e))}addAIMessage(e){return this.addMessage(new gn(e))}async addMessages(e){for(let r of e)await this.addMessage(r)}clear(){throw new Error("Not implemented.")}},VU=class extends HLe{constructor(e){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","stores","message","in_memory"]}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}};var gb=class extends HU{constructor(e){super(),Object.defineProperty(this,"chatHistory",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"returnMessages",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"inputKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.chatHistory=e?.chatHistory??new VU,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(Vle(e,this.inputKey)),await this.chatHistory.addAIChatMessage(zLe(r,this.outputKey))}async clear(){await this.chatHistory.clear()}};var hW=class extends gb{constructor(e){super({chatHistory:e?.chatHistory,returnMessages:e?.returnMessages??!1,inputKey:e?.inputKey,outputKey:e?.outputKey}),Object.defineProperty(this,"humanPrefix",{enumerable:!0,configurable:!0,writable:!0,value:"Human"}),Object.defineProperty(this,"aiPrefix",{enumerable:!0,configurable:!0,writable:!0,value:"AI"}),Object.defineProperty(this,"memoryKey",{enumerable:!0,configurable:!0,writable:!0,value:"history"}),this.humanPrefix=e?.humanPrefix??this.humanPrefix,this.aiPrefix=e?.aiPrefix??this.aiPrefix,this.memoryKey=e?.memoryKey??this.memoryKey}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){let r=await this.chatHistory.getMessages();return this.returnMessages?{[this.memoryKey]:r}:{[this.memoryKey]:Rf(r,this.humanPrefix,this.aiPrefix)}}};gs();gs();VLe();qE();gs();var gW=class extends gb{constructor(e){super({returnMessages:e?.returnMessages??!1,chatHistory:e?.chatHistory,inputKey:e?.inputKey,outputKey:e?.outputKey}),Object.defineProperty(this,"humanPrefix",{enumerable:!0,configurable:!0,writable:!0,value:"Human"}),Object.defineProperty(this,"aiPrefix",{enumerable:!0,configurable:!0,writable:!0,value:"AI"}),Object.defineProperty(this,"memoryKey",{enumerable:!0,configurable:!0,writable:!0,value:"history"}),Object.defineProperty(this,"k",{enumerable:!0,configurable:!0,writable:!0,value:5}),this.humanPrefix=e?.humanPrefix??this.humanPrefix,this.aiPrefix=e?.aiPrefix??this.aiPrefix,this.memoryKey=e?.memoryKey??this.memoryKey,this.k=e?.k??this.k}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){let r=await this.chatHistory.getMessages();return this.returnMessages?{[this.memoryKey]:r.slice(-this.k*2)}:{[this.memoryKey]:Rf(r.slice(-this.k*2),this.humanPrefix,this.aiPrefix)}}};rie();Mhe();gs();yR();VLe();gs();gs();var yW=class t{constructor(){this.initMemory(),xa(()=>{let e=this.memory?.chatHistory;this.initMemory(e)})}static getInstance(){return t.instance||(t.instance=new t),t.instance}initMemory(e){let r=ue().contextTurns;this.memory=new gW({k:r*2,memoryKey:"history",inputKey:"input",returnMessages:!0,chatHistory:e}),this.debug&&console.log("Memory initialized with context turns:",r)}getMemory(){return this.memory}async clearChatMemory(){this.debug&&console.log("Clearing chat memory"),await this.memory.clear()}async loadMemoryVariables(){let e=await this.memory.loadMemoryVariables({});return this.debug&&console.log("Loaded memory variables:",e),e}async saveContext(e,r){this.debug&&console.log("Saving to memory - Input:",e,"Output:",r),await this.memory.saveContext(e,r)}};nr();qE();Cl();var bW=class t{constructor(){this.initChatPrompt(),this.initQAPrompt(),xa(()=>{this.initChatPrompt(),this.initQAPrompt()}),SF(()=>{this.initChatPrompt(),this.initQAPrompt()})}static getInstance(){return t.instance||(t.instance=new t),t.instance}initChatPrompt(){let e=Yb() Line truncated
with CORS Error: `+ei(o);throw new Error(i)}}}findModelByName(e){return ue().activeModels.find(n=>n.name===e)}};nr();gs();var VU=class{},f3t=(t,e)=>{if(e!==void 0)return t[e];let r=Object.keys(t);if(r.length===1)return t[r[0]]},Gle=(t,e)=>{let r=f3t(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},VLe=(t,e)=>{let r=f3t(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};yR();OR();var WLe=class extends gp{addUserMessage(e){return this.addMessage(new Os(e))}addAIChatMessage(e){return this.addMessage(new gn(e))}addAIMessage(e){return this.addMessage(new gn(e))}async addMessages(e){for(let r of e)await this.addMessage(r)}clear(){throw new Error("Not implemented.")}},WU=class extends WLe{constructor(e){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","stores","message","in_memory"]}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}};var gb=class extends VU{constructor(e){super(),Object.defineProperty(this,"chatHistory",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"returnMessages",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"inputKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.chatHistory=e?.chatHistory??new WU,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(Gle(e,this.inputKey)),await this.chatHistory.addAIChatMessage(VLe(r,this.outputKey))}async clear(){await this.chatHistory.clear()}};var gW=class extends gb{constructor(e){super({chatHistory:e?.chatHistory,returnMessages:e?.returnMessages??!1,inputKey:e?.inputKey,outputKey:e?.outputKey}),Object.defineProperty(this,"humanPrefix",{enumerable:!0,configurable:!0,writable:!0,value:"Human"}),Object.defineProperty(this,"aiPrefix",{enumerable:!0,configurable:!0,writable:!0,value:"AI"}),Object.defineProperty(this,"memoryKey",{enumerable:!0,configurable:!0,writable:!0,value:"history"}),this.humanPrefix=e?.humanPrefix??this.humanPrefix,this.aiPrefix=e?.aiPrefix??this.aiPrefix,this.memoryKey=e?.memoryKey??this.memoryKey}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){let r=await this.chatHistory.getMessages();return this.returnMessages?{[this.memoryKey]:r}:{[this.memoryKey]:Rf(r,this.humanPrefix,this.aiPrefix)}}};gs();gs();KLe();qE();gs();var yW=class extends gb{constructor(e){super({returnMessages:e?.returnMessages??!1,chatHistory:e?.chatHistory,inputKey:e?.inputKey,outputKey:e?.outputKey}),Object.defineProperty(this,"humanPrefix",{enumerable:!0,configurable:!0,writable:!0,value:"Human"}),Object.defineProperty(this,"aiPrefix",{enumerable:!0,configurable:!0,writable:!0,value:"AI"}),Object.defineProperty(this,"memoryKey",{enumerable:!0,configurable:!0,writable:!0,value:"history"}),Object.defineProperty(this,"k",{enumerable:!0,configurable:!0,writable:!0,value:5}),this.humanPrefix=e?.humanPrefix??this.humanPrefix,this.aiPrefix=e?.aiPrefix??this.aiPrefix,this.memoryKey=e?.memoryKey??this.memoryKey,this.k=e?.k??this.k}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){let r=await this.chatHistory.getMessages();return this.returnMessages?{[this.memoryKey]:r.slice(-this.k*2)}:{[this.memoryKey]:Rf(r.slice(-this.k*2),this.humanPrefix,this.aiPrefix)}}};iie();Nhe();gs();yR();KLe();gs();gs();var bW=class t{constructor(){this.initMemory(),xa(()=>{let e=this.memory?.chatHistory;this.initMemory(e)})}static getInstance(){return t.instance||(t.instance=new t),t.instance}initMemory(e){let r=ue().contextTurns;this.memory=new yW({k:r*2,memoryKey:"history",inputKey:"input",returnMessages:!0,chatHistory:e}),this.debug&&console.log("Memory initialized with context turns:",r)}getMemory(){return this.memory}async clearChatMemory(){this.debug&&console.log("Clearing chat memory"),await this.memory.clear()}async loadMemoryVariables(){let e=await this.memory.loadMemoryVariables({});return this.debug&&console.log("Loaded memory variables:",e),e}async saveContext(e,r){this.debug&&console.log("Saving to memory - Input:",e,"Output:",r),await this.memory.saveContext(e,r)}};nr();qE();Cl();var _W=class t{constructor(){this.initChatPrompt(),this.initQAPrompt(),xa(()=>{this.initChatPrompt(),this.initQAPrompt()}),xF(()=>{this.initChatPrompt(),this.initQAPrompt()})}static getInstance(){return t.instance||(t.instance=new t),t.instance}initChatPrompt(){let e=Yb() Line truncated
Answer the question with as detailed as possible based only on the following context:
{context}
Question: {question}
`;this.qaPrompt=xp.fromMessages([BE.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 _W=class{constructor(e,r){this.retrievedDocuments=[];this.chatMessages=[];this.chatMessages=[],this.app=e,this.vectorStoreManager=r,this.memoryManager=yW.getInstance(),this.chatModelManager=PD.getInstance(),this.promptManager=bW.getInstance(),this.initialize(),xa(async()=>{await this.createChainWithNewModel()})}getRetrievedDocuments(){return this.retrievedDocuments}async initialize(){await this.createChainWithNewModel()}getChain(){return this.chain}getRetrievalChain(){return this.retrievalChain}validateChainType(e){if(e==null)throw new Error("No chain type set")}validateChatModel(){if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){let e="Chat model is not initialized properly, check your API key in Copilot setting and make sure you have API access.";throw new Wle.Notice(e),new Error(e)}}validateChainInitialization(){(!this.chain||!fVe(this.chain))&&(console.error("Chain is not initialized properly, re-initializing chain: ",Fh()),this.createChainWithNewModel({},!1))}storeRetrieverDocuments(e){this.retrievedDocuments=e}async createChainWithNewModel(e={},r=!0){let n=Fh(),o=Mc();if(n==="project"&&!o)return;let i=n==="project"?o?.projectModelKey:mJ();if(!i)throw new Wle.Notice("No model key found"),new Error("No model key found");try{if(r){let a=eJ(i,ue().activeModels);if(a||(console.error("Resetting default model. No model configuration found for: ",i),a=Zb[0],i=a.name+"|"+a.provider),n==="project"&&!a.projectEnabled){let u=ue().activeModels.find(l=>l.enabled&&l.projectEnabled);if(u)a=u,i=u.name+"|"+u.provider,new Wle.Notice(`Model ${a.name} is not available in project mode. Switching to ${u.name}.`);else throw new Error("No project-enabled models available. Please enable a model for project mode in settings.")}let s={...a,...o?.modelConfigs};await this.chatModelManager.setChatModel(s)}this.setChain(n,e),ie(`Setting model to ${i}`)}catch(a){fe(`createChainWithNewModel failed: ${a}`),ie(`modelKey: ${i}`)}}async setChain(e,r={}){if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){console.error("setChain failed: No chat model set.");return}this.validateChainType(e);let n=this.chatModelManager.getChatModel(),o=this.memoryManager.getMemory(),i=this.promptManager.getChatPrompt();switch(e){case"llm_chain":{this.chain=c4.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),qR("llm_chain");break}case"vault_qa":{await this.initializeQAChain(r);let a=new Rx({minSimilarityScore:.01,maxK:ue().maxSourceChunks,salientTerms:[]});this.retrievalChain=c4.createConversationalRetrievalChain({llm:n,retriever:a,systemMessage:Yb()},this.storeRetrieverDocuments.bind(this),ue().debug),qR("vault_qa"),ue().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=c4.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),qR("copilot_plus");break}case"project":{await this.initializeQAChain(r),this.chain=c4.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),qR("project");break}default:this.validateChainType(e);break}}getChainRunner(){let e=Fh();switch(e){case"llm_chain":return new qie(this);case"vault_qa":return new Uie(this);case"copilot_plus":return new e5(this);case"project":return new zie(this);default:throw new Error(`Unsupported chain type: ${e}`)}}async initializeQAChain(e){e.refreshIndex&&await this.vectorStoreManager.indexVaultToVectorStore()}async runChain(e,r,n,o,i={}){let{debug:a=!1,ignoreSystemMessage:s=!1}=i;a&&console.log(`==== Step 0: Initial user message ====
`,e),this.validateChatModel(),this.validateChainInitialization();let u=this.chatModelManager.getChatModel();if(s||LR(u)){let c=xp.fromMessages([new Gb("history"),Jb.fromTemplate("{input}")]);LR(u)&&(c=xp.fromMessages([[Pi,Yb()||""],c])),this.createChainWithNewModel({prompt:c},!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===Pi&&await this.memoryManager.getMemory().saveContext({input:n.message},{output:o.message})}}clearHistory(){this.chatMessages=[]}getChatMessages(){return this.chatMessages}setChatMessages(e){this.chatMessages=[...e]}addChatMessage(e){this.chatMessages.push(e)}};var ac=class t{constructor(e,r,n){this.defaultProjectKey="defaultProjectKey";this.app=e,this.plugin=n,this.currentProjectId=null,this.chainMangerInstance=new _W(e,r),this.projectContextCache=tb.getInstance(),this.chatMessageCache=new Map,this.fileParserManager=new oI(Fi.getInstance(),this.app.vault,!0,null),ZVe(async()=>{await this.getCurrentChainManager().createChainWithNewModel()}),XVe(async()=>{zR()||await this.getCurrentChainManager().createChainWithNewModel({refreshIndex:ue().indexVaultToVectorStore==="ON MODE SWITCH"&&(Fh()==="vault_qa"||Fh()==="copilot_plus")})}),SF(async o=>{await this.switchProject(o)}),this.setupProjectListChangeMonitor()}setupProjectListChangeMonitor(){xa(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),this.getCurrentChainManager().createChainWithNewModel()]))}})}static getInstance(e,r,n){return t.instance||(t.instance=new t(e,r,n)),t.instance}getCurrentChainManager(){return this.chainMangerInstance}async switchProject(e){try{if(GE(!0),ie("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 oI(Fi.getInstance(),this.app.vault,!0,e),await this.loadProjectContext(e),this.refreshChatView(),ie(`Switched to project: ${e.name}`)}catch(r){throw fe(`Failed to switch project: ${r}`),r}finally{GE(!1)}}async saveCurrentProjectMessage(){this.chatMessageCache.set(this.currentProjectId?this.currentProjectId:this.defaultProjectKey,this.getCurrentChainManager().getChatMessages()),await this.plugin.autosaveCurrentChat()}async loadNextProjectMessage(){let e=this.getCurrentChainManager(),r=this.chatMessageCache.get(this.currentProjectId?this.currentProjectId:this.defaultProjectKey)??[];e.setChatMessages(r),await _N(r,e.memoryManager)}async loadProjectContext(e){try{if(!e.contextSource)return Mh(`[loadProjectContext] Project ${e.name}: No contextSource. Aborting.`),null;ie(`[loadProjectContext] Starting for project: ${e.name}`);let r=await this.projectContextCache.get(e),n=r||{markdownContext:"",webContexts:{},youtubeContexts:{},fileContexts:{},timestamp:Date.now(),markdownNeedsReload:!0};r?ie(`[loadProjectContext] Project ${e.name}: Existing cache found. MarkdownNeedsReload: ${n.markdownNeedsReload}`):ie(`[loadProjectContext] Project ${e.name}: No existing cache found, building fresh context.`);let[o]=await Promise.all([this.processMarkdownFiles(e,n),this.processWebUrls(e,n),this.processYoutubeUrls(e,n)]);if(o.fileContexts){let i=Object.keys(o.fileContexts).length;if(ie(`[loadProjectContext] Project ${e.name}: Checking ${i} fileContexts for non-markdown processing.`),i>0){this.fileParserManager=new oI(Fi.getInstance(),this.app.vault,!0,e);let a=0;for(let s in o.fileContexts){let u=this.app.vault.getAbstractFileByPath(s);if(u instanceof vW.TFile&&u.extension!=="md"&&this.fileParserManager.supportsExtension(u.extension))try{await this.projectContextCache.getFileContext(e,s)||(ie(`[loadProjectContext] Project ${e.name}: Parsing/caching new/updated file: ${s}`),await this.fileParserManager.parseFile(u,this.app.vault),a++)}catch(l){if(fe(`[loadProjectContext] Project ${e.name}: Error parsing file ${s}:`,l),SN(l))throw l}}a>0&&ie(`[loadProjectContext] Project ${e.name}: Processed and cached ${a} non-markdown files.`)}}return o.timestamp=Date.now(),await this.projectContextCache.set(e,o),ie(`[loadProjectContext] Completed for project: ${e.name}.`),o}catch(r){throw fe(`[loadProjectContext] Failed for project ${e.name}:`,r),r}}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||a!==s)&&(await this.projectContextCache.invalidateMarkdownLine truncated
`;this.qaPrompt=xp.fromMessages([BE.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 vW=class{constructor(e,r){this.retrievedDocuments=[];this.chatMessages=[];this.chatMessages=[],this.app=e,this.vectorStoreManager=r,this.memoryManager=bW.getInstance(),this.chatModelManager=ED.getInstance(),this.promptManager=_W.getInstance(),this.initialize(),xa(async()=>{await this.createChainWithNewModel()})}getRetrievedDocuments(){return this.retrievedDocuments}async initialize(){await this.createChainWithNewModel()}getChain(){return this.chain}getRetrievalChain(){return this.retrievalChain}validateChainType(e){if(e==null)throw new Error("No chain type set")}validateChatModel(){if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){let e="Chat model is not initialized properly, check your API key in Copilot setting and make sure you have API access.";throw new Jle.Notice(e),new Error(e)}}validateChainInitialization(){(!this.chain||!mVe(this.chain))&&(console.error("Chain is not initialized properly, re-initializing chain: ",Fh()),this.createChainWithNewModel({},!1))}storeRetrieverDocuments(e){this.retrievedDocuments=e}async createChainWithNewModel(e={},r=!0){let n=Fh(),o=Mc();if(n==="project"&&!o)return;let i=n==="project"?o?.projectModelKey:hJ();if(!i)throw new Jle.Notice("No model key found"),new Error("No model key found");try{if(r){let a=tJ(i,ue().activeModels);if(a||(console.error("Resetting default model. No model configuration found for: ",i),a=Zb[0],i=a.name+"|"+a.provider),n==="project"&&!a.projectEnabled){let u=ue().activeModels.find(l=>l.enabled&&l.projectEnabled);if(u)a=u,i=u.name+"|"+u.provider,new Jle.Notice(`Model ${a.name} is not available in project mode. Switching to ${u.name}.`);else throw new Error("No project-enabled models available. Please enable a model for project mode in settings.")}let s={...a,...o?.modelConfigs};await this.chatModelManager.setChatModel(s)}this.setChain(n,e),ie(`Setting model to ${i}`)}catch(a){fe(`createChainWithNewModel failed: ${a}`),ie(`modelKey: ${i}`)}}async setChain(e,r={}){if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){console.error("setChain failed: No chat model set.");return}this.validateChainType(e);let n=this.chatModelManager.getChatModel(),o=this.memoryManager.getMemory(),i=this.promptManager.getChatPrompt();switch(e){case"llm_chain":{this.chain=d4.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),UR("llm_chain");break}case"vault_qa":{await this.initializeQAChain(r);let a=new jx({minSimilarityScore:.01,maxK:ue().maxSourceChunks,salientTerms:[]});this.retrievalChain=d4.createConversationalRetrievalChain({llm:n,retriever:a,systemMessage:Yb()},this.storeRetrieverDocuments.bind(this),ue().debug),UR("vault_qa"),ue().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=d4.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),UR("copilot_plus");break}case"project":{await this.initializeQAChain(r),this.chain=d4.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),UR("project");break}default:this.validateChainType(e);break}}getChainRunner(){let e=Fh();switch(e){case"llm_chain":return new Hie(this);case"vault_qa":return new Vie(this);case"copilot_plus":return new t5(this);case"project":return new Wie(this);default:throw new Error(`Unsupported chain type: ${e}`)}}async initializeQAChain(e){e.refreshIndex&&await this.vectorStoreManager.indexVaultToVectorStore()}async runChain(e,r,n,o,i={}){let{debug:a=!1,ignoreSystemMessage:s=!1}=i;a&&console.log(`==== Step 0: Initial user message ====
`,e),this.validateChatModel(),this.validateChainInitialization();let u=this.chatModelManager.getChatModel();if(s||FR(u)){let c=xp.fromMessages([new Gb("history"),Jb.fromTemplate("{input}")]);FR(u)&&(c=xp.fromMessages([[Pi,Yb()||""],c])),this.createChainWithNewModel({prompt:c},!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===Pi&&await this.memoryManager.getMemory().saveContext({input:n.message},{output:o.message})}}clearHistory(){this.chatMessages=[]}getChatMessages(){return this.chatMessages}setChatMessages(e){this.chatMessages=[...e]}addChatMessage(e){this.chatMessages.push(e)}};var ac=class t{constructor(e,r,n){this.defaultProjectKey="defaultProjectKey";this.app=e,this.plugin=n,this.currentProjectId=null,this.chainMangerInstance=new vW(e,r),this.projectContextCache=tb.getInstance(),this.chatMessageCache=new Map,this.fileParserManager=new oI(Fi.getInstance(),this.app.vault,!0,null),t8e(async()=>{await this.getCurrentChainManager().createChainWithNewModel()}),r8e(async()=>{HR()||await this.getCurrentChainManager().createChainWithNewModel({refreshIndex:ue().indexVaultToVectorStore==="ON MODE SWITCH"&&(Fh()==="vault_qa"||Fh()==="copilot_plus")})}),xF(async o=>{await this.switchProject(o)}),this.setupProjectListChangeMonitor()}setupProjectListChangeMonitor(){xa(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),this.getCurrentChainManager().createChainWithNewModel()]))}})}static getInstance(e,r,n){return t.instance||(t.instance=new t(e,r,n)),t.instance}getCurrentChainManager(){return this.chainMangerInstance}async switchProject(e){try{if(GE(!0),ie("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 oI(Fi.getInstance(),this.app.vault,!0,e),await this.loadProjectContext(e),this.refreshChatView(),ie(`Switched to project: ${e.name}`)}catch(r){throw fe(`Failed to switch project: ${r}`),r}finally{GE(!1)}}async saveCurrentProjectMessage(){this.chatMessageCache.set(this.currentProjectId?this.currentProjectId:this.defaultProjectKey,this.getCurrentChainManager().getChatMessages()),await this.plugin.autosaveCurrentChat()}async loadNextProjectMessage(){let e=this.getCurrentChainManager(),r=this.chatMessageCache.get(this.currentProjectId?this.currentProjectId:this.defaultProjectKey)??[];e.setChatMessages(r),await vN(r,e.memoryManager)}async loadProjectContext(e){try{if(!e.contextSource)return Mh(`[loadProjectContext] Project ${e.name}: No contextSource. Aborting.`),null;ie(`[loadProjectContext] Starting for project: ${e.name}`);let r=await this.projectContextCache.get(e),n=r||{markdownContext:"",webContexts:{},youtubeContexts:{},fileContexts:{},timestamp:Date.now(),markdownNeedsReload:!0};r?ie(`[loadProjectContext] Project ${e.name}: Existing cache found. MarkdownNeedsReload: ${n.markdownNeedsReload}`):ie(`[loadProjectContext] Project ${e.name}: No existing cache found, building fresh context.`);let[o]=await Promise.all([this.processMarkdownFiles(e,n),this.processWebUrls(e,n),this.processYoutubeUrls(e,n)]);if(o.fileContexts){let i=Object.keys(o.fileContexts).length;if(ie(`[loadProjectContext] Project ${e.name}: Checking ${i} fileContexts for non-markdown processing.`),i>0){this.fileParserManager=new oI(Fi.getInstance(),this.app.vault,!0,e);let a=0;for(let s in o.fileContexts){let u=this.app.vault.getAbstractFileByPath(s);if(u instanceof wW.TFile&&u.extension!=="md"&&this.fileParserManager.supportsExtension(u.extension))try{await this.projectContextCache.getFileContext(e,s)||(ie(`[loadProjectContext] Project ${e.name}: Parsing/caching new/updated file: ${s}`),await this.fileParserManager.parseFile(u,this.app.vault),a++)}catch(l){if(fe(`[loadProjectContext] Project ${e.name}: Error parsing file ${s}:`,l),xN(l))throw l}}a>0&&ie(`[loadProjectContext] Project ${e.name}: Processed and cached ${a} non-markdown files.`)}}return o.timestamp=Date.now(),await this.projectContextCache.set(e,o),ie(`[loadProjectContext] Completed for project: ${e.name}.`),o}catch(r){throw fe(`[loadProjectContext] Failed for project ${e.name}:`,r),r}}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||a!==s)&&(await this.projectContextCache.invalidateMarkdownLine truncated
`).filter(m=>m.trim()),p=l.split(`
`).filter(m=>m.trim());for(let m of f)p.includes(m)||await this.projectContextCache.removeWebUrl(r,m)}let c=e.contextSource?.youtubeUrls||"",d=r.contextSource?.youtubeUrls||"";if(c!==d){let f=c.split(`
`).filter(m=>m.trim()),p=d.split(`
@@ -760,33 +760,33 @@ ${l}`}));return ie("All markdown files processed for project context"),s.join(`
`)}async processWebUrls(e,r){ie(`[processWebUrls] Starting for project: ${e.name}`);let n=e.contextSource?.webUrls?.trim()||"";if(!n)return Object.keys(r.webContexts).length>0&&(ie(`[processWebUrls] Project ${e.name}: Clearing all Web contexts as none are configured.`),r.webContexts={}),r;let o=n.split(`
`).filter(c=>c.trim());ie(`[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&&ie(`[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){ie(`[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.processWebUrlsContext(c);return d&&ie(`[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&&Mh(`[processWebUrls] Project ${e.name}: Fetched empty content for Web URL: ${c.url}`)}),ie(`[processWebUrls] Completed for project: ${e.name}. Total Web contexts: ${Object.keys(r.webContexts).length}`),r}async processYoutubeUrls(e,r){ie(`[processYoutubeUrls] Starting for project: ${e.name}`);let n=e.contextSource?.youtubeUrls?.trim()||"";if(!n)return Object.keys(r.youtubeContexts).length>0&&(ie(`[processYoutubeUrls] Project ${e.name}: Clearing all YouTube contexts as none are configured.`),r.youtubeContexts={}),r;let o=n.split(`
`).filter(c=>c.trim());ie(`[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&&ie(`[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){ie(`[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.processYoutubeUrlsContext(c);return d&&ie(`[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&&Mh(`[processYoutubeUrls] Project ${e.name}: Fetched empty transcript for YouTube URL: ${c.url}`)}),ie(`[processYoutubeUrls] Completed for project: ${e.name}. Total YouTube contexts: ${Object.keys(r.youtubeContexts).length}`),r}async processWebUrlsContext(e){if(!e?.trim())return"";try{let r=Cq.getInstance(),{urlContext:n}=await r.processUrls(e);return n||""}catch(r){return fe(`Failed to process web URLs: ${r}`),new vW.Notice(`Failed to process web URLs: ${ei(r)}`),""}}async processYoutubeUrlsContext(e){if(!e?.trim())return"";let n=e.split(`
`).filter(c=>c.trim());ie(`[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&&ie(`[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){ie(`[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.processYoutubeUrlsContext(c);return d&&ie(`[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&&Mh(`[processYoutubeUrls] Project ${e.name}: Fetched empty transcript for YouTube URL: ${c.url}`)}),ie(`[processYoutubeUrls] Completed for project: ${e.name}. Total YouTube contexts: ${Object.keys(r.youtubeContexts).length}`),r}async processWebUrlsContext(e){if(!e?.trim())return"";try{let r=Oq.getInstance(),{urlContext:n}=await r.processUrls(e);return n||""}catch(r){return fe(`Failed to process web URLs: ${r}`),new wW.Notice(`Failed to process web URLs: ${ei(r)}`),""}}async processYoutubeUrlsContext(e){if(!e?.trim())return"";let n=e.split(`
`).filter(i=>i.trim()).map(async i=>{try{let a=await Fi.getInstance().youtube4llm(i);return a.response.transcript?`
YouTube transcript from ${i}:
${a.response.transcript}`:""}catch(a){return fe(`Failed to process YouTube URL ${i}: ${a}`),new vW.Notice(`Failed to process YouTube URL ${i}: ${ei(a)}`),""}});return(await Promise.all(n)).join("")}onunload(){this.projectContextCache.cleanup()}};Cl();$r();yo();nr();WLe();$r();mg();yo();nr();var Vg=require("@codemirror/view"),QP=require("@codemirror/state");function f3t(t,e,r=void 0){let n={force:()=>{}},o=null;async function*i(...a){o&&clearTimeout(o);let s=null;try{await new Promise(u=>{s=o=setTimeout(()=>u(),e),n.force=()=>{o&&clearTimeout(o),u()}})}catch{if(r!==void 0)throw r}for await(let u of t(...a)){if(s!==o)break;yield u}}return{debounced:i,force:()=>n.force()}}var Uwn=Object.defineProperty,zwn=(t,e,r)=>e in t?Uwn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,WU=(t,e,r)=>(zwn(t,typeof e!="symbol"?e+"":e,r),r),Kle=QP.StateField.define({create(){return{suggestion:null}},update(t,e){let r=e.effects.find(n=>n.is(ZLe));return e.state.doc&&r&&(r.value.doc==null||e.state.doc==r.value.doc)?{suggestion:r.value.suggestion}:{suggestion:null}}}),ZLe=QP.StateEffect.define();function Hwn(t,e){let r=t.state.selection.main.head,n=[],o=Vg.Decoration.widget({widget:new KLe(e),side:1});return n.push(o.range(r)),Vg.Decoration.set(n)}var KLe=class extends Vg.WidgetType{constructor(e){super(),WU(this,"suggestion"),this.suggestion=e}toDOM(){let e=document.createElement("span");return e.style.opacity="0.4",e.className="cm-inline-suggestion",e.textContent=this.suggestion,e}},GLe=t=>{let e=0;return Vg.ViewPlugin.fromClass(class{async update(r){let n=r.state.doc;if(!r.docChanged)return;let o=++e;for await(let i of t(r.state)){if(o!=e)return;r.view.dispatch({effects:ZLe.of({suggestion:i,doc:n})})}}})},JLe=class{constructor(){WU(this,"decorations"),this.decorations=Vg.Decoration.none}update(e){var r;let n=(r=e.state.field(Kle))==null?void 0:r.suggestion;if(!n){this.decorations=Vg.Decoration.none;return}this.decorations=Hwn(e.view,n.display_suggestion)}},p3t=Vg.ViewPlugin.fromClass(JLe,{decorations:t=>t.decorations}),YLe=class{constructor(e,r){WU(this,"suggestFn"),WU(this,"keymap"),WU(this,"completionId"),WU(this,"run",n=>{var o,i;let a=(o=n.state.field(Kle))==null?void 0:o.suggestion;return a?(n.dispatch({...Vwn(n.state,a.complete_suggestion,n.state.selection.main.head,n.state.selection.main.head)}),(i=a.accept_hook)==null||i.call(a),(async()=>{if(this.suggestFn==null)return;let s=++this.completionId;for await(let u of this.suggestFn(n.state)){if(s!=this.completionId)return;n.dispatch({effects:ZLe.of({suggestion:{complete_suggestion:u.complete_suggestion,display_suggestion:u.display_suggestion,accept_hook:u.accept_hook},doc:null})})}})(),!0):!1}),this.suggestFn=e,this.keymap=QP.Prec.highest(Vg.keymap.of([{key:r,run:n=>this.run(n)}])),this.completionId=0}};function Vwn(t,e,r,n){return{...t.changeByRange(o=>{if(o==t.selection.main)return{changes:{from:r,to:n,insert:e},range:QP.EditorSelection.cursor(r+e.length)};let i=n-r;return!o.empty||i&&t.sliceDoc(o.from-i,o.from)!=t.sliceDoc(r,n)?{range:o}:{changes:{from:o.from-i,to:o.from,insert:e},range:QP.EditorSelection.cursor(o.from-i+e.length)}}),userEvent:"input.complete"}}function m3t(t){return typeof t=="string"?{complete_suggestion:t,display_suggestion:t}:t}function Wwn(t){return async function*(e){let r=await t(e);if(typeof r=="string"||"complete_suggestion"in r){yield m3t(r);return}for await(let n of r)yield m3t(n)}}function Gle(t){let{delay:e=500,accept_shortcut:r="Tab"}=t,n=Wwn(t.fetchFn),{debounced:o,force:i}=f3t(n,e);return{extension:r?[Kle,GLe(o),p3t,new YLe(t.continue_suggesting?n:null,r).keymap]:[Kle,GLe(o),p3t],force_fetch:i}}var rFe=require("obsidian");var XLe=class{process(e){let{prefix:r,suffix:n}=e,{completion:o}=e;return o=this.removeWordOverlapPrefix(r,o),o=this.removeWordOverlapSuffix(o,n),o=this.removeCharacterOverlapPrefix(r,o),o=this.removeCharacterOverlapSuffix(o,n),o.startsWith(" ")&&this.endsWithMarker(r)&&(o=o.trimStart()),o}removeWordOverlapPrefix(e,r){let n=r.trimStart(),o=this.getPotentialPrefixSegments(e);for(let i of o)if(n.startsWith(i))return n.substring(i.length);return r}removeWordOverlapSuffix(e,r){let n=r.trimStart(),o=this.getPotentialCompletionSegments(e);for(let i of o)if(n.startsWith(i)&&e.endsWith(i))return e.substring(0,e.length-i.length);return e}removeCharacterOverlapPrefix(e,r){let n=e.length-1,o=0,i=0;for(;o<r.length&&n>=0&&r[o]===e[n]&&this.isWhiteSpaceOrCommonMarker(r[o]);)i++,n--,o++;return i>0?r.substring(i):r}removeCharacterOverlapSuffix(e,r){let n=0,o=e.length-1,i=0;for(;n<r.length&&o>=0&&e[o]===r[n]&&this.isWhiteSpaceOrCommonMarker(e[o]);)i++,n++,o--;return i>0?e.substring(0,e.length-i):e}getPotentialPrefixSegments(e){let r=[],n=this.startLocationOfEachWordOrMarker(e);for(let o=n.length-1;o>=0;o--)r.push(e.substring(n[o]));return e.length>0&&(r.length===0||r[r.length-1]!==e)&&r.push(e),e.length>1&&(r.length===0||r[r.length-1]!==e.slice(-1))&&r.push(e.slice(-1)),e.length>2&&(r.length===0||r[r.length-1]!==e.slice( Line truncated
${a.response.transcript}`:""}catch(a){return fe(`Failed to process YouTube URL ${i}: ${a}`),new wW.Notice(`Failed to process YouTube URL ${i}: ${ei(a)}`),""}});return(await Promise.all(n)).join("")}onunload(){this.projectContextCache.cleanup()}};Cl();$r();yo();nr();GLe();$r();mg();yo();nr();var Vg=require("@codemirror/view"),QP=require("@codemirror/state");function y3t(t,e,r=void 0){let n={force:()=>{}},o=null;async function*i(...a){o&&clearTimeout(o);let s=null;try{await new Promise(u=>{s=o=setTimeout(()=>u(),e),n.force=()=>{o&&clearTimeout(o),u()}})}catch{if(r!==void 0)throw r}for await(let u of t(...a)){if(s!==o)break;yield u}}return{debounced:i,force:()=>n.force()}}var Kwn=Object.defineProperty,Gwn=(t,e,r)=>e in t?Kwn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,KU=(t,e,r)=>(Gwn(t,typeof e!="symbol"?e+"":e,r),r),Yle=QP.StateField.define({create(){return{suggestion:null}},update(t,e){let r=e.effects.find(n=>n.is(QLe));return e.state.doc&&r&&(r.value.doc==null||e.state.doc==r.value.doc)?{suggestion:r.value.suggestion}:{suggestion:null}}}),QLe=QP.StateEffect.define();function Jwn(t,e){let r=t.state.selection.main.head,n=[],o=Vg.Decoration.widget({widget:new JLe(e),side:1});return n.push(o.range(r)),Vg.Decoration.set(n)}var JLe=class extends Vg.WidgetType{constructor(e){super(),KU(this,"suggestion"),this.suggestion=e}toDOM(){let e=document.createElement("span");return e.style.opacity="0.4",e.className="cm-inline-suggestion",e.textContent=this.suggestion,e}},YLe=t=>{let e=0;return Vg.ViewPlugin.fromClass(class{async update(r){let n=r.state.doc;if(!r.docChanged)return;let o=++e;for await(let i of t(r.state)){if(o!=e)return;r.view.dispatch({effects:QLe.of({suggestion:i,doc:n})})}}})},ZLe=class{constructor(){KU(this,"decorations"),this.decorations=Vg.Decoration.none}update(e){var r;let n=(r=e.state.field(Yle))==null?void 0:r.suggestion;if(!n){this.decorations=Vg.Decoration.none;return}this.decorations=Jwn(e.view,n.display_suggestion)}},b3t=Vg.ViewPlugin.fromClass(ZLe,{decorations:t=>t.decorations}),XLe=class{constructor(e,r){KU(this,"suggestFn"),KU(this,"keymap"),KU(this,"completionId"),KU(this,"run",n=>{var o,i;let a=(o=n.state.field(Yle))==null?void 0:o.suggestion;return a?(n.dispatch({...Ywn(n.state,a.complete_suggestion,n.state.selection.main.head,n.state.selection.main.head)}),(i=a.accept_hook)==null||i.call(a),(async()=>{if(this.suggestFn==null)return;let s=++this.completionId;for await(let u of this.suggestFn(n.state)){if(s!=this.completionId)return;n.dispatch({effects:QLe.of({suggestion:{complete_suggestion:u.complete_suggestion,display_suggestion:u.display_suggestion,accept_hook:u.accept_hook},doc:null})})}})(),!0):!1}),this.suggestFn=e,this.keymap=QP.Prec.highest(Vg.keymap.of([{key:r,run:n=>this.run(n)}])),this.completionId=0}};function Ywn(t,e,r,n){return{...t.changeByRange(o=>{if(o==t.selection.main)return{changes:{from:r,to:n,insert:e},range:QP.EditorSelection.cursor(r+e.length)};let i=n-r;return!o.empty||i&&t.sliceDoc(o.from-i,o.from)!=t.sliceDoc(r,n)?{range:o}:{changes:{from:o.from-i,to:o.from,insert:e},range:QP.EditorSelection.cursor(o.from-i+e.length)}}),userEvent:"input.complete"}}function _3t(t){return typeof t=="string"?{complete_suggestion:t,display_suggestion:t}:t}function Zwn(t){return async function*(e){let r=await t(e);if(typeof r=="string"||"complete_suggestion"in r){yield _3t(r);return}for await(let n of r)yield _3t(n)}}function Zle(t){let{delay:e=500,accept_shortcut:r="Tab"}=t,n=Zwn(t.fetchFn),{debounced:o,force:i}=y3t(n,e);return{extension:r?[Yle,YLe(o),b3t,new XLe(t.continue_suggesting?n:null,r).keymap]:[Yle,YLe(o),b3t],force_fetch:i}}var oFe=require("obsidian");var eFe=class{process(e){let{prefix:r,suffix:n}=e,{completion:o}=e;return o=this.removeWordOverlapPrefix(r,o),o=this.removeWordOverlapSuffix(o,n),o=this.removeCharacterOverlapPrefix(r,o),o=this.removeCharacterOverlapSuffix(o,n),o.startsWith(" ")&&this.endsWithMarker(r)&&(o=o.trimStart()),o}removeWordOverlapPrefix(e,r){let n=r.trimStart(),o=this.getPotentialPrefixSegments(e);for(let i of o)if(n.startsWith(i))return n.substring(i.length);return r}removeWordOverlapSuffix(e,r){let n=r.trimStart(),o=this.getPotentialCompletionSegments(e);for(let i of o)if(n.startsWith(i)&&e.endsWith(i))return e.substring(0,e.length-i.length);return e}removeCharacterOverlapPrefix(e,r){let n=e.length-1,o=0,i=0;for(;o<r.length&&n>=0&&r[o]===e[n]&&this.isWhiteSpaceOrCommonMarker(r[o]);)i++,n--,o++;return i>0?r.substring(i):r}removeCharacterOverlapSuffix(e,r){let n=0,o=e.length-1,i=0;for(;n<r.length&&o>=0&&e[o]===r[n]&&this.isWhiteSpaceOrCommonMarker(e[o]);)i++,n++,o--;return i>0?e.substring(0,e.length-i):e}getPotentialPrefixSegments(e){let r=[],n=this.startLocationOfEachWordOrMarker(e);for(let o=n.length-1;o>=0;o--)r.push(e.substring(n[o]));return e.length>0&&(r.length===0||r[r.length-1]!==e)&&r.push(e),e.length>1&&(r.length===0||r[r.length-1]!==e.slice(-1))&&r.push(e.slice(-1)),e.length>2&&(r.length===0||r[r.length-1]!==e.slice( Line truncated
`)&&a.startsWith(`
`)&&(a=a.substring(1)),a}},eFe=class{process(e){let{completion:r,context:n}=e;if(n==="CodeBlock"){let o=r;return o=o.replace(/```[a-zA-Z]*[ \t]*\n?/g,""),o=o.replace(/\n?```[ \t]*\n?/g,""),o.endsWith(`
`)&&(o=o.slice(0,-1)),o}return r}},Jle=class{constructor(){this.processors=[];this.processors.push(new eFe),this.processors.push(new XLe),this.processors.push(new QLe)}process(e,r,n,o){let a={prefix:e,suffix:r,completion:n,context:o};for(let s of this.processors)a.completion=s.process(a);return a.completion}};d4();var h3t=require("obsidian");function g3t(t,e=20){let r=app.metadataCache.getFileCache(t),n=[];if(r?.links)for(let o of r.links){let i=app.metadataCache.getFirstLinkpathDest(o.link,t.path);if(i&&(n.push(i),n.length>=e))break}if(r?.embeds&&n.length<e)for(let o of r.embeds){let i=app.metadataCache.getFirstLinkpathDest(o.link,t.path);if(i&&(n.push(i),n.length>=e))break}return[...new Set(n)]}function y3t(t,e=20){let r=[],n=app.metadataCache.getBacklinksForFile(t);if(n?.data)for(let[o]of n.data){let i=app.vault.getAbstractFileByPath(o);if(i instanceof h3t.TFile&&(r.push(i),r.length>=e))break}return r}Qoe();nr();var tFe=require("obsidian"),Kwn=.4,Gwn=20,b3t=.7,Yle=.3;async function Jwn(t,e){let r=ue().debug,n=await eP.getDocsByPath(e,t);if(!n)return r&&console.log("No hits found for note:",t),[];let o=[];for(let i of n){if(!i?.document?.embedding){r&&console.log("No embedding found for note:",t);continue}o.push(i.document.embedding)}return o}function Ywn(t){if(t.length===0)return[];let e=t[0].length,r=Array(e).fill(0);return t.forEach(n=>{n.forEach((o,i)=>{r[i]+=o/e})}),r}function Zwn(t,e){let r=new Map;for(let n of t){let o=r.get(n.document.path);o?n.score>o&&r.set(n.document.path,n.score):r.set(n.document.path,n.score)}return r.delete(e),r}async function Xwn({db:t,filePath:e}){let r=ue().debug,n=await Jwn(e,t),o=Ywn(n);if(o.length===0)return r&&console.log("No embeddings found for note:",e),new Map;let i=await eP.getDocsByEmbedding(t,o,{limit:Gwn,similarity:Kwn});return Zwn(i,e)}function Qwn(t){let e=new Map,n=g3t(t).map(a=>a.path);for(let a of n)e.set(a,{links:!0,backlinks:!1});let i=y3t(t).map(a=>a.path);for(let a of i)e.has(a)?e.set(a,{links:!0,backlinks:!0}):e.set(a,{links:!1,backlinks:!0});return e}function e0n(t,e){let r=new Map,n=b3t+Yle;for(let[o,i]of t)r.set(o,i*b3t/n);for(let[o,i]of e){let a=0;i.links&&i.backlinks?a=Yle:(i.links||i.backlinks)&&(a=Yle*.8),r.set(o,(r.get(o)??0)+a)}return r}async function Xle({db:t,filePath:e}){let r=app.vault.getAbstractFileByPath(e);if(!(r instanceof tFe.TFile))return[];let n=await Xwn({db:t,filePath:e}),o=Qwn(r),i=e0n(n,o);return Array.from(i.entries()).sort((s,u)=>{let l=s[0],c=u[0],d=Zle(n.get(l)??0),f=Zle(n.get(c)??0);return d!==f?f-d:u[1]-s[1]}).map(([s,u])=>{let l=app.vault.getAbstractFileByPath(s);return l instanceof tFe.TFile?{document:{path:s,title:l.basename},metadata:{score:u,similarityScore:n.get(s),hasOutgoingLinks:o.get(s)?.links??!1,hasBacklinks:o.get(s)?.backlinks??!1}}:null}).filter(s=>s!==null)}function Zle(t){return t>.7?3:t>.55?2:1}Ix();var _3t=require("obsidian"),t0n={cjk:[[19968,40959],[13312,19903],[131072,173791],[173824,177983],[177984,178207],[178208,183983]],japanese:[[12352,12447],[12448,12543]],korean:[[44032,55215],[4352,4607]],other:[[3584,3711],[1536,1791],[2304,2431],[2432,2559],[2688,2815],[2944,3071]]};function r0n(t,e){let r=t.codePointAt(0);return r?e.some(([n,o])=>r>=n&&r<=o):!1}function v3t(t){let e=t.replace(/[\p{Emoji}\p{Symbol}\p{Punctuation}]/gu,"");if(!e)return!1;for(let r of e)if(Object.values(t0n).some(n=>r0n(r,n)))return!0;return!1}function w3t(t,e){let r="",n="",o=Math.max(0,e.line-5);for(let u=o;u<e.line;u++)r+=t.getLine(u)+`
`)&&(a=a.substring(1)),a}},rFe=class{process(e){let{completion:r,context:n}=e;if(n==="CodeBlock"){let o=r;return o=o.replace(/```[a-zA-Z]*[ \t]*\n?/g,""),o=o.replace(/\n?```[ \t]*\n?/g,""),o.endsWith(`
`)&&(o=o.slice(0,-1)),o}return r}},Xle=class{constructor(){this.processors=[];this.processors.push(new rFe),this.processors.push(new eFe),this.processors.push(new tFe)}process(e,r,n,o){let a={prefix:e,suffix:r,completion:n,context:o};for(let s of this.processors)a.completion=s.process(a);return a.completion}};f4();var v3t=require("obsidian");function w3t(t,e=20){let r=app.metadataCache.getFileCache(t),n=[];if(r?.links)for(let o of r.links){let i=app.metadataCache.getFirstLinkpathDest(o.link,t.path);if(i&&(n.push(i),n.length>=e))break}if(r?.embeds&&n.length<e)for(let o of r.embeds){let i=app.metadataCache.getFirstLinkpathDest(o.link,t.path);if(i&&(n.push(i),n.length>=e))break}return[...new Set(n)]}function S3t(t,e=20){let r=[],n=app.metadataCache.getBacklinksForFile(t);if(n?.data)for(let[o]of n.data){let i=app.vault.getAbstractFileByPath(o);if(i instanceof v3t.TFile&&(r.push(i),r.length>=e))break}return r}rie();nr();var nFe=require("obsidian"),Xwn=.4,Qwn=20,x3t=.7,Qle=.3;async function e0n(t,e){let r=ue().debug,n=await eP.getDocsByPath(e,t);if(!n)return r&&console.log("No hits found for note:",t),[];let o=[];for(let i of n){if(!i?.document?.embedding){r&&console.log("No embedding found for note:",t);continue}o.push(i.document.embedding)}return o}function t0n(t){if(t.length===0)return[];let e=t[0].length,r=Array(e).fill(0);return t.forEach(n=>{n.forEach((o,i)=>{r[i]+=o/e})}),r}function r0n(t,e){let r=new Map;for(let n of t){let o=r.get(n.document.path);o?n.score>o&&r.set(n.document.path,n.score):r.set(n.document.path,n.score)}return r.delete(e),r}async function n0n({db:t,filePath:e}){let r=ue().debug,n=await e0n(e,t),o=t0n(n);if(o.length===0)return r&&console.log("No embeddings found for note:",e),new Map;let i=await eP.getDocsByEmbedding(t,o,{limit:Qwn,similarity:Xwn});return r0n(i,e)}function o0n(t){let e=new Map,n=w3t(t).map(a=>a.path);for(let a of n)e.set(a,{links:!0,backlinks:!1});let i=S3t(t).map(a=>a.path);for(let a of i)e.has(a)?e.set(a,{links:!0,backlinks:!0}):e.set(a,{links:!1,backlinks:!0});return e}function i0n(t,e){let r=new Map,n=x3t+Qle;for(let[o,i]of t)r.set(o,i*x3t/n);for(let[o,i]of e){let a=0;i.links&&i.backlinks?a=Qle:(i.links||i.backlinks)&&(a=Qle*.8),r.set(o,(r.get(o)??0)+a)}return r}async function tce({db:t,filePath:e}){let r=app.vault.getAbstractFileByPath(e);if(!(r instanceof nFe.TFile))return[];let n=await n0n({db:t,filePath:e}),o=o0n(r),i=i0n(n,o);return Array.from(i.entries()).sort((s,u)=>{let l=s[0],c=u[0],d=ece(n.get(l)??0),f=ece(n.get(c)??0);return d!==f?f-d:u[1]-s[1]}).map(([s,u])=>{let l=app.vault.getAbstractFileByPath(s);return l instanceof nFe.TFile?{document:{path:s,title:l.basename},metadata:{score:u,similarityScore:n.get(s),hasOutgoingLinks:o.get(s)?.links??!1,hasBacklinks:o.get(s)?.backlinks??!1}}:null}).filter(s=>s!==null)}function ece(t){return t>.7?3:t>.55?2:1}Mx();var C3t=require("obsidian"),a0n={cjk:[[19968,40959],[13312,19903],[131072,173791],[173824,177983],[177984,178207],[178208,183983]],japanese:[[12352,12447],[12448,12543]],korean:[[44032,55215],[4352,4607]],other:[[3584,3711],[1536,1791],[2304,2431],[2432,2559],[2688,2815],[2944,3071]]};function s0n(t,e){let r=t.codePointAt(0);return r?e.some(([n,o])=>r>=n&&r<=o):!1}function O3t(t){let e=t.replace(/[\p{Emoji}\p{Symbol}\p{Punctuation}]/gu,"");if(!e)return!1;for(let r of e)if(Object.values(a0n).some(n=>s0n(r,n)))return!0;return!1}function P3t(t,e){let r="",n="",o=Math.max(0,e.line-5);for(let u=o;u<e.line;u++)r+=t.getLine(u)+`
`;let i=t.getLine(e.line);r+=i.slice(0,e.ch),(e.ch===0||e.ch===i.length&&i.trim()==="")&&(r+=`
`);let a=Math.max(0,e.line-50);for(let u=a;u<e.line;u++)n+=t.getLine(u)+`
`;n+=i.slice(0,e.ch)+"{{CURSOR}}"+i.slice(e.ch)+`
`;let s=Math.min(t.lineCount()-1,e.line+50);for(let u=e.line+1;u<=s;u++)n+=t.getLine(u)+`
`;return{prefix:r,noteContext:n}}var YI=class YI{constructor(){this.currentNotePath=null;this.cachedNotes=null;this.cachedNoteTitles=[]}static getInstance(){return YI.instance||(YI.instance=new YI),YI.instance}getRelevantNoteTitles(){return this.cachedNoteTitles}async getRelevantNotes(e){if(!e)return this.currentNotePath=null,this.cachedNotes=null,this.cachedNoteTitles=[],"";if(this.currentNotePath===e.path&&this.cachedNotes!==null)return this.cachedNotes;let r=await ma.getInstance().getDb(),o=(await Xle({db:r,filePath:e.path})).slice(0,YI.MAX_RELEVANT_NOTES);this.cachedNoteTitles=o.map(a=>a.document.title);let i=await Promise.all(o.map(async a=>{let s=app.vault.getAbstractFileByPath(a.document.path);if(!(s instanceof _3t.TFile))return"";let u=await app.vault.cachedRead(s);if(!u)return"";let l=u.length>3e3?u.slice(0,3e3)+"...":u;return`[[${a.document.title}]]:
`;return{prefix:r,noteContext:n}}var YI=class YI{constructor(){this.currentNotePath=null;this.cachedNotes=null;this.cachedNoteTitles=[]}static getInstance(){return YI.instance||(YI.instance=new YI),YI.instance}getRelevantNoteTitles(){return this.cachedNoteTitles}async getRelevantNotes(e){if(!e)return this.currentNotePath=null,this.cachedNotes=null,this.cachedNoteTitles=[],"";if(this.currentNotePath===e.path&&this.cachedNotes!==null)return this.cachedNotes;let r=await ma.getInstance().getDb(),o=(await tce({db:r,filePath:e.path})).slice(0,YI.MAX_RELEVANT_NOTES);this.cachedNoteTitles=o.map(a=>a.document.title);let i=await Promise.all(o.map(async a=>{let s=app.vault.getAbstractFileByPath(a.document.path);if(!(s instanceof C3t.TFile))return"";let u=await app.vault.cachedRead(s);if(!u)return"";let l=u.length>3e3?u.slice(0,3e3)+"...":u;return`[[${a.document.title}]]:
${l}`}));return this.currentNotePath=e.path,this.cachedNotes=i.join(`
`),this.cachedNotes}clearCache(){this.currentNotePath=null,this.cachedNotes=null,this.cachedNoteTitles=[]}};YI.MAX_RELEVANT_NOTES=3;var Qle=YI;var ED=class{constructor(){this.MIN_WORD_LENGTH=4;this.STOP_WORDS=new Set(["a","ain","all","am","an","and","any","are","as","at","be","but","by","can","d","did","do","don","few","for","had","has","he","her","him","his","how","i","if","in","is","isn","it","its","ll","m","ma","me","my","no","nor","not","now","o","of","off","on","or","our","out","own","re","s","she","so","t","the","to","too","up","ve","was","we","who","why","won","y","you"])}extractWords(e){return(this.preprocessText(e).match(/\b[a-zA-Z]+(?:'[a-zA-Z]+)?\b/g)||[]).filter(o=>this.isValidWord(o))}isWordCharacter(e){return/[a-zA-Z']/.test(e)}isValidWord(e){return!(e.length<this.MIN_WORD_LENGTH||!/^[a-zA-Z]+(?:'[a-zA-Z]+)?$/.test(e)||this.STOP_WORDS.has(e.toLowerCase())||e===e.toUpperCase()&&e.length>4)}getLanguage(){return"en"}preprocessText(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`[^`]+`/g," ").replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/<[^>]+>/g," ").replace(/^#+\s+/gm,"").replace(/[*_]{1,2}([^*_]+)[*_]{1,2}/g,"$1").replace(/^\s*[-*+]\s+/gm,"").replace(/^\s*\d+\.\s+/gm,"").replace(/\s+/g," ").trim()}};var SW=class{constructor(e=5e4){this.wordCount=0;this.root=this.createNode(),this.maxSize=e}createNode(){return{children:new Map,isEndOfWord:!1,wordEntry:void 0}}addWord(e,r){if(!e||e.length<4||this.wordCount>=this.maxSize&&!this.hasWord(e))return;let n=this.root;for(let o of e)n.children.has(o)||n.children.set(o,this.createNode()),n=n.children.get(o);n.isEndOfWord?n.wordEntry&&(n.wordEntry.frequency++,n.wordEntry.lastSeen=Date.now(),r&&!n.wordEntry.contexts.includes(r)&&(n.wordEntry.contexts.push(r),n.wordEntry.contexts.length>10&&(n.wordEntry.contexts=n.wordEntry.contexts.slice(-10)))):(n.isEndOfWord=!0,n.wordEntry={word:e,frequency:1,contexts:r?[r]:[],lastSeen:Date.now()},this.wordCount++)}hasWord(e){let r=this.findNode(e);return r!==null&&r.isEndOfWord}getWordEntry(e){let r=this.findNode(e);return r&&r.isEndOfWord&&r.wordEntry?r.wordEntry:null}findNode(e){let r=this.root;for(let n of e){if(!r.children.has(n))return null;r=r.children.get(n)}return r}getSuggestions(e,r=10){if(!e)return[];let n=[],o=this.generatePrefixVariants(e);for(let a of o){let s=this.findNode(a);if(s&&(this.collectWords(s,a,n,r,e),n.length>=r))break}let i=this.deduplicateSuggestions(n);return i.sort((a,s)=>s.score-a.score),i.slice(0,r)}generatePrefixVariants(e){let r=new Set;return r.add(e),r.add(e.toLowerCase()),e.length>0&&r.add(e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()),r.add(e.toUpperCase()),Array.from(r)}deduplicateSuggestions(e){let r=new Map;for(let n of e){let o=n.word,i=r.get(o);(!i||n.score>i.score)&&r.set(o,n)}return Array.from(r.values())}collectWords(e,r,n,o,i){if(!(n.length>=o)){if(e.isEndOfWord&&e.wordEntry){let a=this.calculateScore(e.wordEntry)+this.getCaseMatchBonus(r,i);n.push({word:r,score:a,source:"vault"})}for(let[a,s]of e.children)this.collectWords(s,r+a,n,o,i)}}getCaseMatchBonus(e,r){if(e.length<r.length)return 0;let n=e.substring(0,r.length);return n===r?2:this.hasSameCasePattern(n,r)?1.5:1}hasSameCasePattern(e,r){if(e.length<r.length)return!1;for(let n=0;n<r.length;n++){let o=e[n],i=r[n],a=o===o.toUpperCase(),s=i===i.toUpperCase();if(a!==s)return!1}return!0}calculateScore(e){let r=Math.log(e.frequency+1)*10,n=Math.max(0,(Date.now()-e.lastSeen)/(1e3*60*60*24)),o=Math.max(0,10-n);return r+o}getStats(){let e=0,r=0,n=(o,i=0)=>{e++,r=Math.max(r,i);for(let a of o.children.values())n(a,i+1)};return n(this.root),{wordCount:this.wordCount,nodeCount:e,maxDepth:r}}clear(){this.root=this.createNode(),this.wordCount=0}getAllWords(){let e=[],r=n=>{n.isEndOfWord&&n.wordEntry&&e.push(n.wordEntry);for(let o of n.children.values())r(o)};return r(this.root),e}addWords(e,r){for(let n of e)this.addWord(n,r)}pruneByFrequency(e=2){let r=0,n=o=>{let i=[];for(let[a,s]of o.children)n(s)&&i.push(a);for(let a of i)o.children.delete(a);return o.isEndOfWord&&o.wordEntry&&o.wordEntry.frequency<e&&(o.isEndOfWord=!1,o.wordEntry=void 0,this.wordCount--,r++),o.children.size===0&&!o.isEndOfWord};return n(this.root),r}};yo();var S3t=require("obsidian");var xW=class{constructor(e,r,n,o){this.isScanning=!1;this.vault=e,this.settings=r,this.performance=n,this.tokenizer=o||new ED}async scanVault(e){let r=Date.now(),n=[],o=new Map;try{let i=this.vault.getMarkdownFiles(),a=0;for(let l of i)try{e&&e({currentFile:l.path,processedFiles:a,totalFiles:i.length,foundWords:o.size});try{let d=await this.vault.adapter.stat(l.path);if(d&&d.size>this.performance.maxFileSize){n.push(`Skipped large file: ${l.path}`);continue}}catch{}let c=await this.vault.read(l);await this.processFile(l.path,c,o),a++,a%this.performance.batchSize===0&&await new Promise(d=>setTimeout(d,1))}catch(c){let d=`Error processing file ${l.path}: ${c}`;fe(d),n.push(d)}(this.settings.includeFileNames||this.settings.includeFolderNameLine truncated
`),this.cachedNotes}clearCache(){this.currentNotePath=null,this.cachedNotes=null,this.cachedNoteTitles=[]}};YI.MAX_RELEVANT_NOTES=3;var rce=YI;var TD=class{constructor(){this.MIN_WORD_LENGTH=4;this.STOP_WORDS=new Set(["a","ain","all","am","an","and","any","are","as","at","be","but","by","can","d","did","do","don","few","for","had","has","he","her","him","his","how","i","if","in","is","isn","it","its","ll","m","ma","me","my","no","nor","not","now","o","of","off","on","or","our","out","own","re","s","she","so","t","the","to","too","up","ve","was","we","who","why","won","y","you"])}extractWords(e){return(this.preprocessText(e).match(/\b[a-zA-Z]+(?:'[a-zA-Z]+)?\b/g)||[]).filter(o=>this.isValidWord(o))}isWordCharacter(e){return/[a-zA-Z']/.test(e)}isValidWord(e){return!(e.length<this.MIN_WORD_LENGTH||!/^[a-zA-Z]+(?:'[a-zA-Z]+)?$/.test(e)||this.STOP_WORDS.has(e.toLowerCase())||e===e.toUpperCase()&&e.length>4)}getLanguage(){return"en"}preprocessText(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`[^`]+`/g," ").replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/<[^>]+>/g," ").replace(/^#+\s+/gm,"").replace(/[*_]{1,2}([^*_]+)[*_]{1,2}/g,"$1").replace(/^\s*[-*+]\s+/gm,"").replace(/^\s*\d+\.\s+/gm,"").replace(/\s+/g," ").trim()}};var xW=class{constructor(e=5e4){this.wordCount=0;this.root=this.createNode(),this.maxSize=e}createNode(){return{children:new Map,isEndOfWord:!1,wordEntry:void 0}}addWord(e,r){if(!e||e.length<4||this.wordCount>=this.maxSize&&!this.hasWord(e))return;let n=this.root;for(let o of e)n.children.has(o)||n.children.set(o,this.createNode()),n=n.children.get(o);n.isEndOfWord?n.wordEntry&&(n.wordEntry.frequency++,n.wordEntry.lastSeen=Date.now(),r&&!n.wordEntry.contexts.includes(r)&&(n.wordEntry.contexts.push(r),n.wordEntry.contexts.length>10&&(n.wordEntry.contexts=n.wordEntry.contexts.slice(-10)))):(n.isEndOfWord=!0,n.wordEntry={word:e,frequency:1,contexts:r?[r]:[],lastSeen:Date.now()},this.wordCount++)}hasWord(e){let r=this.findNode(e);return r!==null&&r.isEndOfWord}getWordEntry(e){let r=this.findNode(e);return r&&r.isEndOfWord&&r.wordEntry?r.wordEntry:null}findNode(e){let r=this.root;for(let n of e){if(!r.children.has(n))return null;r=r.children.get(n)}return r}getSuggestions(e,r=10){if(!e)return[];let n=[],o=this.generatePrefixVariants(e);for(let a of o){let s=this.findNode(a);if(s&&(this.collectWords(s,a,n,r,e),n.length>=r))break}let i=this.deduplicateSuggestions(n);return i.sort((a,s)=>s.score-a.score),i.slice(0,r)}generatePrefixVariants(e){let r=new Set;return r.add(e),r.add(e.toLowerCase()),e.length>0&&r.add(e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()),r.add(e.toUpperCase()),Array.from(r)}deduplicateSuggestions(e){let r=new Map;for(let n of e){let o=n.word,i=r.get(o);(!i||n.score>i.score)&&r.set(o,n)}return Array.from(r.values())}collectWords(e,r,n,o,i){if(!(n.length>=o)){if(e.isEndOfWord&&e.wordEntry){let a=this.calculateScore(e.wordEntry)+this.getCaseMatchBonus(r,i);n.push({word:r,score:a,source:"vault"})}for(let[a,s]of e.children)this.collectWords(s,r+a,n,o,i)}}getCaseMatchBonus(e,r){if(e.length<r.length)return 0;let n=e.substring(0,r.length);return n===r?2:this.hasSameCasePattern(n,r)?1.5:1}hasSameCasePattern(e,r){if(e.length<r.length)return!1;for(let n=0;n<r.length;n++){let o=e[n],i=r[n],a=o===o.toUpperCase(),s=i===i.toUpperCase();if(a!==s)return!1}return!0}calculateScore(e){let r=Math.log(e.frequency+1)*10,n=Math.max(0,(Date.now()-e.lastSeen)/(1e3*60*60*24)),o=Math.max(0,10-n);return r+o}getStats(){let e=0,r=0,n=(o,i=0)=>{e++,r=Math.max(r,i);for(let a of o.children.values())n(a,i+1)};return n(this.root),{wordCount:this.wordCount,nodeCount:e,maxDepth:r}}clear(){this.root=this.createNode(),this.wordCount=0}getAllWords(){let e=[],r=n=>{n.isEndOfWord&&n.wordEntry&&e.push(n.wordEntry);for(let o of n.children.values())r(o)};return r(this.root),e}addWords(e,r){for(let n of e)this.addWord(n,r)}pruneByFrequency(e=2){let r=0,n=o=>{let i=[];for(let[a,s]of o.children)n(s)&&i.push(a);for(let a of i)o.children.delete(a);return o.isEndOfWord&&o.wordEntry&&o.wordEntry.frequency<e&&(o.isEndOfWord=!1,o.wordEntry=void 0,this.wordCount--,r++),o.children.size===0&&!o.isEndOfWord};return n(this.root),r}};yo();var E3t=require("obsidian");var CW=class{constructor(e,r,n,o){this.isScanning=!1;this.vault=e,this.settings=r,this.performance=n,this.tokenizer=o||new TD}async scanVault(e){let r=Date.now(),n=[],o=new Map;try{let i=this.vault.getMarkdownFiles(),a=0;for(let l of i)try{e&&e({currentFile:l.path,processedFiles:a,totalFiles:i.length,foundWords:o.size});try{let d=await this.vault.adapter.stat(l.path);if(d&&d.size>this.performance.maxFileSize){n.push(`Skipped large file: ${l.path}`);continue}}catch{}let c=await this.vault.read(l);await this.processFile(l.path,c,o),a++,a%this.performance.batchSize===0&&await new Promise(d=>setTimeout(d,1))}catch(c){let d=`Error processing file ${l.path}: ${c}`;fe(d),n.push(d)}(this.settings.includeFileNames||this.settings.includeFolderNameLine truncated
`))return!1;let o=e.split(`
`),i=o[o.length-1];if(/^#{1,6}(\s*)$/.test(i))return!1;let a=e.trim().split(/\s+/).filter(u=>u.replace(/[\p{Emoji}\p{Symbol}\p{Punctuation}]/gu,"").length>0),s=a[a.length-1]||"";return v3t(s)?!0:e.endsWith(" ")}async*handleUnifiedCompletion(){if(!this.isActive)return;let e=app.workspace.getActiveViewOfType(rFe.MarkdownView);if(!e)return;await new Promise(c=>setTimeout(c,10));let r=e.editor,n=r.getCursor(),{prefix:o,noteContext:i}=w3t(r,n),a=r.getLine(n.line).substring(n.ch)||"";if(this.lastCursorPosition){let c=Math.abs(n.line-this.lastCursorPosition.line),d=Math.abs(n.ch-this.lastCursorPosition.ch);(c>0||d>5)&&this.clearActiveRequests()}this.lastCursorPosition={line:n.line,ch:n.ch};let s=Date.now();if(s-this.lastRequestTime<this.minRequestInterval)return;let u=ue();if(this.shouldUseWordCompletion(o,u)){let c=this.getCurrentWordFromPrefix(o);if(!c||c.length<2)return;let d=`word:${c}:${o.slice(-50)}`;if(this.activeRequests.has(d))return;let f=this.wordCompletionManager.getSuggestions(c);if(f.length===0)return;let p=f.some(b=>b.word===c),m=f.some(b=>b.word.length-c.length>=2);if(p&&!m)return;let h=p?f.filter(b=>b.word!==c):f;if(h.length===0)return;try{let b=h.map(E=>E.word),g=o.slice(-1e3),y=a.slice(0,500),S,x,O;if(this.cacheEnabled&&(x=this.cache.generateWordKey(g,y,b),O=this.cache.get(x)),O)S=O;else{let E=this.client.wordcomplete(g,y,b);this.activeRequests.set(d,E),this.lastRequestTime=s,S=await E,this.cacheEnabled&&x&&this.cache.set(x,S),this.activeRequests.delete(d)}let P=S.response.selected_word;if(P&&P!==c){let E=this.generateCaseMatchedCompletion(P,c);E&&(yield{display_suggestion:E,complete_suggestion:E})}}catch(b){this.activeRequests.delete(d),fe("[Copilot Autocomplete] Error with LLM word selection, falling back to trie:",b);let g=h[0],y=this.generateCaseMatchedCompletion(g.word,c);y&&(yield{display_suggestion:y,complete_suggestion:y})}}else{if(!u.enableAutocomplete||!this.shouldContinueSuggesting(o,a))return;let c=o.slice(-this.options.maxContextLength);if(c.length<this.options.minTriggerLength)return;let d=`sentence:${c.slice(-100)}`;if(this.activeRequests.has(d))return;try{let f=u.allowAdditionalContext,p="";f&&(p=await Qle.getInstance().getRelevantNotes(e.file));let m=e.file?.basename||"",h=m?`[[${m}]]:
`),i=o[o.length-1];if(/^#{1,6}(\s*)$/.test(i))return!1;let a=e.trim().split(/\s+/).filter(u=>u.replace(/[\p{Emoji}\p{Symbol}\p{Punctuation}]/gu,"").length>0),s=a[a.length-1]||"";return O3t(s)?!0:e.endsWith(" ")}async*handleUnifiedCompletion(){if(!this.isActive)return;let e=app.workspace.getActiveViewOfType(oFe.MarkdownView);if(!e)return;await new Promise(c=>setTimeout(c,10));let r=e.editor,n=r.getCursor(),{prefix:o,noteContext:i}=P3t(r,n),a=r.getLine(n.line).substring(n.ch)||"";if(this.lastCursorPosition){let c=Math.abs(n.line-this.lastCursorPosition.line),d=Math.abs(n.ch-this.lastCursorPosition.ch);(c>0||d>5)&&this.clearActiveRequests()}this.lastCursorPosition={line:n.line,ch:n.ch};let s=Date.now();if(s-this.lastRequestTime<this.minRequestInterval)return;let u=ue();if(this.shouldUseWordCompletion(o,u)){let c=this.getCurrentWordFromPrefix(o);if(!c||c.length<2)return;let d=`word:${c}:${o.slice(-50)}`;if(this.activeRequests.has(d))return;let f=this.wordCompletionManager.getSuggestions(c);if(f.length===0)return;let p=f.some(b=>b.word===c),m=f.some(b=>b.word.length-c.length>=2);if(p&&!m)return;let h=p?f.filter(b=>b.word!==c):f;if(h.length===0)return;try{let b=h.map(E=>E.word),g=o.slice(-1e3),y=a.slice(0,500),S,x,O;if(this.cacheEnabled&&(x=this.cache.generateWordKey(g,y,b),O=this.cache.get(x)),O)S=O;else{let E=this.client.wordcomplete(g,y,b);this.activeRequests.set(d,E),this.lastRequestTime=s,S=await E,this.cacheEnabled&&x&&this.cache.set(x,S),this.activeRequests.delete(d)}let P=S.response.selected_word;if(P&&P!==c){let E=this.generateCaseMatchedCompletion(P,c);E&&(yield{display_suggestion:E,complete_suggestion:E})}}catch(b){this.activeRequests.delete(d),fe("[Copilot Autocomplete] Error with LLM word selection, falling back to trie:",b);let g=h[0],y=this.generateCaseMatchedCompletion(g.word,c);y&&(yield{display_suggestion:y,complete_suggestion:y})}}else{if(!u.enableAutocomplete||!this.shouldContinueSuggesting(o,a))return;let c=o.slice(-this.options.maxContextLength);if(c.length<this.options.minTriggerLength)return;let d=`sentence:${c.slice(-100)}`;if(this.activeRequests.has(d))return;try{let f=u.allowAdditionalContext,p="";f&&(p=await rce.getInstance().getRelevantNotes(e.file));let m=e.file?.basename||"",h=m?`[[${m}]]:
${c}`:c,b,g,y;if(this.cacheEnabled&&(g=this.cache.generateSentenceKey(h,i,p),y=this.cache.get(g)),y)b=y;else{let O=this.client.autocomplete(h,i,p);this.activeRequests.set(d,O),this.lastRequestTime=s,b=await O,this.cacheEnabled&&g&&this.cache.set(g,b),this.activeRequests.delete(d)}let S=b.response.completion,x=this.detectContext(o);S=this.postProcessor.process(c,a,S,x),yield{display_suggestion:S,complete_suggestion:S}}catch(f){this.activeRequests.delete(d),fe("[Copilot Autocomplete] Error fetching autocomplete suggestions:",f)}}}shouldUseWordCompletion(e,r){if(!r.enableWordCompletion||e.endsWith("[[")||/\[\[[^\]]*$/.test(e))return!1;let o=e.trim(),i=o[o.length-1];if(i&&/[a-zA-Z']/.test(i)){let a=this.getCurrentWordFromPrefix(e);if(a&&a.length>=2){let s=this.wordCompletionManager.getSuggestions(a);if(s.length===0)return!1;let u=s.some(c=>c.word===a),l=s.some(c=>c.word.length-a.length>=2);return!(u&&!l)}}return!1}getCurrentWordFromPrefix(e){let r=e.length;for(let o=e.length-1;o>=0;o--){let i=e[o];if(!/[a-zA-Z']/.test(i)){r=o+1;break}o===0&&(r=0)}let n=e.substring(r);return n.length>=2?n:null}generateCaseMatchedCompletion(e,r){if(e.length<=r.length)return"";let n=e.substring(r.length),o=r===r.toUpperCase(),i=r===r.toLowerCase(),a=r.length>0&&r[0]===r[0].toUpperCase()&&r.slice(1)===r.slice(1).toLowerCase();return o?n.toUpperCase():i||a?n.toLowerCase():n}detectContext(e){let r=e.split(`
`).pop()||"";if(/^\s*[-*+]\s/.test(r))return"UnorderedList";if(/^\s*\d+\.\s/.test(r))return"NumberedList";if(/^\s*[-*+]\s\[[ x]\]\s/.test(r))return"TaskList";if(e.includes("```")&&(e.split("```").length-1)%2===1)return"CodeBlock"}triggerCompletion(){this.isActive&&(this.clearActiveRequests(),this.forceFetch())}clearActiveRequests(){this.activeRequests.size>0&&this.activeRequests.clear()}getWordCompletionManager(){return this.wordCompletionManager}setCacheEnabled(e){this.cacheEnabled=e,e||this.cache.clear()}getCacheEnabled(){return this.cacheEnabled}};var tce=class t{constructor(e){this.plugin=e;let r=ue();this.cmIntegration=ece.getInstance({delay:Nh.DELAY_MS,minTriggerLength:Nh.MIN_TRIGGER_LENGTH,maxContextLength:Nh.MAX_CONTEXT_LENGTH}),this.unsubscribeSettings=xa((o,i)=>{let a=(o.enableAutocomplete||o.enableWordCompletion)&&o.isPlusUser===!0,s=(i.enableAutocomplete||i.enableWordCompletion)&&i.isPlusUser===!0;a!==s&&this.cmIntegration.setActive(s)});let n=(r.enableAutocomplete||r.enableWordCompletion)&&r.isPlusUser===!0;this.cmIntegration.setActive(n),this.registerExtension()}static getInstance(e){return t.instance||(t.instance=new t(e)),t.instance}registerExtension(){try{this.plugin.registerEditorExtension([this.cmIntegration.getExtension()])}catch(e){fe("[Copilot Autocomplete] Failed to register CodeMirror extension:",e)}}destroy(){this.unsubscribeSettings(),this.cmIntegration.setActive(!1),this.cmIntegration.destroy()}};Cl();Fd();var x3t=require("obsidian"),rce=class extends x3t.Modal{constructor(r,n){super(r);this.placeholderText="Please enter your custom ad-hoc prompt here, press enter to send.";this.onSubmit=n}onOpen(){let{contentEl:r}=this,n=createFragment(i=>{i.createEl("strong",{text:"- {} represents the selected text (not required). "}),i.createEl("br"),i.createEl("strong",{text:"- {[[Note Title]]} represents a note. "}),i.createEl("br"),i.createEl("strong",{text:"- {activeNote} represents the active note. "}),i.createEl("br"),i.createEl("strong",{text:"- {FolderPath} represents a folder of notes. "}),i.createEl("br"),i.createEl("strong",{text:"- {#tag1, #tag2} represents ALL notes with ANY of the specified tags in their property (an OR operation). "}),i.createEl("br"),i.createEl("br"),i.appendText("Tip: turn on debug mode to show the processed prompt in the chat window."),i.createEl("br"),i.createEl("br")});r.appendChild(n);let o=r.createEl("textarea",{attr:{placeholder:this.placeholderText}});o.style.width="100%",o.style.height="100px",o.style.padding="10px",o.style.resize="vertical",o.addEventListener("input",i=>{this.result=i.target.value}),o.addEventListener("keydown",i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),this.close(),this.onSubmit(this.result))})}onClose(){let{contentEl:r}=this;r.empty()}};L8();var ZI=require("obsidian"),nce=class extends ZI.Modal{constructor(e,r){super(e),this.plugin=r}onOpen(){let{contentEl:e}=this;e.empty(),e.createEl("h2",{text:"Debug: Search OramaDB"});let r=e.createEl("p");r.innerHTML='Enter a JSON search params object. Example:<br><pre>{<br> "term": "#tag",<br> "mode": "hybrid",<br> "limit": 10,<br> "includeVectors": true<br>}</pre>',this.searchInput=e.createEl("textarea",{attr:{placeholder:"Enter search params JSON...",rows:"10",style:"width: 100%; min-height: 200px; margin: 10px 0; padding: 10px; font-family: monospace;"}}),e.createEl("div",{cls:"search-button-container"}).createEl("button",{text:"Search",cls:"mod-cta"}).addEventListener("click",async()=>{try{let i=JSON.parse(this.searchInput.value);i.vector?.value&&!Array.isArray(i.vector.value)&&(i.vector.value=Object.values(i.vector.value));let a=await this.plugin.vectorStoreManager.getDb();if(!a){new ZI.Notice("Database not found");return}let s=await Xc(a,i),u=["## Search Parameters","```json",JSON.stringify(i,null,2),"```","","## Results",`Total hits: ${s.hits.length}`,"","### Hits","```json",JSON.stringify(s.hits,null,2),"```"].join(`
`),l="OramaDB-Debug-Search.md",c=this.app.vault.getAbstractFileByPath(l);c instanceof ZI.TFile?await this.app.vault.modify(c,u):await this.app.vault.create(l,u);let d=this.app.vault.getAbstractFileByPath(l);d instanceof ZI.TFile&&(await this.app.workspace.getLeaf().openFile(d),this.close())}catch(i){console.error("Error in debug search:",i),new ZI.Notice("Error executing search. Check console for details.")}})}onClose(){let{contentEl:e}=this;e.empty()}};Cn();var CW=require("obsidian"),oce=class extends CW.Modal{constructor(e,r){super(e),this.plugin=r}onOpen(){let{contentEl:e}=this;e.empty(),e.createEl("h2",{text:"Inspect Copilot Index by Note Paths"}),this.searchInput=e.createEl("textarea",{attr:{placeholder:`Enter note paths as markdown list:
`).pop()||"";if(/^\s*[-*+]\s/.test(r))return"UnorderedList";if(/^\s*\d+\.\s/.test(r))return"NumberedList";if(/^\s*[-*+]\s\[[ x]\]\s/.test(r))return"TaskList";if(e.includes("```")&&(e.split("```").length-1)%2===1)return"CodeBlock"}triggerCompletion(){this.isActive&&(this.clearActiveRequests(),this.forceFetch())}clearActiveRequests(){this.activeRequests.size>0&&this.activeRequests.clear()}getWordCompletionManager(){return this.wordCompletionManager}setCacheEnabled(e){this.cacheEnabled=e,e||this.cache.clear()}getCacheEnabled(){return this.cacheEnabled}};var oce=class t{constructor(e){this.plugin=e;let r=ue();this.cmIntegration=nce.getInstance({delay:Nh.DELAY_MS,minTriggerLength:Nh.MIN_TRIGGER_LENGTH,maxContextLength:Nh.MAX_CONTEXT_LENGTH}),this.unsubscribeSettings=xa((o,i)=>{let a=(o.enableAutocomplete||o.enableWordCompletion)&&o.isPlusUser===!0,s=(i.enableAutocomplete||i.enableWordCompletion)&&i.isPlusUser===!0;a!==s&&this.cmIntegration.setActive(s)});let n=(r.enableAutocomplete||r.enableWordCompletion)&&r.isPlusUser===!0;this.cmIntegration.setActive(n),this.registerExtension()}static getInstance(e){return t.instance||(t.instance=new t(e)),t.instance}registerExtension(){try{this.plugin.registerEditorExtension([this.cmIntegration.getExtension()])}catch(e){fe("[Copilot Autocomplete] Failed to register CodeMirror extension:",e)}}destroy(){this.unsubscribeSettings(),this.cmIntegration.setActive(!1),this.cmIntegration.destroy()}};Cl();Fd();var T3t=require("obsidian"),ice=class extends T3t.Modal{constructor(r,n){super(r);this.placeholderText="Please enter your custom ad-hoc prompt here, press enter to send.";this.onSubmit=n}onOpen(){let{contentEl:r}=this,n=createFragment(i=>{i.createEl("strong",{text:"- {} represents the selected text (not required). "}),i.createEl("br"),i.createEl("strong",{text:"- {[[Note Title]]} represents a note. "}),i.createEl("br"),i.createEl("strong",{text:"- {activeNote} represents the active note. "}),i.createEl("br"),i.createEl("strong",{text:"- {FolderPath} represents a folder of notes. "}),i.createEl("br"),i.createEl("strong",{text:"- {#tag1, #tag2} represents ALL notes with ANY of the specified tags in their property (an OR operation). "}),i.createEl("br"),i.createEl("br"),i.appendText("Tip: turn on debug mode to show the processed prompt in the chat window."),i.createEl("br"),i.createEl("br")});r.appendChild(n);let o=r.createEl("textarea",{attr:{placeholder:this.placeholderText}});o.style.width="100%",o.style.height="100px",o.style.padding="10px",o.style.resize="vertical",o.addEventListener("input",i=>{this.result=i.target.value}),o.addEventListener("keydown",i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),this.close(),this.onSubmit(this.result))})}onClose(){let{contentEl:r}=this;r.empty()}};F8();var ZI=require("obsidian"),ace=class extends ZI.Modal{constructor(e,r){super(e),this.plugin=r}onOpen(){let{contentEl:e}=this;e.empty(),e.createEl("h2",{text:"Debug: Search OramaDB"});let r=e.createEl("p");r.innerHTML='Enter a JSON search params object. Example:<br><pre>{<br> "term": "#tag",<br> "mode": "hybrid",<br> "limit": 10,<br> "includeVectors": true<br>}</pre>',this.searchInput=e.createEl("textarea",{attr:{placeholder:"Enter search params JSON...",rows:"10",style:"width: 100%; min-height: 200px; margin: 10px 0; padding: 10px; font-family: monospace;"}}),e.createEl("div",{cls:"search-button-container"}).createEl("button",{text:"Search",cls:"mod-cta"}).addEventListener("click",async()=>{try{let i=JSON.parse(this.searchInput.value);i.vector?.value&&!Array.isArray(i.vector.value)&&(i.vector.value=Object.values(i.vector.value));let a=await this.plugin.vectorStoreManager.getDb();if(!a){new ZI.Notice("Database not found");return}let s=await Xc(a,i),u=["## Search Parameters","```json",JSON.stringify(i,null,2),"```","","## Results",`Total hits: ${s.hits.length}`,"","### Hits","```json",JSON.stringify(s.hits,null,2),"```"].join(`
`),l="OramaDB-Debug-Search.md",c=this.app.vault.getAbstractFileByPath(l);c instanceof ZI.TFile?await this.app.vault.modify(c,u):await this.app.vault.create(l,u);let d=this.app.vault.getAbstractFileByPath(l);d instanceof ZI.TFile&&(await this.app.workspace.getLeaf().openFile(d),this.close())}catch(i){console.error("Error in debug search:",i),new ZI.Notice("Error executing search. Check console for details.")}})}onClose(){let{contentEl:e}=this;e.empty()}};yn();var OW=require("obsidian"),sce=class extends OW.Modal{constructor(e,r){super(e),this.plugin=r}onOpen(){let{contentEl:e}=this;e.empty(),e.createEl("h2",{text:"Inspect Copilot Index by Note Paths"}),this.searchInput=e.createEl("textarea",{attr:{placeholder:`Enter note paths as markdown list:
- [[Note 1]]
- [[Note 2]]`,rows:"10",style:"width: 100%; min-height: 200px; margin: 10px 0; padding: 10px; font-family: monospace;"}}),e.createEl("div",{cls:"search-button-container"}).createEl("button",{text:"Show Index Data",cls:"mod-cta"}).addEventListener("click",async()=>{let o=this.searchInput.value,i=NC(o,this.app.vault).map(a=>a.path);if(i.length===0){new CW.Notice("No valid note paths found. Use format: - [[Note Name]]");return}try{let s=await(await this.plugin.vectorStoreManager.getDbOps()).getDocsJsonByPaths(i),u="CopilotDB-Search-Results.md",l=["## Searched Paths",...i.map(f=>`- [[${f}]]`),"","## Index Data","```json",JSON.stringify(s,null,2),"```"].join(`
`),c=this.app.vault.getAbstractFileByPath(u);c?await this.app.vault.modify(c,l):await this.app.vault.create(u,l);let d=this.app.vault.getAbstractFileByPath(u);d&&await this.app.workspace.getLeaf().openFile(d),this.close()}catch(a){console.error("Error searching DB:",a),new CW.Notice("Error searching database. Check console for details.")}})}onClose(){let{contentEl:e}=this;e.empty()}};var OW=require("obsidian"),ice=class extends OW.Modal{constructor(r,n){super(r);this.filePaths="";this.onSubmit=n}onOpen(){let{contentEl:r}=this;r.createEl("h2",{text:"Remove Files from Copilot Index"});let n=r.createDiv({cls:"remove-files-container"});new OW.Setting(n).setName("File paths").setDesc("Paste the markdown list of file paths to remove from the index. You can get the list by running the command `List all indexed files`.").setClass("remove-files-setting").addTextArea(o=>o.setPlaceholder(`- [[path/to/file1.md]]
- [[path/to/file2.md]]`).setValue(this.filePaths).onChange(i=>{this.filePaths=i})),new OW.Setting(n).addButton(o=>o.setButtonText("Remove").setCta().onClick(()=>{let i=this.filePaths.split(`
- [[Note 2]]`,rows:"10",style:"width: 100%; min-height: 200px; margin: 10px 0; padding: 10px; font-family: monospace;"}}),e.createEl("div",{cls:"search-button-container"}).createEl("button",{text:"Show Index Data",cls:"mod-cta"}).addEventListener("click",async()=>{let o=this.searchInput.value,i=DC(o,this.app.vault).map(a=>a.path);if(i.length===0){new OW.Notice("No valid note paths found. Use format: - [[Note Name]]");return}try{let s=await(await this.plugin.vectorStoreManager.getDbOps()).getDocsJsonByPaths(i),u="CopilotDB-Search-Results.md",l=["## Searched Paths",...i.map(f=>`- [[${f}]]`),"","## Index Data","```json",JSON.stringify(s,null,2),"```"].join(`
`),c=this.app.vault.getAbstractFileByPath(u);c?await this.app.vault.modify(c,l):await this.app.vault.create(u,l);let d=this.app.vault.getAbstractFileByPath(u);d&&await this.app.workspace.getLeaf().openFile(d),this.close()}catch(a){console.error("Error searching DB:",a),new OW.Notice("Error searching database. Check console for details.")}})}onClose(){let{contentEl:e}=this;e.empty()}};var PW=require("obsidian"),uce=class extends PW.Modal{constructor(r,n){super(r);this.filePaths="";this.onSubmit=n}onOpen(){let{contentEl:r}=this;r.createEl("h2",{text:"Remove Files from Copilot Index"});let n=r.createDiv({cls:"remove-files-container"});new PW.Setting(n).setName("File paths").setDesc("Paste the markdown list of file paths to remove from the index. You can get the list by running the command `List all indexed files`.").setClass("remove-files-setting").addTextArea(o=>o.setPlaceholder(`- [[path/to/file1.md]]
- [[path/to/file2.md]]`).setValue(this.filePaths).onChange(i=>{this.filePaths=i})),new PW.Setting(n).addButton(o=>o.setButtonText("Remove").setCta().onClick(()=>{let i=this.filePaths.split(`
`).map(a=>{let s=a.match(/\[\[(.*?)\]\]/);return s?s[1].trim():""}).filter(a=>a.length>0);this.onSubmit(i),this.close()})),r.createEl("style",{text:`
.remove-files-container {
width: 100%;
@@ -806,8 +806,8 @@ ${c}`:c,b,g,y;if(this.cacheEnabled&&(g=this.cache.generateSentenceKey(h,i,p),y=t
.remove-files-setting textarea::placeholder {
opacity: 0.5;
}
`})}onClose(){let{contentEl:r}=this;r.empty()}};_g();nr();var Ji=require("obsidian");l2();$r();function df(t,e,r){t.addCommand({id:e,name:ige[e],callback:r})}function C3t(t,e,r){t.addCommand({id:e,name:ige[e],editorCallback:r})}function nFe(t,e,r){C3t(t,Br.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 Ji.Notice(`Selected text contains ${i} words and ${a} tokens.`)}),df(t,Br.COUNT_TOTAL_VAULT_TOKENS,async()=>{try{let n=await JRt(t.app),o=await t.projectManager.getCurrentChainManager().chatModelManager.countTokens(n);new Ji.Notice(`Total tokens in your vault: ${o}`)}catch(n){console.error("Error counting tokens: ",n),new Ji.Notice("An error occurred while counting tokens.")}}),df(t,Br.TOGGLE_COPILOT_CHAT_WINDOW,()=>{t.toggleView()}),df(t,Br.OPEN_COPILOT_CHAT_WINDOW,()=>{t.activateView()}),df(t,Br.NEW_CHAT,()=>{t.newChat()}),df(t,Br.APPLY_ADHOC_PROMPT,async()=>{new rce(t.app,async o=>{try{t.processCustomPrompt(Br.APPLY_ADHOC_PROMPT,o)}catch(i){console.error(i),new Ji.Notice("An error occurred.")}}).open()}),df(t,Br.CLEAR_LOCAL_COPILOT_INDEX,async()=>{await t.vectorStoreManager.clearIndex()}),df(t,Br.GARBAGE_COLLECT_COPILOT_INDEX,async()=>{try{let n=await t.vectorStoreManager.garbageCollectVectorStore();new Ji.Notice(`${n} documents removed from Copilot index.`)}catch(n){console.error("Error garbage collecting the Copilot index:",n),new Ji.Notice("An error occurred while garbage collecting the Copilot index.")}}),df(t,Br.INDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let n=await t.vectorStoreManager.indexVaultToVectorStore();new Ji.Notice(`${n} vault files indexed to Copilot index.`)}catch(n){console.error("Error indexing vault to Copilot index:",n),new Ji.Notice("An error occurred while indexing vault to Copilot index.")}}),df(t,Br.FORCE_REINDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let n=await t.vectorStoreManager.indexVaultToVectorStore(!0);new Ji.Notice(`${n} vault files re-indexed to Copilot index.`)}catch(n){console.error("Error re-indexing vault to Copilot index:",n),new Ji.Notice("An error occurred while re-indexing vault to Copilot index.")}}),df(t,Br.LOAD_COPILOT_CHAT_CONVERSATION,()=>{t.loadCopilotChatHistory()}),df(t,Br.LIST_INDEXED_FILES,async()=>{try{let n=await t.vectorStoreManager.getIndexedFiles(),o=new Set(n),i=t.app.vault.getMarkdownFiles(),a=new Set,s=new Set,u=new Set,l=await t.vectorStoreManager.getDbOps();for(let h of i){let b=await t.app.vault.cachedRead(h);!b||b.trim().length===0?a.add(h.path):o.has(h.path)?await l.hasEmbeddings(h.path)||u.add(h.path):s.add(h.path)}if(n.length===0&&a.size===0&&s.size===0){new Ji.Notice("No files found to list.");return}let c=["# Copilot Files Status",`- Indexed files: ${n.length}`,` - Files missing embeddings: ${u.size}`,`- Unindexed files: ${s.size}`,`- Empty files: ${a.size}`,"","## Indexed Files",...n.map(h=>{let b=u.has(h);return`- [[${h}]]${b?" *(embedding missing)*":""}`}),"","## Unindexed Files",...s.size>0?Array.from(s).sort().map(h=>`- [[${h}]]`):["No unindexed files found."],"","## Empty Files",...a.size>0?Array.from(a).sort().map(h=>`- [[${h}]]`):["No empty files found."]].join(`
`),f=`${`Copilot-Indexed-Files-${new Date().toLocaleDateString().replace(/\//g,"-")}.md`}`,p=t.app.vault.getAbstractFileByPath(f);p instanceof Ji.TFile?await t.app.vault.modify(p,c):await t.app.vault.create(f,c);let m=t.app.vault.getAbstractFileByPath(f);m instanceof Ji.TFile&&(await t.app.workspace.getLeaf().openFile(m),new Ji.Notice(`Listed ${n.length} indexed files`))}catch(n){console.error("Error listing indexed files:",n),new Ji.Notice("Failed to list indexed files.")}}),r.debug&&(df(t,Br.INSPECT_COPILOT_INDEX_BY_NOTE_PATHS,()=>{new oce(t.app,t).open()}),df(t,Br.SEARCH_ORAMA_DB,()=>{new nce(t.app,t).open()}),df(t,Br.REMOVE_FILES_FROM_COPILOT_INDEX,async()=>{new ice(t.app,async n=>{let o=await t.vectorStoreManager.getDbOps();try{for(let i of n)await o.removeDocs(i);await o.saveDB(),new Ji.Notice(`Successfully removed ${n.length} files from the index.`)}catch(i){console.error("Error removing files from index:",i),new Ji.Notice("An error occurred while removing files from the index.")}}).open()})),df(t,Br.CLEAR_COPILOT_CACHE,async()=>{try{await t.fileParserManager.clearPDFCache(),await tb.getInstance().clearAllCache(),await xq.getInstance().clear();let{AutocompleteCache:o}=await Promise.resolve().then(()=>(WLe(),d3t));o.getInstance().clear(),new Ji.Notice("All Copilot caches cleared successfully")}catch(n){console.error("Error clearing Copilot caches:",n),new Ji.Notice("Failed to clear Copilot caches")}}),df(t,Br.TOGGLE_AUTOCOMPLETE,()=>{let o=!ue().enableAutocomplete;dt("enableAutocomplete",o),new Ji.Notice(`Copilot autocomplete ${o?"enabled":"disabled"}`)}),C3t(t,Br.ADD_SELECTION_TO_CHAT_CONTEXT,async n=>{let o=Fh();if(o!=="copilot_plus"&&o!=="project"){new Ji.Notice("Selected text context is only available in Copilot Plus and Project modes");return}let i=n.getSelection();if(!i){new Ji.Notice("No text selected");return}let a=t.app.workspace.getActiveFile();if(!a){new Ji.Notice("No active file");return}let s=n.listSelections()[0];if(!s){new Ji.Notice("Could not determine selection range");return}let u=s.anchor.line+1,l=s.head.line+1,c={id:yC(),content:i,noteTitle:a.basename,notePath:a.path,startLine:Math.min(u,l),endLine:Math.max(u,l)};e8e(c),t.activateView()})}Cl();Fd();var oFe="{copilot-selection}";var XI={title:"",content:"",showInContextMenu:!1,showInSlashMenu:!1,order:Number.MAX_SAFE_INTEGER,modelKey:"",lastUsedMs:0},AD="copilot-command-context-menu-enabled",ID="copilot-command-slash-enabled",MD="copilot-command-context-menu-order",RD="copilot-command-model-key",jD="copilot-command-last-used",O3t=[{title:"Fix grammar and spelling",content:"Fix the grammar and spelling of {}. Preserve all formatting, line breaks, and special characters. Do not add or remove any content. Return only the corrected text.",showInContextMenu:!0,showInSlashMenu:!0,order:1e3,modelKey:"",lastUsedMs:0},{title:"Translate to Chinese",content:`Translate {} into Chinese:
`})}onClose(){let{contentEl:r}=this;r.empty()}};_g();nr();var Ji=require("obsidian");c2();$r();function df(t,e,r){t.addCommand({id:e,name:uge[e],callback:r})}function A3t(t,e,r){t.addCommand({id:e,name:uge[e],editorCallback:r})}function iFe(t,e,r){A3t(t,Br.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 Ji.Notice(`Selected text contains ${i} words and ${a} tokens.`)}),df(t,Br.COUNT_TOTAL_VAULT_TOKENS,async()=>{try{let n=await e1t(t.app),o=await t.projectManager.getCurrentChainManager().chatModelManager.countTokens(n);new Ji.Notice(`Total tokens in your vault: ${o}`)}catch(n){console.error("Error counting tokens: ",n),new Ji.Notice("An error occurred while counting tokens.")}}),df(t,Br.TOGGLE_COPILOT_CHAT_WINDOW,()=>{t.toggleView()}),df(t,Br.OPEN_COPILOT_CHAT_WINDOW,()=>{t.activateView()}),df(t,Br.NEW_CHAT,()=>{t.newChat()}),df(t,Br.APPLY_ADHOC_PROMPT,async()=>{new ice(t.app,async o=>{try{t.processCustomPrompt(Br.APPLY_ADHOC_PROMPT,o)}catch(i){console.error(i),new Ji.Notice("An error occurred.")}}).open()}),df(t,Br.CLEAR_LOCAL_COPILOT_INDEX,async()=>{await t.vectorStoreManager.clearIndex()}),df(t,Br.GARBAGE_COLLECT_COPILOT_INDEX,async()=>{try{let n=await t.vectorStoreManager.garbageCollectVectorStore();new Ji.Notice(`${n} documents removed from Copilot index.`)}catch(n){console.error("Error garbage collecting the Copilot index:",n),new Ji.Notice("An error occurred while garbage collecting the Copilot index.")}}),df(t,Br.INDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let n=await t.vectorStoreManager.indexVaultToVectorStore();new Ji.Notice(`${n} vault files indexed to Copilot index.`)}catch(n){console.error("Error indexing vault to Copilot index:",n),new Ji.Notice("An error occurred while indexing vault to Copilot index.")}}),df(t,Br.FORCE_REINDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let n=await t.vectorStoreManager.indexVaultToVectorStore(!0);new Ji.Notice(`${n} vault files re-indexed to Copilot index.`)}catch(n){console.error("Error re-indexing vault to Copilot index:",n),new Ji.Notice("An error occurred while re-indexing vault to Copilot index.")}}),df(t,Br.LOAD_COPILOT_CHAT_CONVERSATION,()=>{t.loadCopilotChatHistory()}),df(t,Br.LIST_INDEXED_FILES,async()=>{try{let n=await t.vectorStoreManager.getIndexedFiles(),o=new Set(n),i=t.app.vault.getMarkdownFiles(),a=new Set,s=new Set,u=new Set,l=await t.vectorStoreManager.getDbOps();for(let h of i){let b=await t.app.vault.cachedRead(h);!b||b.trim().length===0?a.add(h.path):o.has(h.path)?await l.hasEmbeddings(h.path)||u.add(h.path):s.add(h.path)}if(n.length===0&&a.size===0&&s.size===0){new Ji.Notice("No files found to list.");return}let c=["# Copilot Files Status",`- Indexed files: ${n.length}`,` - Files missing embeddings: ${u.size}`,`- Unindexed files: ${s.size}`,`- Empty files: ${a.size}`,"","## Indexed Files",...n.map(h=>{let b=u.has(h);return`- [[${h}]]${b?" *(embedding missing)*":""}`}),"","## Unindexed Files",...s.size>0?Array.from(s).sort().map(h=>`- [[${h}]]`):["No unindexed files found."],"","## Empty Files",...a.size>0?Array.from(a).sort().map(h=>`- [[${h}]]`):["No empty files found."]].join(`
`),f=`${`Copilot-Indexed-Files-${new Date().toLocaleDateString().replace(/\//g,"-")}.md`}`,p=t.app.vault.getAbstractFileByPath(f);p instanceof Ji.TFile?await t.app.vault.modify(p,c):await t.app.vault.create(f,c);let m=t.app.vault.getAbstractFileByPath(f);m instanceof Ji.TFile&&(await t.app.workspace.getLeaf().openFile(m),new Ji.Notice(`Listed ${n.length} indexed files`))}catch(n){console.error("Error listing indexed files:",n),new Ji.Notice("Failed to list indexed files.")}}),r.debug&&(df(t,Br.INSPECT_COPILOT_INDEX_BY_NOTE_PATHS,()=>{new sce(t.app,t).open()}),df(t,Br.SEARCH_ORAMA_DB,()=>{new ace(t.app,t).open()}),df(t,Br.REMOVE_FILES_FROM_COPILOT_INDEX,async()=>{new uce(t.app,async n=>{let o=await t.vectorStoreManager.getDbOps();try{for(let i of n)await o.removeDocs(i);await o.saveDB(),new Ji.Notice(`Successfully removed ${n.length} files from the index.`)}catch(i){console.error("Error removing files from index:",i),new Ji.Notice("An error occurred while removing files from the index.")}}).open()})),df(t,Br.CLEAR_COPILOT_CACHE,async()=>{try{await t.fileParserManager.clearPDFCache(),await tb.getInstance().clearAllCache(),await Cq.getInstance().clear();let{AutocompleteCache:o}=await Promise.resolve().then(()=>(GLe(),g3t));o.getInstance().clear(),new Ji.Notice("All Copilot caches cleared successfully")}catch(n){console.error("Error clearing Copilot caches:",n),new Ji.Notice("Failed to clear Copilot caches")}}),df(t,Br.TOGGLE_AUTOCOMPLETE,()=>{let o=!ue().enableAutocomplete;dt("enableAutocomplete",o),new Ji.Notice(`Copilot autocomplete ${o?"enabled":"disabled"}`)}),A3t(t,Br.ADD_SELECTION_TO_CHAT_CONTEXT,async n=>{let o=Fh();if(o!=="copilot_plus"&&o!=="project"){new Ji.Notice("Selected text context is only available in Copilot Plus and Project modes");return}let i=n.getSelection();if(!i){new Ji.Notice("No text selected");return}let a=t.app.workspace.getActiveFile();if(!a){new Ji.Notice("No active file");return}let s=n.listSelections()[0];if(!s){new Ji.Notice("Could not determine selection range");return}let u=s.anchor.line+1,l=s.head.line+1,c={id:bC(),content:i,noteTitle:a.basename,notePath:a.path,startLine:Math.min(u,l),endLine:Math.max(u,l)};o8e(c),t.activateView()})}Cl();Fd();var aFe="{copilot-selection}";var XI={title:"",content:"",showInContextMenu:!1,showInSlashMenu:!1,order:Number.MAX_SAFE_INTEGER,modelKey:"",lastUsedMs:0},ID="copilot-command-context-menu-enabled",MD="copilot-command-slash-enabled",RD="copilot-command-context-menu-order",jD="copilot-command-model-key",ND="copilot-command-last-used",I3t=[{title:"Fix grammar and spelling",content:"Fix the grammar and spelling of {}. Preserve all formatting, line breaks, and special characters. Do not add or remove any content. Return only the corrected text.",showInContextMenu:!0,showInSlashMenu:!0,order:1e3,modelKey:"",lastUsedMs:0},{title:"Translate to Chinese",content:`Translate {} into Chinese:
1. Preserve the meaning and tone
2. Maintain appropriate cultural context
3. Keep formatting and structure
@@ -842,23 +842,23 @@ ${c}`:c,b,g,y;if(this.cacheEnabled&&(g=this.cache.generateSentenceKey(h,i,p),y=t
"
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 KU=require("obsidian");nr();s4();s4();var eE=lF(),tE=Ih([]);function ace(t){let e=eE.get(tE);e.some(r=>r.title===t)||eE.set(tE,[...e,{...XI,title:t}])}function PW(t){let e=eE.get(tE);eE.set(tE,e.filter(r=>r.title!==t))}function EW(t,e){let r=eE.get(tE),n;(e?r.findIndex(i=>i.title===e):-1)!==-1?n=r.map(i=>i.title===e?t:i):n=[...r,t],eE.set(tE,n)}function sce(t){eE.set(tE,t)}function P3t(){return i4(tE,{store:eE})}function Gx(){return eE.get(tE)}d4();Cn();$r();function GU(t,e,r){let n=t.trim();return r&&n===r?null:/[#<>:"/\\|?*[\]^\x00-\x1F]/g.test(n)?'Command name contains invalid characters. Avoid using: < > : " / \\ | ? * [ ] ^':e.some(i=>i.title.toLowerCase()===n.toLowerCase())?"A command with this name already exists":null}function JU(t){return encodeURIComponent(t.toLowerCase())}function QI(){return(0,KU.normalizePath)(ue().customPromptsFolder)}function ND(t){return`${QI()}/${t}.md`}function YU(t){if(!(t instanceof KU.TFile)||t.extension!=="md")return!1;let e=QI();return!(!t.path.startsWith(e+"/")||t.path.slice(e.length+1).includes("/"))}function o0n(t){if(t.startsWith("---")){let e=t.indexOf("---",3);if(e!==-1)return t.slice(e+3).trimStart()}return t}async function TW(t){let e=await app.vault.read(t),r=o0n(e),n=app.metadataCache.getFileCache(t),o=n?.frontmatter?.[AD]??XI.showInContextMenu,i=n?.frontmatter?.[ID]??XI.showInSlashMenu,a=n?.frontmatter?.[jD]??XI.lastUsedMs,s=n?.frontmatter?.[MD]??XI.order,u=n?.frontmatter?.[RD]??XI.modelKey;return{title:t.basename,modelKey:u,content:r,showInContextMenu:o,showInSlashMenu:i,order:s,lastUsedMs:a}}async function uce(){let t=app.vault.getFiles().filter(r=>YU(r)),e=await Promise.all(t.map(TW));return sce(e),e}function AW(t){return[...t].sort((e,r)=>e.order===r.order?e.title.localeCompare(r.title):e.order-r.order)}function i0n(t){return[...t].sort((e,r)=>e.lastUsedMs===r.lastUsedMs?e.title.localeCompare(r.title):r.lastUsedMs-e.lastUsedMs)}function a0n(t){return[...t].sort((e,r)=>e.title.localeCompare(r.title))}function E3t(t){switch(ue().promptSortStrategy){case"timestamp":return i0n(t);case"alphabetical":return a0n(t);case"manual":return AW(t);default:return t}}async function iFe(t,e,r=!1){let o=(await lce(t,e,app.vault,app.workspace.getActiveFile())).processedPrompt;if(o.includes("{selectedText}")||r)return o;let i=o.indexOf(oFe);return i===-1&&e.trim()?o+`
Return only the formatted thread.`,showInContextMenu:!1,showInSlashMenu:!1,order:1120,modelKey:"",lastUsedMs:0}];var GU=require("obsidian");nr();u4();u4();var eE=cF(),tE=Ih([]);function lce(t){let e=eE.get(tE);e.some(r=>r.title===t)||eE.set(tE,[...e,{...XI,title:t}])}function EW(t){let e=eE.get(tE);eE.set(tE,e.filter(r=>r.title!==t))}function TW(t,e){let r=eE.get(tE),n;(e?r.findIndex(i=>i.title===e):-1)!==-1?n=r.map(i=>i.title===e?t:i):n=[...r,t],eE.set(tE,n)}function cce(t){eE.set(tE,t)}function M3t(){return a4(tE,{store:eE})}function Jx(){return eE.get(tE)}f4();yn();$r();function JU(t,e,r){let n=t.trim();return r&&n===r?null:/[#<>:"/\\|?*[\]^\x00-\x1F]/g.test(n)?'Command name contains invalid characters. Avoid using: < > : " / \\ | ? * [ ] ^':e.some(i=>i.title.toLowerCase()===n.toLowerCase())?"A command with this name already exists":null}function YU(t){return encodeURIComponent(t.toLowerCase())}function QI(){return(0,GU.normalizePath)(ue().customPromptsFolder)}function DD(t){return`${QI()}/${t}.md`}function ZU(t){if(!(t instanceof GU.TFile)||t.extension!=="md")return!1;let e=QI();return!(!t.path.startsWith(e+"/")||t.path.slice(e.length+1).includes("/"))}function l0n(t){if(t.startsWith("---")){let e=t.indexOf("---",3);if(e!==-1)return t.slice(e+3).trimStart()}return t}async function AW(t){let e=await app.vault.read(t),r=l0n(e),n=app.metadataCache.getFileCache(t),o=n?.frontmatter?.[ID]??XI.showInContextMenu,i=n?.frontmatter?.[MD]??XI.showInSlashMenu,a=n?.frontmatter?.[ND]??XI.lastUsedMs,s=n?.frontmatter?.[RD]??XI.order,u=n?.frontmatter?.[jD]??XI.modelKey;return{title:t.basename,modelKey:u,content:r,showInContextMenu:o,showInSlashMenu:i,order:s,lastUsedMs:a}}async function dce(){let t=app.vault.getFiles().filter(r=>ZU(r)),e=await Promise.all(t.map(AW));return cce(e),e}function IW(t){return[...t].sort((e,r)=>e.order===r.order?e.title.localeCompare(r.title):e.order-r.order)}function c0n(t){return[...t].sort((e,r)=>e.lastUsedMs===r.lastUsedMs?e.title.localeCompare(r.title):r.lastUsedMs-e.lastUsedMs)}function d0n(t){return[...t].sort((e,r)=>e.title.localeCompare(r.title))}function R3t(t){switch(ue().promptSortStrategy){case"timestamp":return c0n(t);case"alphabetical":return d0n(t);case"manual":return IW(t);default:return t}}async function sFe(t,e,r=!1){let o=(await fce(t,e,app.vault,app.workspace.getActiveFile())).processedPrompt;if(o.includes("{selectedText}")||r)return o;let i=o.indexOf(aFe);return i===-1&&e.trim()?o+`
<selectedText>`+e+"</selectedText>":o.slice(0,i)+e+o.slice(i+oFe.length)}var s0n=/\{(?!copilot-selection\})([^}]+)\}/g;async function u0n(t,e,r){let n=new Map,o=new Set,i;for(;(i=s0n.exec(t))!==null;){let a=i[1].trim(),s={content:"",files:[]};if(a.toLowerCase()==="activenote")if(r){let u=await pF(r,e);u&&(s.content=`## ${QG(r)}
<selectedText>`+e+"</selectedText>":o.slice(0,i)+e+o.slice(i+aFe.length)}var f0n=/\{(?!copilot-selection\})([^}]+)\}/g;async function p0n(t,e,r){let n=new Map,o=new Set,i;for(;(i=f0n.exec(t))!==null;){let a=i[1].trim(),s={content:"",files:[]};if(a.toLowerCase()==="activenote")if(r){let u=await mF(r,e);u&&(s.content=`## ${eJ(r)}
${u}`,s.files.push(r))}else new KU.Notice("No active note found.");else if(a.startsWith("#")){let u=a.slice(1).split(",").map(d=>d.trim()),l=await dVe(e,u),c=[];for(let d of l){let f=await pF(d,e);f&&(c.push(`## ${QG(d)}
${u}`,s.files.push(r))}else new GU.Notice("No active note found.");else if(a.startsWith("#")){let u=a.slice(1).split(",").map(d=>d.trim()),l=await pVe(e,u),c=[];for(let d of l){let f=await mF(d,e);f&&(c.push(`## ${eJ(d)}
${f}`),s.files.push(d))}s.content=c.join(`
`)}else{let u=mVe(a),l=await Jhe(e,u),c=[];for(let d of l){let f=await pF(d,e);f&&(c.push(`## ${QG(d)}
`)}else{let u=gVe(a),l=await Xhe(e,u),c=[];for(let d of l){let f=await mF(d,e);f&&(c.push(`## ${eJ(d)}
${f}`),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 lce(t,e,r,n){let o=ue(),i=new Set;if(!o.enableCustomPromptTemplating)return t.includes("{}")&&!e&&n&&i.add(n),{processedPrompt:t+`
`)}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 fce(t,e,r,n){let o=ue(),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 u0n(t,r,n);s.forEach(f=>i.add(f));let u=t,l="",c=null;u.includes("{}")&&(u=u.replace(/\{\}/g,"{selectedText}"),e?l+=`selectedText:
`,includedFiles:Array.from(i)};let{variablesMap:a,includedFiles:s}=await p0n(t,r,n);s.forEach(f=>i.add(f));let u=t,l="",c=null;u.includes("{}")&&(u=u.replace(/\{\}/g,"{selectedText}"),e?l+=`selectedText:
${e}`:n?(c=await pF(n,r),l+=`selectedText (entire active note):
${e}`:n?(c=await mF(n,r),l+=`selectedText (entire active note):
${c}`,i.add(n)):l+=`selectedText:
@@ -868,23 +868,23 @@ ${f}:
${p}`:l+=`${f}:
${p}`);let d=NC(u,r);for(let f of d)if(!i.has(f)){let p=await pF(f,r);if(p){let m=`<${f4}>
${p}`);let d=DC(u,r);for(let f of d)if(!i.has(f)){let p=await mF(f,r);if(p){let m=`<${p4}>
Title: [[${f.basename}]]
Path: ${f.path}
${p}
</${f4}>`;l&&(l+=`
</${p4}>`;l&&(l+=`
`),l+=`${m}`,i.add(f)}}return{processedPrompt:l?`${u}
${l}`:`${u}
`,includedFiles:Array.from(i)}}Cl();Fd();ti();var T3t=require("obsidian"),DD=F(X()),A3t=F(Dc());function l0n({content:t,onConfirm:e,onCancel:r,confirmButtonText:n,cancelButtonText:o}){return DD.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-5"},DD.default.createElement("div",{className:"tw-whitespace-pre-wrap"},t),DD.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},o&&DD.default.createElement(ge,{variant:"secondary",onClick:r},o),n&&DD.default.createElement(ge,{variant:"default",onClick:e},n)))}var sd=class extends T3t.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,A3t.createRoot)(r);let n=()=>{this.onConfirm(),this.close()},o=()=>{this.close()};this.root.render(DD.default.createElement(l0n,{content:this.content,onConfirm:n,onCancel:o,confirmButtonText:this.confirmButtonText,cancelButtonText:this.cancelButtonText}))}onClose(){this.root.unmount()}};ti();var $i=F(X());var $l=F(X(),1);function IW(t,e,{checkForDefaultPrevented:r=!0}={}){return function(o){if(t?.(o),r===!1||!o.defaultPrevented)return e?.(o)}}var c0n=F(X(),1);function I3t(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function cce(...t){return e=>{let r=!1,n=t.map(o=>{let i=I3t(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():I3t(t[o],null)}}}}var Wg=F(X(),1),aFe=F(ft(),1);function M3t(t,e){let r=Wg.createContext(e),n=i=>{let{children:a,...s}=i,u=Wg.useMemo(()=>s,Object.values(s));return(0,aFe.jsx)(r.Provider,{value:u,children:a})};n.displayName=t+"Provider";function o(i){let a=Wg.useContext(r);if(a)return a;if(e!==void 0)return e;throw new Error(`\`${i}\` must be used within \`${t}\``)}return[n,o]}function Yi(t,e=[]){let r=[];function n(i,a){let s=Wg.createContext(a),u=r.length;r=[...r,a];let l=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[u]||s,b=Wg.useMemo(()=>m,Object.values(m));return(0,aFe.jsx)(h.Provider,{value:b,children:p})};l.displayName=i+"Provider";function c(d,f){let p=f?.[t]?.[u]||s,m=Wg.useContext(p);if(m)return m;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[l,c]}let o=()=>{let i=r.map(a=>Wg.createContext(a));return function(s){let u=s?.[t]||i;return Wg.useMemo(()=>({[`__scope${t}`]:{...s,[t]:u}}),[s,u])}};return o.scopeName=t,[n,d0n(o,...e)]}function d0n(...t){let e=t[0];if(t.length===1)return e;let r=()=>{let n=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let a=n.reduce((s,{useScope:u,scopeName:l})=>{let d=u(i)[`__scope${l}`];return{...s,...d}},{});return Wg.useMemo(()=>({[`__scope${e.scopeName}`]:a}),[a])}};return r.scopeName=e.scopeName,r}var eM=F(X(),1);var ZU=F(X(),1);function Ur(t){let e=ZU.useRef(t);return ZU.useEffect(()=>{e.current=t}),ZU.useMemo(()=>(...r)=>e.current?.(...r),[])}function ud({prop:t,defaultProp:e,onChange:r=()=>{}}){let[n,o]=f0n({defaultProp:e,onChange:r}),i=t!==void 0,a=i?t:n,s=Ur(r),u=eM.useCallback(l=>{if(i){let d=typeof l=="function"?l(t):l;d!==t&&s(d)}else o(l)},[i,t,o,s]);return[a,u]}function f0n({defaultProp:t,onChange:e}){let r=eM.useState(t),[n]=r,o=eM.useRef(n),i=Ur(e);return eM.useEffect(()=>{o.current!==n&&(i(n),o.current=n)},[n,o,i]),r}var R3t=F(X(),1),y0n=F(ds(),1);var ld=F(X(),1);var XU=F(ft(),1),uFe=ld.forwardRef((t,e)=>{let{children:r,...n}=t,o=ld.Children.toArray(r),i=o.find(m0n);if(i){let a=i.props.children,s=o.map(u=>u===i?ld.Children.count(a)>1?ld.Children.only(null):ld.isValidElement(a)?a.props.children:null:u);return(0,XU.jsx)(sFe,{...n,ref:e,children:ld.isValidElement(a)?ld.cloneElement(a,void 0,s):null})}return(0,XU.jsx)(sFe,{...n,ref:e,children:r})});uFe.displayName="Slot";var sFe=ld.forwardRef((t,e)=>{let{children:r,...n}=t;if(ld.isValidElement(r)){let o=g0n(r);return ld.cloneElement(r,{...h0n(n,r.props),ref:e?cce(e,o):o})}return ld.Children.count(r)>1?ld.Children.only(null):null});sFe.displayName="SlotClone";var p0n=({children:t})=>(0,XU.jsx)(XU.Fragment,{children:t});function m0n(t){return ld.isValidElement(t)&&t.type===p0n}function h0n(t,e){let r={...e};for(let n in e){let o=t[n],i=e[n];/^on[A-Z]/.test(n)?o&&i?r[n]=(...s)=>{i(...s),o(...s)}:o&&(r[n]=o):n==="style"?r[n]={...o,...i}:n==="className"&&(r[n]=[o,i].filter(Boolean).join(" "))}return{...t,...r}}function g0n(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,r=e&&"isReactWarning"in e&&e.isReactWarning;return r?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,r=e&&"isReactWarning"in e&&e.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}var j3t=F(ft(),1),b0n=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],N3t=b0n.reduce((t,e)=>{let r=R3t.forwardRef((n,o)=>{let{asChild:i,...a}=n,s=i?uFe:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,j3t.jsx)(s,{...a,ref:o})});return r.displayName=`Line truncated
.`.concat(FFe,` {
`,includedFiles:Array.from(i)}}Cl();Fd();ti();var j3t=require("obsidian"),LD=F(X()),N3t=F(Dc());function m0n({content:t,onConfirm:e,onCancel:r,confirmButtonText:n,cancelButtonText:o}){return LD.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-5"},LD.default.createElement("div",{className:"tw-whitespace-pre-wrap"},t),LD.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},o&&LD.default.createElement(ge,{variant:"secondary",onClick:r},o),n&&LD.default.createElement(ge,{variant:"default",onClick:e},n)))}var sd=class extends j3t.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,N3t.createRoot)(r);let n=()=>{this.onConfirm(),this.close()},o=()=>{this.close()};this.root.render(LD.default.createElement(m0n,{content:this.content,onConfirm:n,onCancel:o,confirmButtonText:this.confirmButtonText,cancelButtonText:this.cancelButtonText}))}onClose(){this.root.unmount()}};ti();var $i=F(X());var $l=F(X(),1);function MW(t,e,{checkForDefaultPrevented:r=!0}={}){return function(o){if(t?.(o),r===!1||!o.defaultPrevented)return e?.(o)}}var h0n=F(X(),1);function D3t(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function pce(...t){return e=>{let r=!1,n=t.map(o=>{let i=D3t(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():D3t(t[o],null)}}}}var Wg=F(X(),1),uFe=F(pt(),1);function L3t(t,e){let r=Wg.createContext(e),n=i=>{let{children:a,...s}=i,u=Wg.useMemo(()=>s,Object.values(s));return(0,uFe.jsx)(r.Provider,{value:u,children:a})};n.displayName=t+"Provider";function o(i){let a=Wg.useContext(r);if(a)return a;if(e!==void 0)return e;throw new Error(`\`${i}\` must be used within \`${t}\``)}return[n,o]}function Yi(t,e=[]){let r=[];function n(i,a){let s=Wg.createContext(a),u=r.length;r=[...r,a];let l=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[u]||s,b=Wg.useMemo(()=>m,Object.values(m));return(0,uFe.jsx)(h.Provider,{value:b,children:p})};l.displayName=i+"Provider";function c(d,f){let p=f?.[t]?.[u]||s,m=Wg.useContext(p);if(m)return m;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[l,c]}let o=()=>{let i=r.map(a=>Wg.createContext(a));return function(s){let u=s?.[t]||i;return Wg.useMemo(()=>({[`__scope${t}`]:{...s,[t]:u}}),[s,u])}};return o.scopeName=t,[n,g0n(o,...e)]}function g0n(...t){let e=t[0];if(t.length===1)return e;let r=()=>{let n=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let a=n.reduce((s,{useScope:u,scopeName:l})=>{let d=u(i)[`__scope${l}`];return{...s,...d}},{});return Wg.useMemo(()=>({[`__scope${e.scopeName}`]:a}),[a])}};return r.scopeName=e.scopeName,r}var eM=F(X(),1);var XU=F(X(),1);function Ur(t){let e=XU.useRef(t);return XU.useEffect(()=>{e.current=t}),XU.useMemo(()=>(...r)=>e.current?.(...r),[])}function ud({prop:t,defaultProp:e,onChange:r=()=>{}}){let[n,o]=y0n({defaultProp:e,onChange:r}),i=t!==void 0,a=i?t:n,s=Ur(r),u=eM.useCallback(l=>{if(i){let d=typeof l=="function"?l(t):l;d!==t&&s(d)}else o(l)},[i,t,o,s]);return[a,u]}function y0n({defaultProp:t,onChange:e}){let r=eM.useState(t),[n]=r,o=eM.useRef(n),i=Ur(e);return eM.useEffect(()=>{o.current!==n&&(i(n),o.current=n)},[n,o,i]),r}var F3t=F(X(),1),S0n=F(ds(),1);var ld=F(X(),1);var QU=F(pt(),1),cFe=ld.forwardRef((t,e)=>{let{children:r,...n}=t,o=ld.Children.toArray(r),i=o.find(_0n);if(i){let a=i.props.children,s=o.map(u=>u===i?ld.Children.count(a)>1?ld.Children.only(null):ld.isValidElement(a)?a.props.children:null:u);return(0,QU.jsx)(lFe,{...n,ref:e,children:ld.isValidElement(a)?ld.cloneElement(a,void 0,s):null})}return(0,QU.jsx)(lFe,{...n,ref:e,children:r})});cFe.displayName="Slot";var lFe=ld.forwardRef((t,e)=>{let{children:r,...n}=t;if(ld.isValidElement(r)){let o=w0n(r);return ld.cloneElement(r,{...v0n(n,r.props),ref:e?pce(e,o):o})}return ld.Children.count(r)>1?ld.Children.only(null):null});lFe.displayName="SlotClone";var b0n=({children:t})=>(0,QU.jsx)(QU.Fragment,{children:t});function _0n(t){return ld.isValidElement(t)&&t.type===b0n}function v0n(t,e){let r={...e};for(let n in e){let o=t[n],i=e[n];/^on[A-Z]/.test(n)?o&&i?r[n]=(...s)=>{i(...s),o(...s)}:o&&(r[n]=o):n==="style"?r[n]={...o,...i}:n==="className"&&(r[n]=[o,i].filter(Boolean).join(" "))}return{...t,...r}}function w0n(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,r=e&&"isReactWarning"in e&&e.isReactWarning;return r?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,r=e&&"isReactWarning"in e&&e.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}var k3t=F(pt(),1),x0n=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],$3t=x0n.reduce((t,e)=>{let r=F3t.forwardRef((n,o)=>{let{asChild:i,...a}=n,s=i?cFe:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,k3t.jsx)(s,{...a,ref:o})});return r.displayName=`Line truncated
.`.concat($Fe,` {
overflow: hidden `).concat(n,`;
padding-right: `).concat(s,"px ").concat(n,`;
}
body[`).concat(sz,`] {
body[`).concat(uz,`] {
overflow: hidden `).concat(n,`;
overscroll-behavior: contain;
`).concat([e&&"position: relative ".concat(n,";"),r==="margin"&&`
@@ -913,13 +913,13 @@ ${l}`:`${u}
margin-right: 0 `).concat(n,`;
}
body[`).concat(sz,`] {
`).concat(kFe,": ").concat(s,`px;
body[`).concat(uz,`] {
`).concat(BFe,": ").concat(s,`px;
}
`)},EVt=function(){var t=parseInt(document.body.getAttribute(sz)||"0",10);return isFinite(t)?t:0},XSn=function(){uz.useEffect(function(){return document.body.setAttribute(sz,(EVt()+1).toString()),function(){var t=EVt()-1;t<=0?document.body.removeAttribute(sz):document.body.setAttribute(sz,t.toString())}},[])},WD=function(t){var e=t.noRelative,r=t.noImportant,n=t.gapMode,o=n===void 0?"margin":n;XSn();var i=uz.useMemo(function(){return zFe(o)},[o]);return uz.createElement(YSn,{styles:ZSn(i,!e,o,r?"":"!important")})};var HFe=!1;if(typeof window<"u")try{$W=Object.defineProperty({},"passive",{get:function(){return HFe=!0,!0}}),window.addEventListener("test",$W,$W),window.removeEventListener("test",$W,$W)}catch{HFe=!1}var $W,KD=HFe?{passive:!1}:!1;var QSn=function(t){return t.tagName==="TEXTAREA"},TVt=function(t,e){if(!(t instanceof Element))return!1;var r=window.getComputedStyle(t);return r[e]!=="hidden"&&!(r.overflowY===r.overflowX&&!QSn(t)&&r[e]==="visible")},exn=function(t){return TVt(t,"overflowY")},txn=function(t){return TVt(t,"overflowX")},VFe=function(t,e){var r=e.ownerDocument,n=e;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var o=AVt(t,n);if(o){var i=IVt(t,n),a=i[1],s=i[2];if(a>s)return!0}n=n.parentNode}while(n&&n!==r.body);return!1},rxn=function(t){var e=t.scrollTop,r=t.scrollHeight,n=t.clientHeight;return[e,r,n]},nxn=function(t){var e=t.scrollLeft,r=t.scrollWidth,n=t.clientWidth;return[e,r,n]},AVt=function(t,e){return t==="v"?exn(e):txn(e)},IVt=function(t,e){return t==="v"?rxn(e):nxn(e)},oxn=function(t,e){return t==="h"&&e==="rtl"?-1:1},MVt=function(t,e,r,n,o){var i=oxn(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{var p=IVt(t,s),m=p[0],h=p[1],b=p[2],g=h-b-i*m;(m||g)&&AVt(t,s)&&(d+=g,f+=m),s instanceof ShadowRoot?s=s.host:s=s.parentNode}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 Lce=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},RVt=function(t){return[t.deltaX,t.deltaY]},jVt=function(t){return t&&"current"in t?t.current:t},ixn=function(t,e){return t[0]===e[0]&&t[1]===e[1]},axn=function(t){return`
`)},RVt=function(){var t=parseInt(document.body.getAttribute(uz)||"0",10);return isFinite(t)?t:0},nxn=function(){lz.useEffect(function(){return document.body.setAttribute(uz,(RVt()+1).toString()),function(){var t=RVt()-1;t<=0?document.body.removeAttribute(uz):document.body.setAttribute(uz,t.toString())}},[])},KD=function(t){var e=t.noRelative,r=t.noImportant,n=t.gapMode,o=n===void 0?"margin":n;nxn();var i=lz.useMemo(function(){return VFe(o)},[o]);return lz.createElement(txn,{styles:rxn(i,!e,o,r?"":"!important")})};var WFe=!1;if(typeof window<"u")try{BW=Object.defineProperty({},"passive",{get:function(){return WFe=!0,!0}}),window.addEventListener("test",BW,BW),window.removeEventListener("test",BW,BW)}catch{WFe=!1}var BW,GD=WFe?{passive:!1}:!1;var oxn=function(t){return t.tagName==="TEXTAREA"},jVt=function(t,e){if(!(t instanceof Element))return!1;var r=window.getComputedStyle(t);return r[e]!=="hidden"&&!(r.overflowY===r.overflowX&&!oxn(t)&&r[e]==="visible")},ixn=function(t){return jVt(t,"overflowY")},axn=function(t){return jVt(t,"overflowX")},KFe=function(t,e){var r=e.ownerDocument,n=e;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var o=NVt(t,n);if(o){var i=DVt(t,n),a=i[1],s=i[2];if(a>s)return!0}n=n.parentNode}while(n&&n!==r.body);return!1},sxn=function(t){var e=t.scrollTop,r=t.scrollHeight,n=t.clientHeight;return[e,r,n]},uxn=function(t){var e=t.scrollLeft,r=t.scrollWidth,n=t.clientWidth;return[e,r,n]},NVt=function(t,e){return t==="v"?ixn(e):axn(e)},DVt=function(t,e){return t==="v"?sxn(e):uxn(e)},lxn=function(t,e){return t==="h"&&e==="rtl"?-1:1},LVt=function(t,e,r,n,o){var i=lxn(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{var p=DVt(t,s),m=p[0],h=p[1],b=p[2],g=h-b-i*m;(m||g)&&NVt(t,s)&&(d+=g,f+=m),s instanceof ShadowRoot?s=s.host:s=s.parentNode}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 $ce=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},FVt=function(t){return[t.deltaX,t.deltaY]},kVt=function(t){return t&&"current"in t?t.current:t},cxn=function(t,e){return t[0]===e[0]&&t[1]===e[1]},dxn=function(t){return`
.block-interactivity-`.concat(t,` {pointer-events: none;}
.allow-interactivity-`).concat(t,` {pointer-events: all;}
`)},sxn=0,lz=[];function NVt(t){var e=ya.useRef([]),r=ya.useRef([0,0]),n=ya.useRef(),o=ya.useState(sxn++)[0],i=ya.useState(iE)[0],a=ya.useRef(t);ya.useEffect(function(){a.current=t},[t]),ya.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var h=az([t.lockRef.current],(t.shards||[]).map(jVt),!0).filter(Boolean);return h.forEach(function(b){return b.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),h.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(o))})}}},[t.inert,t.lockRef.current,t.shards]);var s=ya.useCallback(function(h,b){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!a.current.allowPinchZoom;var g=Lce(h),y=r.current,S="deltaX"in h?h.deltaX:y[0]-g[0],x="deltaY"in h?h.deltaY:y[1]-g[1],O,P=h.target,E=Math.abs(S)>Math.abs(x)?"h":"v";if("touches"in h&&E==="h"&&P.type==="range")return!1;var A=VFe(E,P);if(!A)return!0;if(A?O=E:(O=E==="v"?"h":"v",A=VFe(E,P)),!A)return!1;if(!n.current&&"changedTouches"in h&&(S||x)&&(n.current=O),!O)return!0;var I=n.current||O;return MVt(I,b,h,I==="h"?S:x,!0)},[]),u=ya.useCallback(function(h){var b=h;if(!(!lz.length||lz[lz.length-1]!==i)){var g="deltaY"in b?RVt(b):Lce(b),y=e.current.filter(function(O){return O.name===b.type&&(O.target===b.target||b.target===O.shadowParent)&&ixn(O.delta,g)})[0];if(y&&y.should){b.cancelable&&b.preventDefault();return}if(!y){var S=(a.current.shards||[]).map(jVt).filter(Boolean).filter(function(O){return O.contains(b.target)}),x=S.length>0?s(b,S[0]):!a.current.noIsolation;x&&b.cancelable&&b.preventDefault()}}},[]),l=ya.useCallback(function(h,b,g,y){var S={name:h,delta:b,target:g,should:y,shadowParent:uxn(g)};e.current.push(S),setTimeout(function(){e.current=e.current.filter(function(x){return x!==S})},1)},[]),c=ya.useCallback(function(h){r.current=Lce(h),n.current=void 0},[]),d=ya.useCallback(function(h){l(h.type,RVt(h),h.target,s(h,t.lockRef.current))},[]),f=ya.useCallback(function(h){l(h.type,Lce(h),h.target,s(h,t.lockRef.current))},[]);ya.useEffect(function(){return lz.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,KD),document.addEventListener("touchmove",u,KD),document.addEventListener("touchstart",c,KD),function(){lz=lz.filter(function(h){return h!==i}),document.removeEventListener("wheel",u,KD),document.removeEventListener("touchmove",u,KD),document.removeEventListener("touchstart",c,KD)}},[]);var p=t.removeScrollBar,m=t.inert;return ya.createElement(ya.Fragment,null,m?ya.createElement(i,{styles:axn(o)}):null,p?ya.createElement(WD,{gapMode:t.gapMode}):null)}function uxn(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var DVt=VD(Dce,NVt);var LVt=Fce.forwardRef(function(t,e){return Fce.createElement(kW,yi({},t,{ref:e,sideCar:DVt}))});LVt.classNames=kW.classNames;var WFe=LVt;var Mr=F(ft(),1),KFe=["Enter"," "],lxn=["ArrowDown","PageUp","Home"],kVt=["ArrowUp","PageDown","End"],cxn=[...lxn,...kVt],dxn={ltr:[...KFe,"ArrowRight"],rtl:[...KFe,"ArrowLeft"]},fxn={ltr:["ArrowLeft"],rtl:["ArrowRight"]},zW="Menu",[qW,pxn,mxn]=F3t(zW),[GD,GFe]=Yi(zW,[mxn,PFe,DFe]),HW=PFe(),$Vt=DFe(),[BVt,vM]=GD(zW),[hxn,VW]=GD(zW),qVt=t=>{let{__scopeMenu:e,open:r=!1,children:n,dir:o,onOpenChange:i,modal:a=!0}=t,s=HW(e),[u,l]=zt.useState(null),c=zt.useRef(!1),d=Ur(i),f=nM(o);return zt.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,Mr.jsx)(TFe,{...s,children:(0,Mr.jsx)(BVt,{scope:e,open:r,onOpenChange:d,content:u,onContentChange:l,children:(0,Mr.jsx)(hxn,{scope:e,onClose:zt.useCallback(()=>d(!1),[d]),isUsingKeyboardRef:c,dir:f,modal:a,children:n})})})};qVt.displayName=zW;var gxn="MenuAnchor",JFe=zt.forwardRef((t,e)=>{let{__scopeMenu:r,...n}=t,o=HW(r);return(0,Mr.jsx)(ZHt,{...o,...n,ref:e})});JFe.displayName=gxn;var YFe="MenuPortal",[yxn,UVt]=GD(YFe,{forceMount:void 0}),zVt=t=>{let{__scopeMenu:e,forceMount:r,children:n,container:o}=t,i=vM(YFe,e);return(0,Mr.jsx)(yxn,{scope:e,forceMount:r,children:(0,Mr.jsx)(fd,{present:r||i.open,children:(0,Mr.jsx)(AFe,{asChild:!0,container:o,children:n})})})};zVt.displayName=YFe;var Yg="MenuContent",[bxn,ZFe]=GD(Yg),HVt=zt.forwardRef((t,e)=>{let r=UVt(Yg,t.__scopeMenu),{forceMount:n=r.forceMount,...o}=t,i=vM(Yg,t.__scopeMenu),a=VW(Yg,t.__scopeMenu);return(0,Mr.jsx)(qW.Provider,{scope:t.__scopeMenu,children:(0,Mr.jsx)(fd,{present:n||i.open,children:(0,Mr.jsx)(qW.Slot,{scope:t.__scopeMenu,children:a.modal?(0,Mr.jsx)(_xn,{...o,ref:e}):(0,Mr.jsx)(vxn,{...o,ref:e})})})})}),_xn Line truncated
`)},fxn=0,cz=[];function $Vt(t){var e=ya.useRef([]),r=ya.useRef([0,0]),n=ya.useRef(),o=ya.useState(fxn++)[0],i=ya.useState(iE)[0],a=ya.useRef(t);ya.useEffect(function(){a.current=t},[t]),ya.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var h=sz([t.lockRef.current],(t.shards||[]).map(kVt),!0).filter(Boolean);return h.forEach(function(b){return b.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),h.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(o))})}}},[t.inert,t.lockRef.current,t.shards]);var s=ya.useCallback(function(h,b){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!a.current.allowPinchZoom;var g=$ce(h),y=r.current,S="deltaX"in h?h.deltaX:y[0]-g[0],x="deltaY"in h?h.deltaY:y[1]-g[1],O,P=h.target,E=Math.abs(S)>Math.abs(x)?"h":"v";if("touches"in h&&E==="h"&&P.type==="range")return!1;var A=KFe(E,P);if(!A)return!0;if(A?O=E:(O=E==="v"?"h":"v",A=KFe(E,P)),!A)return!1;if(!n.current&&"changedTouches"in h&&(S||x)&&(n.current=O),!O)return!0;var I=n.current||O;return LVt(I,b,h,I==="h"?S:x,!0)},[]),u=ya.useCallback(function(h){var b=h;if(!(!cz.length||cz[cz.length-1]!==i)){var g="deltaY"in b?FVt(b):$ce(b),y=e.current.filter(function(O){return O.name===b.type&&(O.target===b.target||b.target===O.shadowParent)&&cxn(O.delta,g)})[0];if(y&&y.should){b.cancelable&&b.preventDefault();return}if(!y){var S=(a.current.shards||[]).map(kVt).filter(Boolean).filter(function(O){return O.contains(b.target)}),x=S.length>0?s(b,S[0]):!a.current.noIsolation;x&&b.cancelable&&b.preventDefault()}}},[]),l=ya.useCallback(function(h,b,g,y){var S={name:h,delta:b,target:g,should:y,shadowParent:pxn(g)};e.current.push(S),setTimeout(function(){e.current=e.current.filter(function(x){return x!==S})},1)},[]),c=ya.useCallback(function(h){r.current=$ce(h),n.current=void 0},[]),d=ya.useCallback(function(h){l(h.type,FVt(h),h.target,s(h,t.lockRef.current))},[]),f=ya.useCallback(function(h){l(h.type,$ce(h),h.target,s(h,t.lockRef.current))},[]);ya.useEffect(function(){return cz.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,GD),document.addEventListener("touchmove",u,GD),document.addEventListener("touchstart",c,GD),function(){cz=cz.filter(function(h){return h!==i}),document.removeEventListener("wheel",u,GD),document.removeEventListener("touchmove",u,GD),document.removeEventListener("touchstart",c,GD)}},[]);var p=t.removeScrollBar,m=t.inert;return ya.createElement(ya.Fragment,null,m?ya.createElement(i,{styles:dxn(o)}):null,p?ya.createElement(KD,{gapMode:t.gapMode}):null)}function pxn(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var BVt=WD(kce,$Vt);var qVt=Bce.forwardRef(function(t,e){return Bce.createElement($W,yi({},t,{ref:e,sideCar:BVt}))});qVt.classNames=$W.classNames;var GFe=qVt;var Mr=F(pt(),1),JFe=["Enter"," "],mxn=["ArrowDown","PageUp","Home"],zVt=["ArrowUp","PageDown","End"],hxn=[...mxn,...zVt],gxn={ltr:[...JFe,"ArrowRight"],rtl:[...JFe,"ArrowLeft"]},yxn={ltr:["ArrowLeft"],rtl:["ArrowRight"]},HW="Menu",[UW,bxn,_xn]=U3t(HW),[JD,YFe]=Yi(HW,[_xn,TFe,FFe]),VW=TFe(),HVt=FFe(),[VVt,vM]=JD(HW),[vxn,WW]=JD(HW),WVt=t=>{let{__scopeMenu:e,open:r=!1,children:n,dir:o,onOpenChange:i,modal:a=!0}=t,s=VW(e),[u,l]=zt.useState(null),c=zt.useRef(!1),d=Ur(i),f=nM(o);return zt.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,Mr.jsx)(IFe,{...s,children:(0,Mr.jsx)(VVt,{scope:e,open:r,onOpenChange:d,content:u,onContentChange:l,children:(0,Mr.jsx)(vxn,{scope:e,onClose:zt.useCallback(()=>d(!1),[d]),isUsingKeyboardRef:c,dir:f,modal:a,children:n})})})};WVt.displayName=HW;var wxn="MenuAnchor",ZFe=zt.forwardRef((t,e)=>{let{__scopeMenu:r,...n}=t,o=VW(r);return(0,Mr.jsx)(rVt,{...o,...n,ref:e})});ZFe.displayName=wxn;var XFe="MenuPortal",[Sxn,KVt]=JD(XFe,{forceMount:void 0}),GVt=t=>{let{__scopeMenu:e,forceMount:r,children:n,container:o}=t,i=vM(XFe,e);return(0,Mr.jsx)(Sxn,{scope:e,forceMount:r,children:(0,Mr.jsx)(fd,{present:r||i.open,children:(0,Mr.jsx)(MFe,{asChild:!0,container:o,children:n})})})};GVt.displayName=XFe;var Yg="MenuContent",[xxn,QFe]=JD(Yg),JVt=zt.forwardRef((t,e)=>{let r=KVt(Yg,t.__scopeMenu),{forceMount:n=r.forceMount,...o}=t,i=vM(Yg,t.__scopeMenu),a=WW(Yg,t.__scopeMenu);return(0,Mr.jsx)(UW.Provider,{scope:t.__scopeMenu,children:(0,Mr.jsx)(fd,{present:n||i.open,children:(0,Mr.jsx)(UW.Slot,{scope:t.__scopeMenu,children:a.modal?(0,Mr.jsx)(Cxn,{...o,ref:e}):(0,Mr.jsx)(Oxn,{...o,ref:e})})})})}),Cxn Line truncated
Embedded PDF (${s}):
${l}
@@ -928,7 +928,7 @@ ${l}
Embedded PDF (${s}): [Error: Could not process PDF]
`)}}return e}async processContextNotes(e,r,n,o,i,a,s){let u="",l=async(d,f=f4)=>{try{if(e.has(d.path)){console.log(`Skipping note ${d.path} as it was included via custom prompt.`);return}if(console.log(`Processing note: ${d.path}, extension: ${d.extension}, chain: ${s}`),!r.supportsExtension(d.extension)){console.warn(`Unsupported file type: ${d.extension}`);return}if(s!=="copilot_plus"&&d.extension!=="md"&&d.extension!=="canvas"){console.warn(`File type ${d.extension} requires Copilot Plus mode for context processing.`);return}let p=await r.parseFile(d,n);d.extension==="md"&&s==="copilot_plus"&&(p=await this.processEmbeddedPDFs(p,n,r)),u+=`
`)}}return e}async processContextNotes(e,r,n,o,i,a,s){let u="",l=async(d,f=p4)=>{try{if(e.has(d.path)){console.log(`Skipping note ${d.path} as it was included via custom prompt.`);return}if(console.log(`Processing note: ${d.path}, extension: ${d.extension}, chain: ${s}`),!r.supportsExtension(d.extension)){console.warn(`Unsupported file type: ${d.extension}`);return}if(s!=="copilot_plus"&&d.extension!=="md"&&d.extension!=="canvas"){console.warn(`File type ${d.extension} requires Copilot Plus mode for context processing.`);return}let p=await r.parseFile(d,n);d.extension==="md"&&s==="copilot_plus"&&(p=await this.processEmbeddedPDFs(p,n,r)),u+=`
<${f}>
Title: [[${d.basename}]]
@@ -942,7 +942,7 @@ ${p}
Path: ${d.path}
[Error: Could not process file]
</${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=hJ();if(!e||e.length===0)return"";let r="";for(let n of e){let o=n.startLine===n.endLine?`L${n.startLine}`:`L${n.startLine}-${n.endLine}`;r+=`
</${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=gJ();if(!e||e.length===0)return"";let r="";for(let n of e){let o=n.startLine===n.endLine?`L${n.startLine}`:`L${n.startLine}-${n.endLine}`;r+=`
<selected_text>
Title: [[${n.noteTitle}]]
@@ -950,22 +950,22 @@ Path: ${n.notePath}
Lines: ${o}
${n.content}
</selected_text>`}return r}};var Qce=require("obsidian");wT();var lm=class t{static getInstance(){return t.instance||(t.instance=new t),t.instance}async createCommand(e,r,n=!1){n||ace(e);let o=QI(),i=ND(e);await app.vault.adapter.exists(o)||await app.vault.createFolder(o);let s=await app.vault.create(i,r);await app.fileManager.processFrontMatter(s,u=>{u[AD]=!1,u[ID]=!1,u[MD]=Number.MAX_SAFE_INTEGER,u[RD]="",u[jD]=0})}async recordUsage(e){this.updateCommand({...e,lastUsedMs:Date.now()},e.title)}async updateCommand(e,r,n=!1){n||EW(e,r);let o=app.vault.getAbstractFileByPath(ND(e.title));if(e.title!==r){let i=ND(e.title);if(app.vault.getAbstractFileByPath(i))throw new Rr("Error saving custom prompt. Please check if the title already exists.");let s=ND(r),u=app.vault.getAbstractFileByPath(s);u instanceof Qce.TFile&&(await app.vault.rename(u,i),o=u)}o||(await this.createCommand(e.title,e.content,n),o=app.vault.getAbstractFileByPath(ND(e.title))),o instanceof Qce.TFile&&(await app.vault.modify(o,e.content),await app.fileManager.processFrontMatter(o,i=>{i[AD]=e.showInContextMenu,i[ID]=e.showInSlashMenu,i[MD]=e.order,i[RD]=e.modelKey,i[jD]=e.lastUsedMs}))}async updateCommands(e){sce(e),await Promise.all(e.map(r=>this.updateCommand(r,r.title,!0)))}async deleteCommand(e){PW(e.title);let r=app.vault.getAbstractFileByPath(ND(e.title));r instanceof Qce.TFile&&await app.vault.delete(r)}};nr();Cn();yn();var CM=require("obsidian"),at=F(X());var vn=F(X()),Mi=F(Z6t());function xM(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())})}var uOn=new Map([["1km","application/vnd.1000minds.decision-model+xml"],["3dml","text/vnd.in3d.3dml"],["3ds","image/x-3ds"],["3g2","video/3gpp2"],["3gp","video/3gp"],["3gpp","video/3gpp"],["3mf","model/3mf"],["7z","application/x-7z-compressed"],["7zip","application/x-7z-compressed"],["123","application/vnd.lotus-1-2-3"],["aab","application/x-authorware-bin"],["aac","audio/x-acc"],["aam","application/x-authorware-map"],["aas","application/x-authorware-seg"],["abw","application/x-abiword"],["ac","application/vnd.nokia.n-gage.ac+xml"],["ac3","audio/ac3"],["acc","application/vnd.americandynamics.acc"],["ace","application/x-ace-compressed"],["acu","application/vnd.acucobol"],["acutc","application/vnd.acucorp"],["adp","audio/adpcm"],["aep","application/vnd.audiograph"],["afm","application/x-font-type1"],["afp","application/vnd.ibm.modcap"],["ahead","application/vnd.ahead.space"],["ai","application/pdf"],["aif","audio/x-aiff"],["aifc","audio/x-aiff"],["aiff","audio/x-aiff"],["air","application/vnd.adobe.air-application-installer-package+zip"],["ait","application/vnd.dvb.ait"],["ami","application/vnd.amiga.ami"],["amr","audio/amr"],["apk","application/vnd.android.package-archive"],["apng","image/apng"],["appcache","text/cache-manifest"],["application","application/x-ms-application"],["apr","application/vnd.lotus-approach"],["arc","application/x-freearc"],["arj","application/x-arj"],["asc","application/pgp-signature"],["asf","video/x-ms-asf"],["asm","text/x-asm"],["aso","application/vnd.accpac.simply.aso"],["asx","video/x-ms-asf"],["atc","application/vnd.acucorp"],["atom","application/atom+xml"],["atomcat","application/atomcat+xml"],["atomdeleted","application/atomdeleted+xml"],["atomsvc","application/atomsvc+xml"],["atx","application/vnd.antix.game-component"],["au","audio/x-au"],["avi","video/x-msvideo"],["avif","image/avif"],["aw","application/applixware"],["azf","application/vnd.airzip.filesecure.azf"],["azs","application/vnd.airzip.filesecure.azs"],["azv","image/vnd.airzip.accelerator.azv"],["azw","application/vnd.amazon.ebook"],["b16","image/vnd.pco.b16"],["bat","application/x-msdownload"],["bcpio","application/x-bcpio"],["bdf","application/x-font-bdf"],["bdm","application/vnd.syncml.dm+wbxml"],["bdoc","application/x-bdoc"],["bed","application/vnd.realvnc.bed"],["bh2","application/vnd.fujitsu.oasysprs"],["bin","application/octet-stream"],["blb","application/x-blorb"],["blorb","application/x-blorb"],["bmi","application/vnd.bmi"],["bmml","application/vnd.balsamiq.bmml+xml"],["bmp","image/bmp"],["book","application/vnd.framemaker"],["box","application/vnd.previewsystems.box"],["boz","application/x-bzip2"],["bpk","application/octet-stream"],["bpmn","application/octet-stream"],["bsp","model/vnd.valve.source.compiled-map"],["btif","image/prs.btif"],["buffer","application/octet-stream"],["bz","application/x-bzip"],["bz2","application/x-bzip2"],["c","text/x-c"],["c4d","application/vnd.clonk.c4group"],["c4f","application/vnd.clonk.c4group"],["c4g","application/vnd.clonk.c4group"],["c4p","application/vnd.clonk.c4group"],["c4u","application/vnd.clonk.c4group"],["c11amc","application/vnd.cluetrust.cartomobile-config"],["c11amz","application/vnd.cluetrust.cartomobile-config-pkg"Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function vOn(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function wOn(t){if(Array.isArray(t))return Rke(t)}function i5t(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),r.push.apply(r,n)}return r}function a5t(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?i5t(Object(r),!0).forEach(function(n){l5t(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):i5t(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}function l5t(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function e9(t,e){return COn(t)||xOn(t,e)||c5t(t,e)||SOn()}function SOn(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function c5t(t,e){if(t){if(typeof t=="string")return Rke(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Rke(t,e)}}function Rke(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function xOn(t,e){var r=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(r!=null){var n=[],o=!0,i=!1,a,s;try{for(r=r.call(t);!(o=(a=r.next()).done)&&(n.push(a.value),!(e&&n.length===e));o=!0);}catch(u){i=!0,s=u}finally{try{!o&&r.return!=null&&r.return()}finally{if(i)throw s}}return n}}function COn(t){if(Array.isArray(t))return t}var OOn=typeof tde.default=="function"?tde.default:tde.default.default,POn="file-invalid-type",EOn="file-too-large",TOn="file-too-small",AOn="too-many-files";var IOn=function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",r=e.split(","),n=r.length>1?"one of ".concat(r.join(", ")):r[0];return{code:POn,message:"File type must be ".concat(n)}},s5t=function(e){return{code:EOn,message:"File is larger than ".concat(e," ").concat(e===1?"byte":"bytes")}},u5t=function(e){return{code:TOn,message:"File is smaller than ".concat(e," ").concat(e===1?"byte":"bytes")}},d5t={code:AOn,message:"Too many files"};function jke(t,e){var r=t.type==="application/x-moz-file"||OOn(t,e);return[r,r?null:IOn(e)]}function Nke(t,e,r){if(QD(t.size))if(QD(e)&&QD(r)){if(t.size>r)return[!1,s5t(r)];if(t.size<e)return[!1,u5t(e)]}else{if(QD(e)&&t.size<e)return[!1,u5t(e)];if(QD(r)&&t.size>r)return[!1,s5t(r)]}return[!0,null]}function QD(t){return t!=null}function f5t(t){var e=t.files,r=t.accept,n=t.minSize,o=t.maxSize,i=t.multiple,a=t.maxFiles,s=t.validator;return!i&&e.length>1||i&&a>=1&&e.length>a?!1:e.every(function(u){var l=jke(u,r),c=e9(l,1),d=c[0],f=Nke(u,n,o),p=e9(f,1),m=p[0],h=s?s(u):null;return d&&m&&!h})}function t9(t){return typeof t.isPropagationStopped=="function"?t.isPropagationStopped():typeof t.cancelBubble<"u"?t.cancelBubble:!1}function r9(t){return t.dataTransfer?Array.prototype.some.call(t.dataTransfer.types,function(e){return e==="Files"||e==="application/x-moz-file"}):!!t.target&&!!t.target.files}function Dke(t){t.preventDefault()}function MOn(t){return t.indexOf("MSIE")!==-1||t.indexOf("Trident/")!==-1}function ROn(t){return t.indexOf("Edge/")!==-1}function p5t(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.navigator.userAgent;return MOn(t)||ROn(t)}function Pb(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return function(n){for(var o=arguments.length,i=new Array(o>1?o-1:0),a=1;a<o;a++)i[a-1]=arguments[a];return e.some(function(s){return!t9(n)&&s&&s.apply(void 0,[n].concat(i)),t9(n)})}}function m5t(){return"showOpenFilePicker"in window}function h5t(t){if(QD(t)){var e=Object.entries(t).filter(function(r){var n=e9(r,2),o=n[0],i=n[1],a=!0;return _5t(o)||(console.warn('Skipped "'.concat(o,'" because it is not a valid MIME type. Check https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for a list of valid MIME types.')),a=!1),(!Array.isArray(i)||!i.every(v5t))&&(console.warn('Skipped "'.concat(o,'" because an invalid file extension was provided.')),a=!1),a}).reduce(function(r,n){var o=e9(n,2),i=o[0],a=o[1];return a5t(a5t({},r),{},l5t({},i,a))},{});return[{description:"Files",accept:e}]}return t}function g5t(t){if(QD(t))return Object.entries(t).reduce(function(e,r){var n=e9(r,2),o=n[0],i=n[1];return[].concat(o5t(e),[o],o5t(i))},[]).filter(function(e){return _5t(e)||v5t(e)}).join(",")}function y5t(t){return t instanceof DOMException&&(t.name==="AbortError"||t.code===t.ABORT_ERR)}function b5t(t){return t instanceof DOMException&&(t.name==="SecurityError"||t.code===t.SECURITY_ERR)}function _5t(t){return t==="audio/*"||t==="video/*"||t==="image/*"||t==="text/*"||t==="application/*"||/\w+\/[-+.\w]+/g.test(t)}function v5t(t){return/^.*\.[\w]+$/.test(t)}var jOn=["children"],NOn=["open"],DOn=["refKey","role","onKeyDown","onFocus","onBlur","onClick","onDragEnter","onDragOver","onDragLeave","onDrop"],LOn=["refKey","onChange","onClick"];function FOn(t){return BOn(t)||$On(t)||x5t(t)||kOn()}function kOn(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function $On(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function BOn(t){if(Array.isArray(t))return Fke(t)}function Lke(t,e){return zOn(t)||UOn(t,e)||x5t(t,e)||qOn()}function qOn(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function x5t(t,e){if(t){if(typeof t=="string")return Fke(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Fke(t,e)}}function Fke(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function UOn(t,e){var r=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(r!=null){var n=[],o=!0,i=!1,a,s;try{for(r=r.call(t);!(o=(a=r.next()).done)&&(n.push(a.value),!(e&&n.length===e));o=!0);}catch(u){i=!0,s=u}finally{try{!o&&r.return!=null&&r.return()}finally{if(i)throw s}}return n}}function zOn(t){if(Array.isArray(t))return t}function w5t(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),r.push.apply(r,n)}return r}function ts(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?w5t(Object(r),!0).forEach(function(n){kke(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):w5t(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}function kke(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function rde(t,e){if(t==null)return{};var r=HOn(t,e),n,o;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(o=0;o<i.length;o++)n=i[o],!(e.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function HOn(t,e){if(t==null)return{};var r={},n=Object.keys(t),o,i;for(i=0;i<n.length;i++)o=n[i],!(e.indexOf(o)>=0)&&(r[o]=t[o]);return r}var Bke=(0,vn.forwardRef)(function(t,e){var r=t.children,n=rde(t,jOn),o=qke(n),i=o.open,a=rde(o,NOn);return(0,vn.useImperativeHandle)(e,function(){return{open:i}},[i]),vn.default.createElement(vn.Fragment,null,r(ts(ts({},a),{},{open:i})))});Bke.displayName="Dropzone";var C5t={disabled:!1,getFilesFromEvent:Ike,maxSize:1/0,minSize:0,multiple:!0,maxFiles:0,preventDropOnDocument:!0,noClick:!1,noKeyboard:!1,noDrag:!1,noDragEventsBubbling:!1,validator:null,useFsAccessApi:!1,autoFocus:!1};Bke.defaultProps=C5t;Bke.propTypes={children:Mi.default.func,accept:Mi.default.objectOf(Mi.default.arrayOf(Mi.default.string)),multiple:Mi.default.bool,preventDropOnDocument:Mi.default.bool,noClick:Mi.default.bool,noKeyboard:Mi.default.bool,noDrag:Mi.default.bool,noDragEventsBubbling:Mi.default.bool,minSize:Mi.default.number,maxSize:Mi.default.number,maxFiles:Mi.default.number,disabled:Mi.default.bool,getFilesFromEvent:Mi.default.func,onFileDialogCancel:Mi.default.func,onFileDialogOpen:Mi.default.func,useFsAccessApi:Mi.default.bool,autoFocus:Mi.default.bool,onDragEnter:Mi.default.func,onDragLeave:Mi.default.func,onDragOver:Mi.default.func,onDrop:Mi.default.func,onDropAccepted:Mi.default.func,onDropRejected:Mi.default.func,onError:Mi.default.func,validator:Mi.default.func};var $ke={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function qke(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=ts(ts({},C5t),t),r=e.accept,n=e.disabled,o=e.getFilesFromEvent,i=e.maxSize,a=e.minSize,s=e.multiple,u=e.maxFiles,l=e.onDragEnter,c=e.onDragLeave,d=e.onDragOver,f=e.onDrop,p=e.onDropAccepted,m=e.onDropRejected,h=e.onFileDialogCancel,b=e.onFileDialogOpen,g=e.useFsAccessApi,y=e.autoFocus,S=e.preventDropOnDocument,x=e.noClick,O=e.noKeyboard,P=e.noDrag,E=e.noDragEventsBubbling,A=e.onError,I=e.validator,R=(0,vn.useMemo)(function(){return g5t(r)},[r]),N=(0,vn.useMemo)(function(){return h5t(r)},[r]),j=(0,vn.useMemo)(function(){return typeof b=="function"?b:S5t},[b]),$=(0,vn.useMemo)(function(){return typeof h=="function"?h:S5t},[h]),k=(0,vn.useRef)(null),z=(0,vn.useRef)(null),V=(0,vn.useReducer)(VOn,$ke),Q=Lke(V,2),J=Q[0],D=Q[1],B=J.isFocused,q=J.isFileDialogActive,K=(0,vn.useRef)(typeof window<"u"&&window.isSecureContext&&g&&m5t()),H=function(){!K.current&&q&&setTimeout(function(){if(z.current){var se=z.current.files;se.length||(D({type:"closeDialog"}),$())}},300)};(0,vn.useEffect)(function(){return window.addEventListener("focus",H,!1),function(){window.removeEventListener("focus",H,!1)}},[z,q,$,K]);var ee=(0,vn.useRef)([]),U=function(se){k.current&&k.current.contains(se.target)||(se.preventDefault(),ee.current=[])};(0,vn.useEffect)(function(){return S&&(document.addEventListener("dragover",Dke,!1),document.addEventListener("drop",U,!1)),function(){S&&(document.removeEventListener("dragover",Dke),document.removeEventListener("drop",U))}},[k,S]),(0,vn.useEffect)(function(){return!n&&y&&k.current&&k.current.focus(),function(){}},[k,y,n]);var W=(0,vn.useCallback)(functio Line truncated
`));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};sde.equals=function(t,e,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
</selected_text>`}return r}};var rde=require("obsidian");wT();var lm=class t{static getInstance(){return t.instance||(t.instance=new t),t.instance}async createCommand(e,r,n=!1){n||lce(e);let o=QI(),i=DD(e);await app.vault.adapter.exists(o)||await app.vault.createFolder(o);let s=await app.vault.create(i,r);await app.fileManager.processFrontMatter(s,u=>{u[ID]=!1,u[MD]=!1,u[RD]=Number.MAX_SAFE_INTEGER,u[jD]="",u[ND]=0})}async recordUsage(e){this.updateCommand({...e,lastUsedMs:Date.now()},e.title)}async updateCommand(e,r,n=!1){n||TW(e,r);let o=app.vault.getAbstractFileByPath(DD(e.title));if(e.title!==r){let i=DD(e.title);if(app.vault.getAbstractFileByPath(i))throw new Rr("Error saving custom prompt. Please check if the title already exists.");let s=DD(r),u=app.vault.getAbstractFileByPath(s);u instanceof rde.TFile&&(await app.vault.rename(u,i),o=u)}o||(await this.createCommand(e.title,e.content,n),o=app.vault.getAbstractFileByPath(DD(e.title))),o instanceof rde.TFile&&(await app.vault.modify(o,e.content),await app.fileManager.processFrontMatter(o,i=>{i[ID]=e.showInContextMenu,i[MD]=e.showInSlashMenu,i[RD]=e.order,i[jD]=e.modelKey,i[ND]=e.lastUsedMs}))}async updateCommands(e){cce(e),await Promise.all(e.map(r=>this.updateCommand(r,r.title,!0)))}async deleteCommand(e){EW(e.title);let r=app.vault.getAbstractFileByPath(DD(e.title));r instanceof rde.TFile&&await app.vault.delete(r)}};nr();yn();bn();var CM=require("obsidian"),at=F(X());var wn=F(X()),Mi=F(r5t());function xM(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())})}var pOn=new Map([["1km","application/vnd.1000minds.decision-model+xml"],["3dml","text/vnd.in3d.3dml"],["3ds","image/x-3ds"],["3g2","video/3gpp2"],["3gp","video/3gp"],["3gpp","video/3gpp"],["3mf","model/3mf"],["7z","application/x-7z-compressed"],["7zip","application/x-7z-compressed"],["123","application/vnd.lotus-1-2-3"],["aab","application/x-authorware-bin"],["aac","audio/x-acc"],["aam","application/x-authorware-map"],["aas","application/x-authorware-seg"],["abw","application/x-abiword"],["ac","application/vnd.nokia.n-gage.ac+xml"],["ac3","audio/ac3"],["acc","application/vnd.americandynamics.acc"],["ace","application/x-ace-compressed"],["acu","application/vnd.acucobol"],["acutc","application/vnd.acucorp"],["adp","audio/adpcm"],["aep","application/vnd.audiograph"],["afm","application/x-font-type1"],["afp","application/vnd.ibm.modcap"],["ahead","application/vnd.ahead.space"],["ai","application/pdf"],["aif","audio/x-aiff"],["aifc","audio/x-aiff"],["aiff","audio/x-aiff"],["air","application/vnd.adobe.air-application-installer-package+zip"],["ait","application/vnd.dvb.ait"],["ami","application/vnd.amiga.ami"],["amr","audio/amr"],["apk","application/vnd.android.package-archive"],["apng","image/apng"],["appcache","text/cache-manifest"],["application","application/x-ms-application"],["apr","application/vnd.lotus-approach"],["arc","application/x-freearc"],["arj","application/x-arj"],["asc","application/pgp-signature"],["asf","video/x-ms-asf"],["asm","text/x-asm"],["aso","application/vnd.accpac.simply.aso"],["asx","video/x-ms-asf"],["atc","application/vnd.acucorp"],["atom","application/atom+xml"],["atomcat","application/atomcat+xml"],["atomdeleted","application/atomdeleted+xml"],["atomsvc","application/atomsvc+xml"],["atx","application/vnd.antix.game-component"],["au","audio/x-au"],["avi","video/x-msvideo"],["avif","image/avif"],["aw","application/applixware"],["azf","application/vnd.airzip.filesecure.azf"],["azs","application/vnd.airzip.filesecure.azs"],["azv","image/vnd.airzip.accelerator.azv"],["azw","application/vnd.amazon.ebook"],["b16","image/vnd.pco.b16"],["bat","application/x-msdownload"],["bcpio","application/x-bcpio"],["bdf","application/x-font-bdf"],["bdm","application/vnd.syncml.dm+wbxml"],["bdoc","application/x-bdoc"],["bed","application/vnd.realvnc.bed"],["bh2","application/vnd.fujitsu.oasysprs"],["bin","application/octet-stream"],["blb","application/x-blorb"],["blorb","application/x-blorb"],["bmi","application/vnd.bmi"],["bmml","application/vnd.balsamiq.bmml+xml"],["bmp","image/bmp"],["book","application/vnd.framemaker"],["box","application/vnd.previewsystems.box"],["boz","application/x-bzip2"],["bpk","application/octet-stream"],["bpmn","application/octet-stream"],["bsp","model/vnd.valve.source.compiled-map"],["btif","image/prs.btif"],["buffer","application/octet-stream"],["bz","application/x-bzip"],["bz2","application/x-bzip2"],["c","text/x-c"],["c4d","application/vnd.clonk.c4group"],["c4f","application/vnd.clonk.c4group"],["c4g","application/vnd.clonk.c4group"],["c4p","application/vnd.clonk.c4group"],["c4u","application/vnd.clonk.c4group"],["c11amc","application/vnd.cluetrust.cartomobile-config"],["c11amz","application/vnd.cluetrust.cartomobile-config-pkg"Line truncated
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function OOn(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function POn(t){if(Array.isArray(t))return Nke(t)}function c5t(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),r.push.apply(r,n)}return r}function d5t(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?c5t(Object(r),!0).forEach(function(n){m5t(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):c5t(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}function m5t(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function t9(t,e){return AOn(t)||TOn(t,e)||h5t(t,e)||EOn()}function EOn(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function h5t(t,e){if(t){if(typeof t=="string")return Nke(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Nke(t,e)}}function Nke(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function TOn(t,e){var r=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(r!=null){var n=[],o=!0,i=!1,a,s;try{for(r=r.call(t);!(o=(a=r.next()).done)&&(n.push(a.value),!(e&&n.length===e));o=!0);}catch(u){i=!0,s=u}finally{try{!o&&r.return!=null&&r.return()}finally{if(i)throw s}}return n}}function AOn(t){if(Array.isArray(t))return t}var IOn=typeof ode.default=="function"?ode.default:ode.default.default,MOn="file-invalid-type",ROn="file-too-large",jOn="file-too-small",NOn="too-many-files";var DOn=function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",r=e.split(","),n=r.length>1?"one of ".concat(r.join(", ")):r[0];return{code:MOn,message:"File type must be ".concat(n)}},f5t=function(e){return{code:ROn,message:"File is larger than ".concat(e," ").concat(e===1?"byte":"bytes")}},p5t=function(e){return{code:jOn,message:"File is smaller than ".concat(e," ").concat(e===1?"byte":"bytes")}},g5t={code:NOn,message:"Too many files"};function Dke(t,e){var r=t.type==="application/x-moz-file"||IOn(t,e);return[r,r?null:DOn(e)]}function Lke(t,e,r){if(eL(t.size))if(eL(e)&&eL(r)){if(t.size>r)return[!1,f5t(r)];if(t.size<e)return[!1,p5t(e)]}else{if(eL(e)&&t.size<e)return[!1,p5t(e)];if(eL(r)&&t.size>r)return[!1,f5t(r)]}return[!0,null]}function eL(t){return t!=null}function y5t(t){var e=t.files,r=t.accept,n=t.minSize,o=t.maxSize,i=t.multiple,a=t.maxFiles,s=t.validator;return!i&&e.length>1||i&&a>=1&&e.length>a?!1:e.every(function(u){var l=Dke(u,r),c=t9(l,1),d=c[0],f=Lke(u,n,o),p=t9(f,1),m=p[0],h=s?s(u):null;return d&&m&&!h})}function r9(t){return typeof t.isPropagationStopped=="function"?t.isPropagationStopped():typeof t.cancelBubble<"u"?t.cancelBubble:!1}function n9(t){return t.dataTransfer?Array.prototype.some.call(t.dataTransfer.types,function(e){return e==="Files"||e==="application/x-moz-file"}):!!t.target&&!!t.target.files}function Fke(t){t.preventDefault()}function LOn(t){return t.indexOf("MSIE")!==-1||t.indexOf("Trident/")!==-1}function FOn(t){return t.indexOf("Edge/")!==-1}function b5t(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.navigator.userAgent;return LOn(t)||FOn(t)}function Pb(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return function(n){for(var o=arguments.length,i=new Array(o>1?o-1:0),a=1;a<o;a++)i[a-1]=arguments[a];return e.some(function(s){return!r9(n)&&s&&s.apply(void 0,[n].concat(i)),r9(n)})}}function _5t(){return"showOpenFilePicker"in window}function v5t(t){if(eL(t)){var e=Object.entries(t).filter(function(r){var n=t9(r,2),o=n[0],i=n[1],a=!0;return C5t(o)||(console.warn('Skipped "'.concat(o,'" because it is not a valid MIME type. Check https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for a list of valid MIME types.')),a=!1),(!Array.isArray(i)||!i.every(O5t))&&(console.warn('Skipped "'.concat(o,'" because an invalid file extension was provided.')),a=!1),a}).reduce(function(r,n){var o=t9(n,2),i=o[0],a=o[1];return d5t(d5t({},r),{},m5t({},i,a))},{});return[{description:"Files",accept:e}]}return t}function w5t(t){if(eL(t))return Object.entries(t).reduce(function(e,r){var n=t9(r,2),o=n[0],i=n[1];return[].concat(l5t(e),[o],l5t(i))},[]).filter(function(e){return C5t(e)||O5t(e)}).join(",")}function S5t(t){return t instanceof DOMException&&(t.name==="AbortError"||t.code===t.ABORT_ERR)}function x5t(t){return t instanceof DOMException&&(t.name==="SecurityError"||t.code===t.SECURITY_ERR)}function C5t(t){return t==="audio/*"||t==="video/*"||t==="image/*"||t==="text/*"||t==="application/*"||/\w+\/[-+.\w]+/g.test(t)}function O5t(t){return/^.*\.[\w]+$/.test(t)}var kOn=["children"],$On=["open"],BOn=["refKey","role","onKeyDown","onFocus","onBlur","onClick","onDragEnter","onDragOver","onDragLeave","onDrop"],qOn=["refKey","onChange","onClick"];function UOn(t){return VOn(t)||HOn(t)||T5t(t)||zOn()}function zOn(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function HOn(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function VOn(t){if(Array.isArray(t))return $ke(t)}function kke(t,e){return GOn(t)||KOn(t,e)||T5t(t,e)||WOn()}function WOn(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function T5t(t,e){if(t){if(typeof t=="string")return $ke(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return $ke(t,e)}}function $ke(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function KOn(t,e){var r=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(r!=null){var n=[],o=!0,i=!1,a,s;try{for(r=r.call(t);!(o=(a=r.next()).done)&&(n.push(a.value),!(e&&n.length===e));o=!0);}catch(u){i=!0,s=u}finally{try{!o&&r.return!=null&&r.return()}finally{if(i)throw s}}return n}}function GOn(t){if(Array.isArray(t))return t}function P5t(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),r.push.apply(r,n)}return r}function ts(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?P5t(Object(r),!0).forEach(function(n){Bke(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):P5t(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}function Bke(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function ide(t,e){if(t==null)return{};var r=JOn(t,e),n,o;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(o=0;o<i.length;o++)n=i[o],!(e.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function JOn(t,e){if(t==null)return{};var r={},n=Object.keys(t),o,i;for(i=0;i<n.length;i++)o=n[i],!(e.indexOf(o)>=0)&&(r[o]=t[o]);return r}var Uke=(0,wn.forwardRef)(function(t,e){var r=t.children,n=ide(t,kOn),o=zke(n),i=o.open,a=ide(o,$On);return(0,wn.useImperativeHandle)(e,function(){return{open:i}},[i]),wn.default.createElement(wn.Fragment,null,r(ts(ts({},a),{},{open:i})))});Uke.displayName="Dropzone";var A5t={disabled:!1,getFilesFromEvent:Rke,maxSize:1/0,minSize:0,multiple:!0,maxFiles:0,preventDropOnDocument:!0,noClick:!1,noKeyboard:!1,noDrag:!1,noDragEventsBubbling:!1,validator:null,useFsAccessApi:!1,autoFocus:!1};Uke.defaultProps=A5t;Uke.propTypes={children:Mi.default.func,accept:Mi.default.objectOf(Mi.default.arrayOf(Mi.default.string)),multiple:Mi.default.bool,preventDropOnDocument:Mi.default.bool,noClick:Mi.default.bool,noKeyboard:Mi.default.bool,noDrag:Mi.default.bool,noDragEventsBubbling:Mi.default.bool,minSize:Mi.default.number,maxSize:Mi.default.number,maxFiles:Mi.default.number,disabled:Mi.default.bool,getFilesFromEvent:Mi.default.func,onFileDialogCancel:Mi.default.func,onFileDialogOpen:Mi.default.func,useFsAccessApi:Mi.default.bool,autoFocus:Mi.default.bool,onDragEnter:Mi.default.func,onDragLeave:Mi.default.func,onDragOver:Mi.default.func,onDrop:Mi.default.func,onDropAccepted:Mi.default.func,onDropRejected:Mi.default.func,onError:Mi.default.func,validator:Mi.default.func};var qke={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function zke(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=ts(ts({},A5t),t),r=e.accept,n=e.disabled,o=e.getFilesFromEvent,i=e.maxSize,a=e.minSize,s=e.multiple,u=e.maxFiles,l=e.onDragEnter,c=e.onDragLeave,d=e.onDragOver,f=e.onDrop,p=e.onDropAccepted,m=e.onDropRejected,h=e.onFileDialogCancel,b=e.onFileDialogOpen,g=e.useFsAccessApi,y=e.autoFocus,S=e.preventDropOnDocument,x=e.noClick,O=e.noKeyboard,P=e.noDrag,E=e.noDragEventsBubbling,A=e.onError,I=e.validator,R=(0,wn.useMemo)(function(){return w5t(r)},[r]),N=(0,wn.useMemo)(function(){return v5t(r)},[r]),j=(0,wn.useMemo)(function(){return typeof b=="function"?b:E5t},[b]),$=(0,wn.useMemo)(function(){return typeof h=="function"?h:E5t},[h]),k=(0,wn.useRef)(null),z=(0,wn.useRef)(null),V=(0,wn.useReducer)(YOn,qke),Q=kke(V,2),J=Q[0],D=Q[1],B=J.isFocused,q=J.isFileDialogActive,K=(0,wn.useRef)(typeof window<"u"&&window.isSecureContext&&g&&_5t()),H=function(){!K.current&&q&&setTimeout(function(){if(z.current){var se=z.current.files;se.length||(D({type:"closeDialog"}),$())}},300)};(0,wn.useEffect)(function(){return window.addEventListener("focus",H,!1),function(){window.removeEventListener("focus",H,!1)}},[z,q,$,K]);var ee=(0,wn.useRef)([]),U=function(se){k.current&&k.current.contains(se.target)||(se.preventDefault(),ee.current=[])};(0,wn.useEffect)(function(){return S&&(document.addEventListener("dragover",Fke,!1),document.addEventListener("drop",U,!1)),function(){S&&(document.removeEventListener("dragover",Fke),document.removeEventListener("drop",U))}},[k,S]),(0,wn.useEffect)(function(){return!n&&y&&k.current&&k.current.focus(),function(){}},[k,y,n]);var W=(0,wn.useCallback)(functio Line truncated
`));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};cde.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))),Eb.prototype.equals.call(this,t,e,r)};function q5t(t,e,r){var n=QOn(r,{ignoreWhitespace:!0});return sde.diff(t,e,n)}var ePn=new Eb;ePn.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var tPn=new Eb;tPn.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function Hke(t){"@babel/helpers - typeof";return Hke=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},Hke(t)}var o9=new Eb;o9.useLongestToken=!0;o9.tokenize=sde.tokenize;o9.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(Vke(t,null,null,o),o," ")};o9.equals=function(t,e,r){return Eb.prototype.equals.call(o9,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"),r)};function Vke(t,e,r,n,o){e=e||[],r=r||[],n&&(t=n(o,t));var i;for(i=0;i<e.length;i+=1)if(e[i]===t)return r[i];var a;if(Object.prototype.toString.call(t)==="[object Array]"){for(e.push(t),a=new Array(t.length),r.push(a),i=0;i<t.length;i+=1)a[i]=Vke(t[i],e,r,n,o);return e.pop(),r.pop(),a}if(t&&t.toJSON&&(t=t.toJSON()),Hke(t)==="object"&&t!==null){e.push(t),a={},r.push(a);var s=[],u;for(u in t)Object.prototype.hasOwnProperty.call(t,u)&&s.push(u);for(s.sort(),i=0;i<s.length;i+=1)u=s[i],a[u]=Vke(t[u],e,r,n,u);e.pop(),r.pop()}else a=t;return a}var Wke=new Eb;Wke.tokenize=function(t){return t.slice()};Wke.join=Wke.removeEmpty=function(t){return t};var Sr=F(X()),K5t=F(Dc());var Tb=F(X());ti();yn();Tn();yo();yn();var sE=require("obsidian"),wr=F(X()),U5t=F(Dc());ti();var z5t=F(X());function rPn(t){return t.trim().split(`
`)&&(e=e.slice(0,-1))),Eb.prototype.equals.call(this,t,e,r)};function W5t(t,e,r){var n=oPn(r,{ignoreWhitespace:!0});return cde.diff(t,e,n)}var iPn=new Eb;iPn.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var aPn=new Eb;aPn.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function Wke(t){"@babel/helpers - typeof";return Wke=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},Wke(t)}var i9=new Eb;i9.useLongestToken=!0;i9.tokenize=cde.tokenize;i9.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(Kke(t,null,null,o),o," ")};i9.equals=function(t,e,r){return Eb.prototype.equals.call(i9,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"),r)};function Kke(t,e,r,n,o){e=e||[],r=r||[],n&&(t=n(o,t));var i;for(i=0;i<e.length;i+=1)if(e[i]===t)return r[i];var a;if(Object.prototype.toString.call(t)==="[object Array]"){for(e.push(t),a=new Array(t.length),r.push(a),i=0;i<t.length;i+=1)a[i]=Kke(t[i],e,r,n,o);return e.pop(),r.pop(),a}if(t&&t.toJSON&&(t=t.toJSON()),Wke(t)==="object"&&t!==null){e.push(t),a={},r.push(a);var s=[],u;for(u in t)Object.prototype.hasOwnProperty.call(t,u)&&s.push(u);for(s.sort(),i=0;i<s.length;i+=1)u=s[i],a[u]=Kke(t[u],e,r,n,u);e.pop(),r.pop()}else a=t;return a}var Gke=new Eb;Gke.tokenize=function(t){return t.slice()};Gke.join=Gke.removeEmpty=function(t){return t};var Sr=F(X()),X5t=F(Dc());var Tb=F(X());ti();bn();Tn();yo();bn();var sE=require("obsidian"),wr=F(X()),K5t=F(Dc());ti();var G5t=F(X());function sPn(t){return t.trim().split(`
`).map(r=>"- "+r).join(`
`)}function Kke(t){return t.map(r=>{let n=r.some(a=>a.added),o=r.some(a=>a.removed),i="";return n?i=r.map(a=>a.added?a.value:"").join(`
`):o?i=r.map(a=>a.removed?rPn(a.value):"").join(`
`)}function Jke(t){return t.map(r=>{let n=r.some(a=>a.added),o=r.some(a=>a.removed),i="";return n?i=r.map(a=>a.added?a.value:"").join(`
`):o?i=r.map(a=>a.removed?sPn(a.value):"").join(`
`):r.map(s=>s.value).join(`
`).trim().length>0&&(i="..."),i}).join(`
`)}function a9(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 s9="obsidian-copilot-apply-view",ude=class extends sE.ItemView{constructor(r){super(r);this.root=null;this.state=null}getViewType(){return s9}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)}render(){if(!this.state)return;let r=this.containerEl.children[1];r.empty();let n=r.createDiv();this.root||(this.root=(0,U5t.createRoot)(n)),this.root.render(wr.default.createElement(nPn,{app:this.app,state:this.state,close:()=>this.leaf.detach()}))}},H5t=(0,wr.memo)(({oldLine:t,newLine:e})=>{let r=$5t(t,e);return wr.default.createElement(wr.default.Fragment,null,r.map((n,o)=>n.added?wr.default.createElement("span",{key:o,className:"tw-text-success"},n.value):n.removed?wr.default.createElement("span",{key:o,className:"tw-text-error tw-line-through"},n.value):wr.default.createElement("span",{key:o},n.value)))});H5t.displayName="WordDiff";var nPn=({app:t,state:e,close:r})=>{let[n,o]=(0,z5t.useState)(()=>e.changes.map(p=>({...p,accepted:null}))),i=a9(n),a=(0,wr.useRef)([]);if(!e||!e.changes)return fe("Invalid state:",e),wr.default.createElement("div",{className:"tw-flex tw-h-full tw-flex-col tw-items-center tw-justify-center"},wr.default.createElement("div",{className:"tw-text-error"},"Error: Invalid state - missing changes"),wr.default.createElement(ge,{onClick:r,className:"tw-mt-4"},"Close"));let s=async()=>{try{let p=n.map(m=>m.accepted===null?{...m,accepted:!0}:m);await l(p)}catch(p){fe("Error applying changes:",p),new sE.Notice(`Error applying changes: ${p.message}`)}},u=async()=>{try{let p=n.map(m=>m.accepted===null?{...m,accepted:!1}:m);await l(p)}catch(p){fe("Error applying changes:",p),new sE.Notice(`Error applying changes: ${p.message}`)}},l=async p=>{let m=p.filter(b=>b.added?b.accepted===!0:b.removed?b.accepted===!1:!0).map(b=>b.value).join(""),h=t.vault.getAbstractFileByPath(e.path);if(!h||!(h instanceof sE.TFile)){new sE.Notice("File not found:"+e.path),r();return}await t.vault.modify(h,m),new sE.Notice("Changes applied successfully"),r()},c=p=>{if(!i)return;let m=-1;for(let h=p+1;h<i.length;h++){let b=i[h],g=b.some(S=>S.added||S.removed),y=b.some(S=>(S.added||S.removed)&&S.accepted===null);if(g&&y){m=h;break}}m!==-1&&a.current[m]&&a.current[m]?.scrollIntoView({behavior:"smooth",block:"center"})},d=p=>{o(m=>{let h=[...m],b=i?.[p];return b&&b.forEach(g=>{let y=h.findIndex(S=>S===g);y!==-1&&(h[y]={...h[y],accepted:!0})}),h}),setTimeout(()=>c(p),0)},f=p=>{o(m=>{let h=[...m],b=i?.[p];return b&&b.forEach(g=>{let y=h.findIndex(S=>S===g);y!==-1&&(h[y]={...h[y],accepted:!1})}),h}),setTimeout(()=>c(p),0)};return wr.default.createElement("div",{className:"tw-relative tw-flex tw-h-full tw-flex-col"},wr.default.createElement("div",{className:"tw-fixed tw-bottom-2 tw-left-1/2 tw-z-[1] tw-flex tw-gap-2 tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-secondary tw-p-2"},wr.default.createElement(ge,{variant:"destructive",size:"sm",onClick:u},wr.default.createElement(Vi,{className:"tw-size-4"}),"Reject"),wr.default.createElement(ge,{variant:"success",size:"sm",onClick:s},wr.default.createElement(Jl,{className:"tw-size-4"}),"Accept")),wr.default.createElement("div",{className:"tw-flex tw-items-center tw-border-b tw-border-solid tw-border-border tw-p-2 tw-text-sm tw-font-medium"},e.path),wr.default.createElement("div",{className:"tw-flex-1 tw-overflow-auto tw-p-2"},i?.map((p,m)=>{let h=p.some(g=>g.added||g.removed),b=h?p.every(g=>!g.added&&!g.removed||g.accepted===!0)?"accepted":p.every(g=>!g.added&&!g.removed||g.accepted===!1)?"rejected":"undecided":"unchanged";return wr.default.createElement("div",{key:m,ref:g=>a.current[m]=g,className:_e("tw-mb-4 tw-overflow-hidden tw-rounded-md")},b==="accepted"?wr.default.createElement("div",{className:"tw-flex-1 tw-whitespace-pre-wrap tw-px-2 tw-py-1 tw-font-mono tw-text-sm tw-text-normal"},p.filter(g=>!g.removed).map((g,y)=>wr.default.createElement("div",{key:y},g.value))):b==="rejected"?wr.default.createElement("div",{className:"tw-flex-1 tw-whitespace-pre-wrap tw-px-2 tw-py-1 tw-font-mono tw-text-sm tw-text-normal"},p.filter(g=>!g.added).map((g,y)=>wr.default.createElement("div",{key:y},g.value))):p.map((g,y)=>{if(g.added){let S=p.findIndex((x,O)=>x.removed&&O!==y);if(S!==-1){let x=p[S].value;return wr.default.createElement("div",{key:`${m}-${y}`,className:"tw-relative"},wr.default.createElement("div",{className:"tw-flex-1 tw-whitespace-pre-wrap tw-px-2 tw-py-1 tw-font-mono tw-text-sm"},wr.default.createElement(H5t,{oldLine:x,newLine:g.value})))}}return g.removed&&p.findIndex((x,O)=>x.added&&O!==y)!==-1?null:wr.default.createElement("div",{key:`${m}-${y}`,className:"tw-relative"},wr.default.createElement("div",{className:_e("tw-flex-1 tw-whitespace-pre-wrap tw-px-2 tw-py-1 tw-font-mono tw-te Line truncated
`)}function s9(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 u9="obsidian-copilot-apply-view",dde=class extends sE.ItemView{constructor(r){super(r);this.root=null;this.state=null}getViewType(){return u9}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)}render(){if(!this.state)return;let r=this.containerEl.children[1];r.empty();let n=r.createDiv();this.root||(this.root=(0,K5t.createRoot)(n)),this.root.render(wr.default.createElement(uPn,{app:this.app,state:this.state,close:()=>this.leaf.detach()}))}},J5t=(0,wr.memo)(({oldLine:t,newLine:e})=>{let r=H5t(t,e);return wr.default.createElement(wr.default.Fragment,null,r.map((n,o)=>n.added?wr.default.createElement("span",{key:o,className:"tw-text-success"},n.value):n.removed?wr.default.createElement("span",{key:o,className:"tw-text-error tw-line-through"},n.value):wr.default.createElement("span",{key:o},n.value)))});J5t.displayName="WordDiff";var uPn=({app:t,state:e,close:r})=>{let[n,o]=(0,G5t.useState)(()=>e.changes.map(p=>({...p,accepted:null}))),i=s9(n),a=(0,wr.useRef)([]);if(!e||!e.changes)return fe("Invalid state:",e),wr.default.createElement("div",{className:"tw-flex tw-h-full tw-flex-col tw-items-center tw-justify-center"},wr.default.createElement("div",{className:"tw-text-error"},"Error: Invalid state - missing changes"),wr.default.createElement(ge,{onClick:r,className:"tw-mt-4"},"Close"));let s=async()=>{try{let p=n.map(m=>m.accepted===null?{...m,accepted:!0}:m);await l(p)}catch(p){fe("Error applying changes:",p),new sE.Notice(`Error applying changes: ${p.message}`)}},u=async()=>{try{let p=n.map(m=>m.accepted===null?{...m,accepted:!1}:m);await l(p)}catch(p){fe("Error applying changes:",p),new sE.Notice(`Error applying changes: ${p.message}`)}},l=async p=>{let m=p.filter(b=>b.added?b.accepted===!0:b.removed?b.accepted===!1:!0).map(b=>b.value).join(""),h=t.vault.getAbstractFileByPath(e.path);if(!h||!(h instanceof sE.TFile)){new sE.Notice("File not found:"+e.path),r();return}await t.vault.modify(h,m),new sE.Notice("Changes applied successfully"),r()},c=p=>{if(!i)return;let m=-1;for(let h=p+1;h<i.length;h++){let b=i[h],g=b.some(S=>S.added||S.removed),y=b.some(S=>(S.added||S.removed)&&S.accepted===null);if(g&&y){m=h;break}}m!==-1&&a.current[m]&&a.current[m]?.scrollIntoView({behavior:"smooth",block:"center"})},d=p=>{o(m=>{let h=[...m],b=i?.[p];return b&&b.forEach(g=>{let y=h.findIndex(S=>S===g);y!==-1&&(h[y]={...h[y],accepted:!0})}),h}),setTimeout(()=>c(p),0)},f=p=>{o(m=>{let h=[...m],b=i?.[p];return b&&b.forEach(g=>{let y=h.findIndex(S=>S===g);y!==-1&&(h[y]={...h[y],accepted:!1})}),h}),setTimeout(()=>c(p),0)};return wr.default.createElement("div",{className:"tw-relative tw-flex tw-h-full tw-flex-col"},wr.default.createElement("div",{className:"tw-fixed tw-bottom-2 tw-left-1/2 tw-z-[1] tw-flex tw-gap-2 tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-secondary tw-p-2"},wr.default.createElement(ge,{variant:"destructive",size:"sm",onClick:u},wr.default.createElement(Vi,{className:"tw-size-4"}),"Reject"),wr.default.createElement(ge,{variant:"success",size:"sm",onClick:s},wr.default.createElement(Jl,{className:"tw-size-4"}),"Accept")),wr.default.createElement("div",{className:"tw-flex tw-items-center tw-border-b tw-border-solid tw-border-border tw-p-2 tw-text-sm tw-font-medium"},e.path),wr.default.createElement("div",{className:"tw-flex-1 tw-overflow-auto tw-p-2"},i?.map((p,m)=>{let h=p.some(g=>g.added||g.removed),b=h?p.every(g=>!g.added&&!g.removed||g.accepted===!0)?"accepted":p.every(g=>!g.added&&!g.removed||g.accepted===!1)?"rejected":"undecided":"unchanged";return wr.default.createElement("div",{key:m,ref:g=>a.current[m]=g,className:_e("tw-mb-4 tw-overflow-hidden tw-rounded-md")},b==="accepted"?wr.default.createElement("div",{className:"tw-flex-1 tw-whitespace-pre-wrap tw-px-2 tw-py-1 tw-font-mono tw-text-sm tw-text-normal"},p.filter(g=>!g.removed).map((g,y)=>wr.default.createElement("div",{key:y},g.value))):b==="rejected"?wr.default.createElement("div",{className:"tw-flex-1 tw-whitespace-pre-wrap tw-px-2 tw-py-1 tw-font-mono tw-text-sm tw-text-normal"},p.filter(g=>!g.added).map((g,y)=>wr.default.createElement("div",{key:y},g.value))):p.map((g,y)=>{if(g.added){let S=p.findIndex((x,O)=>x.removed&&O!==y);if(S!==-1){let x=p[S].value;return wr.default.createElement("div",{key:`${m}-${y}`,className:"tw-relative"},wr.default.createElement("div",{className:"tw-flex-1 tw-whitespace-pre-wrap tw-px-2 tw-py-1 tw-font-mono tw-text-sm"},wr.default.createElement(J5t,{oldLine:x,newLine:g.value})))}}return g.removed&&p.findIndex((x,O)=>x.added&&O!==y)!==-1?null:wr.default.createElement("div",{key:`${m}-${y}`,className:"tw-relative"},wr.default.createElement("div",{className:_e("tw-flex-1 tw-whitespace-pre-wrap tw-px-2 tw-py-1 tw-font-mono tw-te Line truncated
<summary style="${W}">Thought for a second</summary>
<div class="tw-text-muted" style="${Y}">${le.trim()}</div>
</details>
@@ -991,25 +991,25 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
<ul>
`+V+`
</ul>
</details>`};(0,Sr.useEffect)(()=>{let j=[],$=!1;if(p.current&&t.sender!==Pi){p.current.innerHTML="",m.current||(m.current=new lE.Component);let k=g(t.message);if(!$&&(lE.MarkdownRenderer.renderMarkdown(k,p.current,"",m.current),!r)){let z=p.current.querySelectorAll("pre");z.length>0&&z.forEach(V=>{if($)return;let Q=V.querySelector("code");if(!Q)return;let J=Q.textContent||"";try{if(J.trim().startsWith("{")&&J.trim().endsWith("}")){let D=JSON.parse(J);if(D.type==="composer"&&D.path&&(typeof D.content=="string"||typeof D.canvas_json=="string")){let B;typeof D.content=="string"?B=D.content:B=JSON.stringify(D.canvas_json);let q=D.path.trim();q.startsWith("/")&&(q=q.slice(1));let K=document.createElement("div");V.parentNode?.replaceChild(K,V);let H=(0,K5t.createRoot)(K);j.push(H);let ee=e.vault.getAbstractFileByPath(q),U=[];(async()=>{if(ee instanceof lE.TFile){let W=await e.vault.read(ee);U=q5t(W,B,{newlineIsToken:!0})}else{let W=q.split("/").pop()?.split(".")[0],Y=B.split(`
</details>`};(0,Sr.useEffect)(()=>{let j=[],$=!1;if(p.current&&t.sender!==Pi){p.current.innerHTML="",m.current||(m.current=new lE.Component);let k=g(t.message);if(!$&&(lE.MarkdownRenderer.renderMarkdown(k,p.current,"",m.current),!r)){let z=p.current.querySelectorAll("pre");z.length>0&&z.forEach(V=>{if($)return;let Q=V.querySelector("code");if(!Q)return;let J=Q.textContent||"";try{if(J.trim().startsWith("{")&&J.trim().endsWith("}")){let D=JSON.parse(J);if(D.type==="composer"&&D.path&&(typeof D.content=="string"||typeof D.canvas_json=="object")){let B;typeof D.content=="string"?B=D.content:B=JSON.stringify(D.canvas_json);let q=D.path.trim();q.startsWith("/")&&(q=q.slice(1));let K=document.createElement("div");V.parentNode?.replaceChild(K,V);let H=(0,X5t.createRoot)(K);j.push(H);let ee=e.vault.getAbstractFileByPath(q),U=[];(async()=>{if(ee instanceof lE.TFile){let W=await e.vault.read(ee);U=W5t(W,B,{newlineIsToken:!0})}else{let W=q.split("/").pop()?.split(".")[0],Y=B.split(`
`);(Y[0]===`# ${W}
`||Y[0]===`## ${W}`)&&Y.shift(),B=Y.join(`
`)}$||H.render(Sr.default.createElement(W5t,{note_path:q,note_content:B,note_changes:U}))})()}}}catch(D){console.error("Failed to parse composer JSON:",D)}})}}return()=>{$=!0,setTimeout(()=>{m.current&&(m.current.unload(),m.current=null),j.forEach(k=>{try{k.unmount()}catch{}})},0)}},[t,e,m,r,g]),(0,Sr.useEffect)(()=>{l&&h.current&&S(h.current)},[l]),(0,Sr.useEffect)(()=>{f(t.message)},[t.message]);let S=j=>{j.style.height="auto",j.style.height=`${j.scrollHeight}px`},x=j=>{f(j.target.value),S(j.target)},O=j=>{j.nativeEvent.isComposing||(j.key==="Enter"&&!j.shiftKey?(j.preventDefault(),A()):j.key==="Escape"&&(j.preventDefault(),P()))},P=()=>{c(!1),f(t.message)},E=()=>{c(!0)},A=()=>{c(!1),o&&o(d)},I=()=>{t.sources&&t.sources.length>0&&new ode(e,t.sources).open()},R=()=>{let j=e.workspace.getMostRecentLeaf();if((!j||!(j.view instanceof lE.MarkdownView))&&(j=e.workspace.getLeaf(!1),!j||!(j.view instanceof lE.MarkdownView)))return;let k=j.view.editor.getSelection().length>0;l4(t.message,k)},N=()=>t.content?Sr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-3"},t.content.map((j,$)=>j.type==="text"?Sr.default.createElement("div",{key:$},t.sender===Pi&&l?Sr.default.createElement("textarea",{ref:h,value:d,onChange:x,onKeyDown:O,autoFocus:!0,className:"edit-textarea"}):t.sender===Pi?Sr.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-break-words tw-text-[calc(var(--font-text-size)_-_2px)] tw-font-normal"},t.message):Sr.default.createElement("div",{ref:p,className:t.isErrorMessage?"tw-text-error":""})):j.type==="image_url"?Sr.default.createElement("div",{key:$,className:"message-image-content"},Sr.default.createElement("img",{src:j.image_url.url,alt:"User uploaded image",className:"chat-message-image"})):null)):t.sender===Pi&&l?Sr.default.createElement("textarea",{ref:h,value:d,onChange:x,onKeyDown:O,autoFocus:!0,className:"edit-textarea"}):t.sender===Pi?Sr.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-break-words tw-text-[calc(var(--font-text-size)_-_2px)] tw-font-normal"},t.message):Sr.default.createElement("div",{ref:p,className:t.isErrorMessage?"tw-text-error":""});return Sr.default.createElement("div",{className:"tw-my-1 tw-flex tw-w-full tw-flex-col"},Sr.default.createElement("div",{className:_e("tw-group tw-mx-2 tw-flex tw-gap-2 tw-rounded-md tw-p-2",t.sender===Pi&&"tw-border tw-border-solid tw-border-border")},Sr.default.createElement("div",{className:"tw-w-6 tw-shrink-0"},t.sender===Pi?Sr.default.createElement(M3,null):Sr.default.createElement(a1,null)),Sr.default.createElement("div",{className:"tw-flex tw-max-w-full tw-grow tw-flex-col tw-gap-2 tw-overflow-hidden"},!l&&Sr.default.createElement(oPn,{context:t.context}),Sr.default.createElement("div",{className:"message-content"},N()),!r&&Sr.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between"},Sr.default.createElement("div",{className:"tw-text-xs tw-text-faint"},t.timestamp?.display),Sr.default.createElement(R5t,{message:t,onCopy:b,isCopied:s,onInsertIntoEditor:R,onRegenerate:n,onEdit:E,onDelete:i,onShowSources:I,hasSources:!!(t.sources&&t.sources.length>0)})))))},Gke=iPn;ti();var hd=F(X(),1);function G5t(t,e,{checkForDefaultPrevented:r=!0}={}){return function(o){if(t?.(o),r===!1||!o.defaultPrevented)return e?.(o)}}var Y5t=F(X(),1);function J5t(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Jke(...t){return e=>{let r=!1,n=t.map(o=>{let i=J5t(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():J5t(t[o],null)}}}}function Z5t(...t){return Y5t.useCallback(Jke(...t),t)}var X5t=F(X(),1),cPn=F(ds(),1);var md=F(X(),1);var hz=F(ft(),1),Zke=md.forwardRef((t,e)=>{let{children:r,...n}=t,o=md.Children.toArray(r),i=o.find(sPn);if(i){let a=i.props.children,s=o.map(u=>u===i?md.Children.count(a)>1?md.Children.only(null):md.isValidElement(a)?a.props.children:null:u);return(0,hz.jsx)(Yke,{...n,ref:e,children:md.isValidElement(a)?md.cloneElement(a,void 0,s):null})}return(0,hz.jsx)(Yke,{...n,ref:e,children:r})});Zke.displayName="Slot";var Yke=md.forwardRef((t,e)=>{let{children:r,...n}=t;if(md.isValidElement(r)){let o=lPn(r);return md.cloneElement(r,{...uPn(n,r.props),ref:e?Jke(e,o):o})}return md.Children.count(r)>1?md.Children.only(null):null});Yke.displayName="SlotClone";var aPn=({children:t})=>(0,hz.jsx)(hz.Fragment,{children:t});function sPn(t){return md.isValidElement(t)&&t.type===aPn}function uPn(t,e){let r={...e};for(let n in e){let o=t[n],i=e[n];/^on[A-Z]/.test(n)?o&&i?r[n]=(...s)=>{i(...s),o(...s)}:o&&(r[n]=o):n==="style"?r[n]={...o,...i}:n==="className"&&(r[n]=[o,i].filter(Boolean).join(" "))}return{...t,...r}}function lPn(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,r=e&&"isReactWarning"in e&&e.isReactWarning;return r?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,r=e&&"isReactWarning"in e&&e.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}var Q5t=F(ft(),1),dP Line truncated
`)}$||H.render(Sr.default.createElement(Z5t,{note_path:q,note_content:B,note_changes:U}))})()}}}catch(D){console.error("Failed to parse composer JSON:",D)}})}}return()=>{$=!0,setTimeout(()=>{m.current&&(m.current.unload(),m.current=null),j.forEach(k=>{try{k.unmount()}catch{}})},0)}},[t,e,m,r,g]),(0,Sr.useEffect)(()=>{l&&h.current&&S(h.current)},[l]),(0,Sr.useEffect)(()=>{f(t.message)},[t.message]);let S=j=>{j.style.height="auto",j.style.height=`${j.scrollHeight}px`},x=j=>{f(j.target.value),S(j.target)},O=j=>{j.nativeEvent.isComposing||(j.key==="Enter"&&!j.shiftKey?(j.preventDefault(),A()):j.key==="Escape"&&(j.preventDefault(),P()))},P=()=>{c(!1),f(t.message)},E=()=>{c(!0)},A=()=>{c(!1),o&&o(d)},I=()=>{t.sources&&t.sources.length>0&&new sde(e,t.sources).open()},R=()=>{let j=e.workspace.getMostRecentLeaf();if((!j||!(j.view instanceof lE.MarkdownView))&&(j=e.workspace.getLeaf(!1),!j||!(j.view instanceof lE.MarkdownView)))return;let k=j.view.editor.getSelection().length>0;c4(t.message,k)},N=()=>t.content?Sr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-3"},t.content.map((j,$)=>j.type==="text"?Sr.default.createElement("div",{key:$},t.sender===Pi&&l?Sr.default.createElement("textarea",{ref:h,value:d,onChange:x,onKeyDown:O,autoFocus:!0,className:"edit-textarea"}):t.sender===Pi?Sr.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-break-words tw-text-[calc(var(--font-text-size)_-_2px)] tw-font-normal"},t.message):Sr.default.createElement("div",{ref:p,className:t.isErrorMessage?"tw-text-error":""})):j.type==="image_url"?Sr.default.createElement("div",{key:$,className:"message-image-content"},Sr.default.createElement("img",{src:j.image_url.url,alt:"User uploaded image",className:"chat-message-image"})):null)):t.sender===Pi&&l?Sr.default.createElement("textarea",{ref:h,value:d,onChange:x,onKeyDown:O,autoFocus:!0,className:"edit-textarea"}):t.sender===Pi?Sr.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-break-words tw-text-[calc(var(--font-text-size)_-_2px)] tw-font-normal"},t.message):Sr.default.createElement("div",{ref:p,className:t.isErrorMessage?"tw-text-error":""});return Sr.default.createElement("div",{className:"tw-my-1 tw-flex tw-w-full tw-flex-col"},Sr.default.createElement("div",{className:_e("tw-group tw-mx-2 tw-flex tw-gap-2 tw-rounded-md tw-p-2",t.sender===Pi&&"tw-border tw-border-solid tw-border-border")},Sr.default.createElement("div",{className:"tw-w-6 tw-shrink-0"},t.sender===Pi?Sr.default.createElement(R3,null):Sr.default.createElement(s1,null)),Sr.default.createElement("div",{className:"tw-flex tw-max-w-full tw-grow tw-flex-col tw-gap-2 tw-overflow-hidden"},!l&&Sr.default.createElement(lPn,{context:t.context}),Sr.default.createElement("div",{className:"message-content"},N()),!r&&Sr.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between"},Sr.default.createElement("div",{className:"tw-text-xs tw-text-faint"},t.timestamp?.display),Sr.default.createElement(F5t,{message:t,onCopy:b,isCopied:s,onInsertIntoEditor:R,onRegenerate:n,onEdit:E,onDelete:i,onShowSources:I,hasSources:!!(t.sources&&t.sources.length>0)})))))},Yke=cPn;ti();var hd=F(X(),1);function Q5t(t,e,{checkForDefaultPrevented:r=!0}={}){return function(o){if(t?.(o),r===!1||!o.defaultPrevented)return e?.(o)}}var tWt=F(X(),1);function eWt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Zke(...t){return e=>{let r=!1,n=t.map(o=>{let i=eWt(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():eWt(t[o],null)}}}}function rWt(...t){return tWt.useCallback(Zke(...t),t)}var nWt=F(X(),1),hPn=F(ds(),1);var md=F(X(),1);var gz=F(pt(),1),Qke=md.forwardRef((t,e)=>{let{children:r,...n}=t,o=md.Children.toArray(r),i=o.find(fPn);if(i){let a=i.props.children,s=o.map(u=>u===i?md.Children.count(a)>1?md.Children.only(null):md.isValidElement(a)?a.props.children:null:u);return(0,gz.jsx)(Xke,{...n,ref:e,children:md.isValidElement(a)?md.cloneElement(a,void 0,s):null})}return(0,gz.jsx)(Xke,{...n,ref:e,children:r})});Qke.displayName="Slot";var Xke=md.forwardRef((t,e)=>{let{children:r,...n}=t;if(md.isValidElement(r)){let o=mPn(r);return md.cloneElement(r,{...pPn(n,r.props),ref:e?Zke(e,o):o})}return md.Children.count(r)>1?md.Children.only(null):null});Xke.displayName="SlotClone";var dPn=({children:t})=>(0,gz.jsx)(gz.Fragment,{children:t});function fPn(t){return md.isValidElement(t)&&t.type===dPn}function pPn(t,e){let r={...e};for(let n in e){let o=t[n],i=e[n];/^on[A-Z]/.test(n)?o&&i?r[n]=(...s)=>{i(...s),o(...s)}:o&&(r[n]=o):n==="style"?r[n]={...o,...i}:n==="className"&&(r[n]=[o,i].filter(Boolean).join(" "))}return{...t,...r}}function mPn(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,r=e&&"isReactWarning"in e&&e.isReactWarning;return r?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,r=e&&"isReactWarning"in e&&e.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}var oWt=F(pt(),1),gP Line truncated
.block-interactivity-`.concat(t,` {pointer-events: none;}
.allow-interactivity-`).concat(t,` {pointer-events: all;}
`)},QPn=0,yz=[];function UWt(t){var e=ba.useRef([]),r=ba.useRef([0,0]),n=ba.useRef(),o=ba.useState(QPn++)[0],i=ba.useState(iE)[0],a=ba.useRef(t);ba.useEffect(function(){a.current=t},[t]),ba.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var h=az([t.lockRef.current],(t.shards||[]).map(qWt),!0).filter(Boolean);return h.forEach(function(b){return b.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),h.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(o))})}}},[t.inert,t.lockRef.current,t.shards]);var s=ba.useCallback(function(h,b){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!a.current.allowPinchZoom;var g=fde(h),y=r.current,S="deltaX"in h?h.deltaX:y[0]-g[0],x="deltaY"in h?h.deltaY:y[1]-g[1],O,P=h.target,E=Math.abs(S)>Math.abs(x)?"h":"v";if("touches"in h&&E==="h"&&P.type==="range")return!1;var A=v$e(E,P);if(!A)return!0;if(A?O=E:(O=E==="v"?"h":"v",A=v$e(E,P)),!A)return!1;if(!n.current&&"changedTouches"in h&&(S||x)&&(n.current=O),!O)return!0;var I=n.current||O;return $Wt(I,b,h,I==="h"?S:x,!0)},[]),u=ba.useCallback(function(h){var b=h;if(!(!yz.length||yz[yz.length-1]!==i)){var g="deltaY"in b?BWt(b):fde(b),y=e.current.filter(function(O){return O.name===b.type&&(O.target===b.target||b.target===O.shadowParent)&&ZPn(O.delta,g)})[0];if(y&&y.should){b.cancelable&&b.preventDefault();return}if(!y){var S=(a.current.shards||[]).map(qWt).filter(Boolean).filter(function(O){return O.contains(b.target)}),x=S.length>0?s(b,S[0]):!a.current.noIsolation;x&&b.cancelable&&b.preventDefault()}}},[]),l=ba.useCallback(function(h,b,g,y){var S={name:h,delta:b,target:g,should:y,shadowParent:eEn(g)};e.current.push(S),setTimeout(function(){e.current=e.current.filter(function(x){return x!==S})},1)},[]),c=ba.useCallback(function(h){r.current=fde(h),n.current=void 0},[]),d=ba.useCallback(function(h){l(h.type,BWt(h),h.target,s(h,t.lockRef.current))},[]),f=ba.useCallback(function(h){l(h.type,fde(h),h.target,s(h,t.lockRef.current))},[]);ba.useEffect(function(){return yz.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,rL),document.addEventListener("touchmove",u,rL),document.addEventListener("touchstart",c,rL),function(){yz=yz.filter(function(h){return h!==i}),document.removeEventListener("wheel",u,rL),document.removeEventListener("touchmove",u,rL),document.removeEventListener("touchstart",c,rL)}},[]);var p=t.removeScrollBar,m=t.inert;return ba.createElement(ba.Fragment,null,m?ba.createElement(i,{styles:XPn(o)}):null,p?ba.createElement(WD,{gapMode:t.gapMode}):null)}function eEn(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var zWt=VD(dde,UWt);var HWt=pde.forwardRef(function(t,e){return pde.createElement(l9,yi({},t,{ref:e,sideCar:zWt}))});HWt.classNames=l9.classNames;var w$e=HWt;var bl=F(ft(),1),S$e="Popover",[VWt,Upi]=Yi(S$e,[m$e]),d9=m$e(),[tEn,EM]=VWt(S$e),WWt=t=>{let{__scopePopover:e,children:r,open:n,defaultOpen:o,onOpenChange:i,modal:a=!1}=t,s=d9(e),u=Da.useRef(null),[l,c]=Da.useState(!1),[d=!1,f]=ud({prop:n,defaultProp:o,onChange:i});return(0,bl.jsx)(MWt,{...s,children:(0,bl.jsx)(tEn,{scope:e,contentId:hl(),triggerRef:u,open:d,onOpenChange:f,onOpenToggle:Da.useCallback(()=>f(p=>!p),[f]),hasCustomAnchor:l,onCustomAnchorAdd:Da.useCallback(()=>c(!0),[]),onCustomAnchorRemove:Da.useCallback(()=>c(!1),[]),modal:a,children:r})})};WWt.displayName=S$e;var KWt="PopoverAnchor",rEn=Da.forwardRef((t,e)=>{let{__scopePopover:r,...n}=t,o=EM(KWt,r),i=d9(r),{onCustomAnchorAdd:a,onCustomAnchorRemove:s}=o;return Da.useEffect(()=>(a(),()=>s()),[a,s]),(0,bl.jsx)(g$e,{...i,...n,ref:e})});rEn.displayName=KWt;var GWt="PopoverTrigger",JWt=Da.forwardRef((t,e)=>{let{__scopePopover:r,...n}=t,o=EM(GWt,r),i=d9(r),a=Ab(e,o.triggerRef),s=(0,bl.jsx)(op.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":t9t(o.open),...n,ref:a,onClick:eC(t.onClick,o.onOpenToggle)});return o.hasCustomAnchor?s:(0,bl.jsx)(g$e,{asChild:!0,...i,children:s})});JWt.displayName=GWt;var x$e="PopoverPortal",[nEn,oEn]=VWt(x$e,{forceMount:void 0}),YWt=t=>{let{__scopePopover:e,forceMount:r,children:n,container:o}=t,i=EM(x$e,e);return(0,bl.jsx)(nEn,{scope:e,forceMount:r,children:(0,bl.jsx)(fd,{present:r||i.open,children:(0,bl.jsx)(y$e,{asChild:!0,container:o,children:n})})})};YWt.displayName=x$e;var bz="PopoverContent",ZWt=Da.forwardRef((t,e)=>{let r=oEn(bz,t.__scopePopover),{forceMount:n=r.forceMount,...o}=t,i=EM(bz,t.__scopePopover);return(0,bl.jsx)(fd,{present:n||i.open,children:i.modal?(0,bl.jsx)(iEn,{...o,ref:e}):(0,bl.jsx)(aEn,{...o,ref:e})})});ZWt.displayName=bz;var iEn=Da.forwardRef((t,e)=>{let r=EM(bz,t.__scopePopover),n=Da.useRef(null),o=Ab(e,n),i=Da.useRef(!1);return Da.useEffect(()=>{let a=n.current;if(a)return bM(a)},[]),(0,bl.jsx)(w$e,{as:u9,a Line truncated
`)},oEn=0,bz=[];function KWt(t){var e=ba.useRef([]),r=ba.useRef([0,0]),n=ba.useRef(),o=ba.useState(oEn++)[0],i=ba.useState(iE)[0],a=ba.useRef(t);ba.useEffect(function(){a.current=t},[t]),ba.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var h=sz([t.lockRef.current],(t.shards||[]).map(WWt),!0).filter(Boolean);return h.forEach(function(b){return b.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),h.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(o))})}}},[t.inert,t.lockRef.current,t.shards]);var s=ba.useCallback(function(h,b){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!a.current.allowPinchZoom;var g=hde(h),y=r.current,S="deltaX"in h?h.deltaX:y[0]-g[0],x="deltaY"in h?h.deltaY:y[1]-g[1],O,P=h.target,E=Math.abs(S)>Math.abs(x)?"h":"v";if("touches"in h&&E==="h"&&P.type==="range")return!1;var A=S$e(E,P);if(!A)return!0;if(A?O=E:(O=E==="v"?"h":"v",A=S$e(E,P)),!A)return!1;if(!n.current&&"changedTouches"in h&&(S||x)&&(n.current=O),!O)return!0;var I=n.current||O;return HWt(I,b,h,I==="h"?S:x,!0)},[]),u=ba.useCallback(function(h){var b=h;if(!(!bz.length||bz[bz.length-1]!==i)){var g="deltaY"in b?VWt(b):hde(b),y=e.current.filter(function(O){return O.name===b.type&&(O.target===b.target||b.target===O.shadowParent)&&rEn(O.delta,g)})[0];if(y&&y.should){b.cancelable&&b.preventDefault();return}if(!y){var S=(a.current.shards||[]).map(WWt).filter(Boolean).filter(function(O){return O.contains(b.target)}),x=S.length>0?s(b,S[0]):!a.current.noIsolation;x&&b.cancelable&&b.preventDefault()}}},[]),l=ba.useCallback(function(h,b,g,y){var S={name:h,delta:b,target:g,should:y,shadowParent:iEn(g)};e.current.push(S),setTimeout(function(){e.current=e.current.filter(function(x){return x!==S})},1)},[]),c=ba.useCallback(function(h){r.current=hde(h),n.current=void 0},[]),d=ba.useCallback(function(h){l(h.type,VWt(h),h.target,s(h,t.lockRef.current))},[]),f=ba.useCallback(function(h){l(h.type,hde(h),h.target,s(h,t.lockRef.current))},[]);ba.useEffect(function(){return bz.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,nL),document.addEventListener("touchmove",u,nL),document.addEventListener("touchstart",c,nL),function(){bz=bz.filter(function(h){return h!==i}),document.removeEventListener("wheel",u,nL),document.removeEventListener("touchmove",u,nL),document.removeEventListener("touchstart",c,nL)}},[]);var p=t.removeScrollBar,m=t.inert;return ba.createElement(ba.Fragment,null,m?ba.createElement(i,{styles:nEn(o)}):null,p?ba.createElement(KD,{gapMode:t.gapMode}):null)}function iEn(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var GWt=WD(mde,KWt);var JWt=gde.forwardRef(function(t,e){return gde.createElement(c9,yi({},t,{ref:e,sideCar:GWt}))});JWt.classNames=c9.classNames;var x$e=JWt;var bl=F(pt(),1),C$e="Popover",[YWt,Zpi]=Yi(C$e,[g$e]),f9=g$e(),[aEn,EM]=YWt(C$e),ZWt=t=>{let{__scopePopover:e,children:r,open:n,defaultOpen:o,onOpenChange:i,modal:a=!1}=t,s=f9(e),u=Da.useRef(null),[l,c]=Da.useState(!1),[d=!1,f]=ud({prop:n,defaultProp:o,onChange:i});return(0,bl.jsx)(LWt,{...s,children:(0,bl.jsx)(aEn,{scope:e,contentId:hl(),triggerRef:u,open:d,onOpenChange:f,onOpenToggle:Da.useCallback(()=>f(p=>!p),[f]),hasCustomAnchor:l,onCustomAnchorAdd:Da.useCallback(()=>c(!0),[]),onCustomAnchorRemove:Da.useCallback(()=>c(!1),[]),modal:a,children:r})})};ZWt.displayName=C$e;var XWt="PopoverAnchor",sEn=Da.forwardRef((t,e)=>{let{__scopePopover:r,...n}=t,o=EM(XWt,r),i=f9(r),{onCustomAnchorAdd:a,onCustomAnchorRemove:s}=o;return Da.useEffect(()=>(a(),()=>s()),[a,s]),(0,bl.jsx)(b$e,{...i,...n,ref:e})});sEn.displayName=XWt;var QWt="PopoverTrigger",e9t=Da.forwardRef((t,e)=>{let{__scopePopover:r,...n}=t,o=EM(QWt,r),i=f9(r),a=Ab(e,o.triggerRef),s=(0,bl.jsx)(op.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":a9t(o.open),...n,ref:a,onClick:tC(t.onClick,o.onOpenToggle)});return o.hasCustomAnchor?s:(0,bl.jsx)(b$e,{asChild:!0,...i,children:s})});e9t.displayName=QWt;var O$e="PopoverPortal",[uEn,lEn]=YWt(O$e,{forceMount:void 0}),t9t=t=>{let{__scopePopover:e,forceMount:r,children:n,container:o}=t,i=EM(O$e,e);return(0,bl.jsx)(uEn,{scope:e,forceMount:r,children:(0,bl.jsx)(fd,{present:r||i.open,children:(0,bl.jsx)(_$e,{asChild:!0,container:o,children:n})})})};t9t.displayName=O$e;var _z="PopoverContent",r9t=Da.forwardRef((t,e)=>{let r=lEn(_z,t.__scopePopover),{forceMount:n=r.forceMount,...o}=t,i=EM(_z,t.__scopePopover);return(0,bl.jsx)(fd,{present:n||i.open,children:i.modal?(0,bl.jsx)(cEn,{...o,ref:e}):(0,bl.jsx)(dEn,{...o,ref:e})})});r9t.displayName=_z;var cEn=Da.forwardRef((t,e)=>{let r=EM(_z,t.__scopePopover),n=Da.useRef(null),o=Ab(e,n),i=Da.useRef(!1);return Da.useEffect(()=>{let a=n.current;if(a)return bM(a)},[]),(0,bl.jsx)(x$e,{as:l9,a Line truncated
`).map(y=>{if(!y.trim())return y;try{return new URL(y.trim()),y}catch{return y}});p("contextSource.webUrls",g.join(`
`))},placeholder:"Enter web URLs, one per line",className:"tw-min-h-20 tw-w-full"})),Kt.default.createElement(Yn,{label:"YouTube URLs"},Kt.default.createElement(yE,{value:u.contextSource?.youtubeUrls,onChange:h=>{let g=h.target.value.split(`
`).map(y=>{if(!y.trim())return y;try{let S=new URL(y.trim());return S.hostname.includes("youtube.com")||S.hostname.includes("youtu.be"),y}catch{return y}});p("contextSource.youtubeUrls",g.join(`
`))},placeholder:"Enter YouTube URLs, one per line",className:"tw-min-h-20 tw-w-full"})))),Kt.default.createElement("div",{className:"tw-mt-4 tw-flex tw-items-center tw-justify-end tw-gap-2"},Kt.default.createElement(ge,{variant:"ghost",onClick:r,disabled:o},"Cancel"),Kt.default.createElement(ge,{onClick:m,disabled:o||!f()},o?"Saving...":"Save")))}var P9=class extends $z.Modal{constructor(r,n,o){super(r);this.onSave=n;this.initialProject=o}onOpen(){let{contentEl:r}=this;this.root=(0,JKt.createRoot)(r);let n=async i=>{await this.onSave(i),this.close()},o=()=>{this.close()};this.root.render(Kt.default.createElement(iAn,{initialProject:this.initialProject,onSave:n,onCancel:o}))}onClose(){this.root.unmount()}};ti();var ji=F(X());var ct=F(X(),1),IBe=F(ds(),1);var ns=F(X(),1);var lBe=F(ft(),1),aAn="DismissableLayer",uBe="dismissableLayer.update",sAn="dismissableLayer.pointerDownOutside",uAn="dismissableLayer.focusOutside",YKt,XKt=ns.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),cBe=ns.forwardRef((t,e)=>{let{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:n,onPointerDownOutside:o,onFocusOutside:i,onInteractOutside:a,onDismiss:s,...u}=t,l=ns.useContext(XKt),[c,d]=ns.useState(null),f=c?.ownerDocument??globalThis?.document,[,p]=ns.useState({}),m=Ri(e,E=>d(E)),h=Array.from(l.layers),[b]=[...l.layersWithOutsidePointerEventsDisabled].slice(-1),g=h.indexOf(b),y=c?h.indexOf(c):-1,S=l.layersWithOutsidePointerEventsDisabled.size>0,x=y>=g,O=dAn(E=>{let A=E.target,I=[...l.branches].some(R=>R.contains(A));!x||I||(o?.(E),a?.(E),E.defaultPrevented||s?.())},f),P=fAn(E=>{let A=E.target;[...l.branches].some(R=>R.contains(A))||(i?.(E),a?.(E),E.defaultPrevented||s?.())},f);return oM(E=>{y===l.layers.size-1&&(n?.(E),!E.defaultPrevented&&s&&(E.preventDefault(),s()))},f),ns.useEffect(()=>{if(c)return r&&(l.layersWithOutsidePointerEventsDisabled.size===0&&(YKt=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),l.layersWithOutsidePointerEventsDisabled.add(c)),l.layers.add(c),ZKt(),()=>{r&&l.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=YKt)}},[c,f,r,l]),ns.useEffect(()=>()=>{c&&(l.layers.delete(c),l.layersWithOutsidePointerEventsDisabled.delete(c),ZKt())},[c,l]),ns.useEffect(()=>{let E=()=>p({});return document.addEventListener(uBe,E),()=>document.removeEventListener(uBe,E)},[]),(0,lBe.jsx)(ho.div,{...u,ref:m,style:{pointerEvents:S?x?"auto":"none":void 0,...t.style},onFocusCapture:xi(t.onFocusCapture,P.onFocusCapture),onBlurCapture:xi(t.onBlurCapture,P.onBlurCapture),onPointerDownCapture:xi(t.onPointerDownCapture,O.onPointerDownCapture)})});cBe.displayName=aAn;var lAn="DismissableLayerBranch",cAn=ns.forwardRef((t,e)=>{let r=ns.useContext(XKt),n=ns.useRef(null),o=Ri(e,n);return ns.useEffect(()=>{let i=n.current;if(i)return r.branches.add(i),()=>{r.branches.delete(i)}},[r.branches]),(0,lBe.jsx)(ho.div,{...t,ref:o})});cAn.displayName=lAn;function dAn(t,e=globalThis?.document){let r=Ur(t),n=ns.useRef(!1),o=ns.useRef(()=>{});return ns.useEffect(()=>{let i=s=>{if(s.target&&!n.current){let l=function(){QKt(sAn,r,c,{discrete:!0})};var u=l;let c={originalEvent:s};s.pointerType==="touch"?(e.removeEventListener("click",o.current),o.current=l,e.addEventListener("click",o.current,{once:!0})):l()}else e.removeEventListener("click",o.current);n.current=!1},a=window.setTimeout(()=>{e.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(a),e.removeEventListener("pointerdown",i),e.removeEventListener("click",o.current)}},[e,r]),{onPointerDownCapture:()=>n.current=!0}}function fAn(t,e=globalThis?.document){let r=Ur(t),n=ns.useRef(!1);return ns.useEffect(()=>{let o=i=>{i.target&&!n.current&&QKt(uAn,r,{originalEvent:i},{discrete:!1})};return e.addEventListener("focusin",o),()=>e.removeEventListener("focusin",o)},[e,r]),{onFocusCapture:()=>n.current=!0,onBlurCapture:()=>n.current=!1}}function ZKt(){let t=new CustomEvent(uBe);document.dispatchEvent(t)}function QKt(t,e,r,{discrete:n}){let o=r.originalEvent.target,i=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:r});e&&o.addEventListener(t,e,{once:!0}),n?EKt(o,i):o.dispatchEvent(i)}var ny=F(X(),1);var oGt=F(ft(),1),dBe="focusScope.autoFocusOnMount",fBe="focusScope.autoFocusOnUnmount",eGt={bubbles:!1,cancelable:!0},pAn="FocusScope",pBe=ny.forwardRef((t,e)=>{let{loop:r=!1,trapped:n=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...a}=t,[s,u]=ny.useState(null),l=Ur(o),c=Ur(i),d=ny.useRef(null),f=Ri(e,h=>u(h)),p=ny.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;ny.useEffect(()=>{if(n){let y=function(P){if(p.paused||!s)return;let E=P.target;s.contains(E)?d.current=E:NM(d.current,{select:!0})},S=function(P){if(p.paused||!s)return;let E=P.relatedTarget;E!==null&&(s.contains(E)||NM(d.current,{select:!0}))},x=function(P){if(document.activeElement===document.body)for(let A of P)A.removedNodes.length>0&&NM(s)};var h=y,b=S,g=x;document.addEventListener("focusin",y),document.addEventListe Line truncated
`))},placeholder:"Enter YouTube URLs, one per line",className:"tw-min-h-20 tw-w-full"})))),Kt.default.createElement("div",{className:"tw-mt-4 tw-flex tw-items-center tw-justify-end tw-gap-2"},Kt.default.createElement(ge,{variant:"ghost",onClick:r,disabled:o},"Cancel"),Kt.default.createElement(ge,{onClick:m,disabled:o||!f()},o?"Saving...":"Save")))}var E9=class extends Bz.Modal{constructor(r,n,o){super(r);this.onSave=n;this.initialProject=o}onOpen(){let{contentEl:r}=this;this.root=(0,eGt.createRoot)(r);let n=async i=>{await this.onSave(i),this.close()},o=()=>{this.close()};this.root.render(Kt.default.createElement(cAn,{initialProject:this.initialProject,onSave:n,onCancel:o}))}onClose(){this.root.unmount()}};ti();var ji=F(X());var ct=F(X(),1),RBe=F(ds(),1);var ns=F(X(),1);var dBe=F(pt(),1),dAn="DismissableLayer",cBe="dismissableLayer.update",fAn="dismissableLayer.pointerDownOutside",pAn="dismissableLayer.focusOutside",tGt,nGt=ns.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),fBe=ns.forwardRef((t,e)=>{let{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:n,onPointerDownOutside:o,onFocusOutside:i,onInteractOutside:a,onDismiss:s,...u}=t,l=ns.useContext(nGt),[c,d]=ns.useState(null),f=c?.ownerDocument??globalThis?.document,[,p]=ns.useState({}),m=Ri(e,E=>d(E)),h=Array.from(l.layers),[b]=[...l.layersWithOutsidePointerEventsDisabled].slice(-1),g=h.indexOf(b),y=c?h.indexOf(c):-1,S=l.layersWithOutsidePointerEventsDisabled.size>0,x=y>=g,O=gAn(E=>{let A=E.target,I=[...l.branches].some(R=>R.contains(A));!x||I||(o?.(E),a?.(E),E.defaultPrevented||s?.())},f),P=yAn(E=>{let A=E.target;[...l.branches].some(R=>R.contains(A))||(i?.(E),a?.(E),E.defaultPrevented||s?.())},f);return oM(E=>{y===l.layers.size-1&&(n?.(E),!E.defaultPrevented&&s&&(E.preventDefault(),s()))},f),ns.useEffect(()=>{if(c)return r&&(l.layersWithOutsidePointerEventsDisabled.size===0&&(tGt=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),l.layersWithOutsidePointerEventsDisabled.add(c)),l.layers.add(c),rGt(),()=>{r&&l.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=tGt)}},[c,f,r,l]),ns.useEffect(()=>()=>{c&&(l.layers.delete(c),l.layersWithOutsidePointerEventsDisabled.delete(c),rGt())},[c,l]),ns.useEffect(()=>{let E=()=>p({});return document.addEventListener(cBe,E),()=>document.removeEventListener(cBe,E)},[]),(0,dBe.jsx)(ho.div,{...u,ref:m,style:{pointerEvents:S?x?"auto":"none":void 0,...t.style},onFocusCapture:xi(t.onFocusCapture,P.onFocusCapture),onBlurCapture:xi(t.onBlurCapture,P.onBlurCapture),onPointerDownCapture:xi(t.onPointerDownCapture,O.onPointerDownCapture)})});fBe.displayName=dAn;var mAn="DismissableLayerBranch",hAn=ns.forwardRef((t,e)=>{let r=ns.useContext(nGt),n=ns.useRef(null),o=Ri(e,n);return ns.useEffect(()=>{let i=n.current;if(i)return r.branches.add(i),()=>{r.branches.delete(i)}},[r.branches]),(0,dBe.jsx)(ho.div,{...t,ref:o})});hAn.displayName=mAn;function gAn(t,e=globalThis?.document){let r=Ur(t),n=ns.useRef(!1),o=ns.useRef(()=>{});return ns.useEffect(()=>{let i=s=>{if(s.target&&!n.current){let l=function(){oGt(fAn,r,c,{discrete:!0})};var u=l;let c={originalEvent:s};s.pointerType==="touch"?(e.removeEventListener("click",o.current),o.current=l,e.addEventListener("click",o.current,{once:!0})):l()}else e.removeEventListener("click",o.current);n.current=!1},a=window.setTimeout(()=>{e.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(a),e.removeEventListener("pointerdown",i),e.removeEventListener("click",o.current)}},[e,r]),{onPointerDownCapture:()=>n.current=!0}}function yAn(t,e=globalThis?.document){let r=Ur(t),n=ns.useRef(!1);return ns.useEffect(()=>{let o=i=>{i.target&&!n.current&&oGt(pAn,r,{originalEvent:i},{discrete:!1})};return e.addEventListener("focusin",o),()=>e.removeEventListener("focusin",o)},[e,r]),{onFocusCapture:()=>n.current=!0,onBlurCapture:()=>n.current=!1}}function rGt(){let t=new CustomEvent(cBe);document.dispatchEvent(t)}function oGt(t,e,r,{discrete:n}){let o=r.originalEvent.target,i=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:r});e&&o.addEventListener(t,e,{once:!0}),n?RKt(o,i):o.dispatchEvent(i)}var ny=F(X(),1);var lGt=F(pt(),1),pBe="focusScope.autoFocusOnMount",mBe="focusScope.autoFocusOnUnmount",iGt={bubbles:!1,cancelable:!0},bAn="FocusScope",hBe=ny.forwardRef((t,e)=>{let{loop:r=!1,trapped:n=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...a}=t,[s,u]=ny.useState(null),l=Ur(o),c=Ur(i),d=ny.useRef(null),f=Ri(e,h=>u(h)),p=ny.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;ny.useEffect(()=>{if(n){let y=function(P){if(p.paused||!s)return;let E=P.target;s.contains(E)?d.current=E:NM(d.current,{select:!0})},S=function(P){if(p.paused||!s)return;let E=P.relatedTarget;E!==null&&(s.contains(E)||NM(d.current,{select:!0}))},x=function(P){if(document.activeElement===document.body)for(let A of P)A.removedNodes.length>0&&NM(s)};var h=y,b=S,g=x;document.addEventListener("focusin",y),document.addEventListe Line truncated
.block-interactivity-`.concat(t,` {pointer-events: none;}
.allow-interactivity-`).concat(t,` {pointer-events: all;}
`)},HAn=0,qz=[];function NGt(t){var e=_a.useRef([]),r=_a.useRef([0,0]),n=_a.useRef(),o=_a.useState(HAn++)[0],i=_a.useState(iE)[0],a=_a.useRef(t);_a.useEffect(function(){a.current=t},[t]),_a.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var h=az([t.lockRef.current],(t.shards||[]).map(jGt),!0).filter(Boolean);return h.forEach(function(b){return b.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),h.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(o))})}}},[t.inert,t.lockRef.current,t.shards]);var s=_a.useCallback(function(h,b){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!a.current.allowPinchZoom;var g=Zde(h),y=r.current,S="deltaX"in h?h.deltaX:y[0]-g[0],x="deltaY"in h?h.deltaY:y[1]-g[1],O,P=h.target,E=Math.abs(S)>Math.abs(x)?"h":"v";if("touches"in h&&E==="h"&&P.type==="range")return!1;var A=CBe(E,P);if(!A)return!0;if(A?O=E:(O=E==="v"?"h":"v",A=CBe(E,P)),!A)return!1;if(!n.current&&"changedTouches"in h&&(S||x)&&(n.current=O),!O)return!0;var I=n.current||O;return MGt(I,b,h,I==="h"?S:x,!0)},[]),u=_a.useCallback(function(h){var b=h;if(!(!qz.length||qz[qz.length-1]!==i)){var g="deltaY"in b?RGt(b):Zde(b),y=e.current.filter(function(O){return O.name===b.type&&(O.target===b.target||b.target===O.shadowParent)&&UAn(O.delta,g)})[0];if(y&&y.should){b.cancelable&&b.preventDefault();return}if(!y){var S=(a.current.shards||[]).map(jGt).filter(Boolean).filter(function(O){return O.contains(b.target)}),x=S.length>0?s(b,S[0]):!a.current.noIsolation;x&&b.cancelable&&b.preventDefault()}}},[]),l=_a.useCallback(function(h,b,g,y){var S={name:h,delta:b,target:g,should:y,shadowParent:VAn(g)};e.current.push(S),setTimeout(function(){e.current=e.current.filter(function(x){return x!==S})},1)},[]),c=_a.useCallback(function(h){r.current=Zde(h),n.current=void 0},[]),d=_a.useCallback(function(h){l(h.type,RGt(h),h.target,s(h,t.lockRef.current))},[]),f=_a.useCallback(function(h){l(h.type,Zde(h),h.target,s(h,t.lockRef.current))},[]);_a.useEffect(function(){return qz.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,lL),document.addEventListener("touchmove",u,lL),document.addEventListener("touchstart",c,lL),function(){qz=qz.filter(function(h){return h!==i}),document.removeEventListener("wheel",u,lL),document.removeEventListener("touchmove",u,lL),document.removeEventListener("touchstart",c,lL)}},[]);var p=t.removeScrollBar,m=t.inert;return _a.createElement(_a.Fragment,null,m?_a.createElement(i,{styles:zAn(o)}):null,p?_a.createElement(WD,{gapMode:t.gapMode}):null)}function VAn(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var DGt=VD(Yde,NGt);var LGt=Xde.forwardRef(function(t,e){return Xde.createElement(E9,yi({},t,{ref:e,sideCar:DGt}))});LGt.classNames=E9.classNames;var A9=LGt;var lr=F(ft(),1),WAn=[" ","Enter","ArrowUp","ArrowDown"],KAn=[" ","Enter"],M9="Select",[efe,tfe,GAn]=Kde(M9),[Uz,vbi]=Yi(M9,[GAn,gBe]),rfe=gBe(),[JAn,LM]=Uz(M9),[YAn,ZAn]=Uz(M9),FGt=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=rfe(e),[b,g]=ct.useState(null),[y,S]=ct.useState(null),[x,O]=ct.useState(!1),P=nM(l),[E=!1,A]=ud({prop:n,defaultProp:o,onChange:i}),[I,R]=ud({prop:a,defaultProp:s,onChange:u}),N=ct.useRef(null),j=b?m||!!b.closest("form"):!0,[$,k]=ct.useState(new Set),z=Array.from($).map(V=>V.props.value).join(";");return(0,lr.jsx)(vGt,{...h,children:(0,lr.jsxs)(JAn,{required:p,scope:e,trigger:b,onTriggerChange:g,valueNode:y,onValueNodeChange:S,valueNodeHasChildren:x,onValueNodeHasChildrenChange:O,contentId:hl(),value:I,onValueChange:R,open:E,onOpenChange:A,dir:P,triggerPointerDownPosRef:N,disabled:f,children:[(0,lr.jsx)(efe.Provider,{scope:e,children:(0,lr.jsx)(YAn,{scope:t.__scopeSelect,onNativeOptionAdd:ct.useCallback(V=>{k(Q=>new Set(Q).add(V))},[]),onNativeOptionRemove:ct.useCallback(V=>{k(Q=>{let J=new Set(Q);return J.delete(V),J})},[]),children:r})}),j?(0,lr.jsxs)(uJt,{"aria-hidden":!0,required:p,tabIndex:-1,name:c,autoComplete:d,value:I,onChange:V=>R(V.target.value),disabled:f,form:m,children:[I===void 0?(0,lr.jsx)("option",{value:""}):null,Array.from($)]},z):null]})})};FGt.displayName=M9;var kGt="SelectTrigger",$Gt=ct.forwardRef((t,e)=>{let{__scopeSelect:r,disabled:n=!1,...o}=t,i=rfe(r),a=LM(kGt,r),s=a.disabled||n,u=Ri(e,a.onTriggerChange),l=tfe(r),c=ct.useRef("touch"),[d,f,p]=lJt(h=>{let b=l().filter(S=>!S.disabled),g=b.find(S=>S.value===a.value),y=cJt(b,h,g);y!==void 0&&a.onValueChange(y.value)}),m=h=>{s||(a.onOpenChange(!0),p()),h&&(a.triggerPointerDownPosRef.current={x:Math.round(h.pageX),y:Math.round(h.pageY)})};return(0,lr.jsx)(wGt,{asChild:!0,...i,children:(0,lr.jsx)(ho.button,{type:"button",role:"combobox","aria-controls":a.contentId,"ar Line truncated
`)},JAn=0,Uz=[];function $Gt(t){var e=_a.useRef([]),r=_a.useRef([0,0]),n=_a.useRef(),o=_a.useState(JAn++)[0],i=_a.useState(iE)[0],a=_a.useRef(t);_a.useEffect(function(){a.current=t},[t]),_a.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var h=sz([t.lockRef.current],(t.shards||[]).map(kGt),!0).filter(Boolean);return h.forEach(function(b){return b.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),h.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(o))})}}},[t.inert,t.lockRef.current,t.shards]);var s=_a.useCallback(function(h,b){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!a.current.allowPinchZoom;var g=efe(h),y=r.current,S="deltaX"in h?h.deltaX:y[0]-g[0],x="deltaY"in h?h.deltaY:y[1]-g[1],O,P=h.target,E=Math.abs(S)>Math.abs(x)?"h":"v";if("touches"in h&&E==="h"&&P.type==="range")return!1;var A=PBe(E,P);if(!A)return!0;if(A?O=E:(O=E==="v"?"h":"v",A=PBe(E,P)),!A)return!1;if(!n.current&&"changedTouches"in h&&(S||x)&&(n.current=O),!O)return!0;var I=n.current||O;return LGt(I,b,h,I==="h"?S:x,!0)},[]),u=_a.useCallback(function(h){var b=h;if(!(!Uz.length||Uz[Uz.length-1]!==i)){var g="deltaY"in b?FGt(b):efe(b),y=e.current.filter(function(O){return O.name===b.type&&(O.target===b.target||b.target===O.shadowParent)&&KAn(O.delta,g)})[0];if(y&&y.should){b.cancelable&&b.preventDefault();return}if(!y){var S=(a.current.shards||[]).map(kGt).filter(Boolean).filter(function(O){return O.contains(b.target)}),x=S.length>0?s(b,S[0]):!a.current.noIsolation;x&&b.cancelable&&b.preventDefault()}}},[]),l=_a.useCallback(function(h,b,g,y){var S={name:h,delta:b,target:g,should:y,shadowParent:YAn(g)};e.current.push(S),setTimeout(function(){e.current=e.current.filter(function(x){return x!==S})},1)},[]),c=_a.useCallback(function(h){r.current=efe(h),n.current=void 0},[]),d=_a.useCallback(function(h){l(h.type,FGt(h),h.target,s(h,t.lockRef.current))},[]),f=_a.useCallback(function(h){l(h.type,efe(h),h.target,s(h,t.lockRef.current))},[]);_a.useEffect(function(){return Uz.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,cL),document.addEventListener("touchmove",u,cL),document.addEventListener("touchstart",c,cL),function(){Uz=Uz.filter(function(h){return h!==i}),document.removeEventListener("wheel",u,cL),document.removeEventListener("touchmove",u,cL),document.removeEventListener("touchstart",c,cL)}},[]);var p=t.removeScrollBar,m=t.inert;return _a.createElement(_a.Fragment,null,m?_a.createElement(i,{styles:GAn(o)}):null,p?_a.createElement(KD,{gapMode:t.gapMode}):null)}function YAn(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var BGt=WD(Qde,$Gt);var qGt=tfe.forwardRef(function(t,e){return tfe.createElement(T9,yi({},t,{ref:e,sideCar:BGt}))});qGt.classNames=T9.classNames;var I9=qGt;var lr=F(pt(),1),ZAn=[" ","Enter","ArrowUp","ArrowDown"],XAn=[" ","Enter"],R9="Select",[nfe,ofe,QAn]=Yde(R9),[zz,Abi]=Yi(R9,[QAn,bBe]),ife=bBe(),[eIn,LM]=zz(R9),[tIn,rIn]=zz(R9),UGt=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=ife(e),[b,g]=ct.useState(null),[y,S]=ct.useState(null),[x,O]=ct.useState(!1),P=nM(l),[E=!1,A]=ud({prop:n,defaultProp:o,onChange:i}),[I,R]=ud({prop:a,defaultProp:s,onChange:u}),N=ct.useRef(null),j=b?m||!!b.closest("form"):!0,[$,k]=ct.useState(new Set),z=Array.from($).map(V=>V.props.value).join(";");return(0,lr.jsx)(OGt,{...h,children:(0,lr.jsxs)(eIn,{required:p,scope:e,trigger:b,onTriggerChange:g,valueNode:y,onValueNodeChange:S,valueNodeHasChildren:x,onValueNodeHasChildrenChange:O,contentId:hl(),value:I,onValueChange:R,open:E,onOpenChange:A,dir:P,triggerPointerDownPosRef:N,disabled:f,children:[(0,lr.jsx)(nfe.Provider,{scope:e,children:(0,lr.jsx)(tIn,{scope:t.__scopeSelect,onNativeOptionAdd:ct.useCallback(V=>{k(Q=>new Set(Q).add(V))},[]),onNativeOptionRemove:ct.useCallback(V=>{k(Q=>{let J=new Set(Q);return J.delete(V),J})},[]),children:r})}),j?(0,lr.jsxs)(pJt,{"aria-hidden":!0,required:p,tabIndex:-1,name:c,autoComplete:d,value:I,onChange:V=>R(V.target.value),disabled:f,form:m,children:[I===void 0?(0,lr.jsx)("option",{value:""}):null,Array.from($)]},z):null]})})};UGt.displayName=R9;var zGt="SelectTrigger",HGt=ct.forwardRef((t,e)=>{let{__scopeSelect:r,disabled:n=!1,...o}=t,i=ife(r),a=LM(zGt,r),s=a.disabled||n,u=Ri(e,a.onTriggerChange),l=ofe(r),c=ct.useRef("touch"),[d,f,p]=mJt(h=>{let b=l().filter(S=>!S.disabled),g=b.find(S=>S.value===a.value),y=hJt(b,h,g);y!==void 0&&a.onValueChange(y.value)}),m=h=>{s||(a.onOpenChange(!0),p()),h&&(a.triggerPointerDownPosRef.current={x:Math.round(h.pageX),y:Math.round(h.pageY)})};return(0,lr.jsx)(PGt,{asChild:!0,...i,children:(0,lr.jsx)(ho.button,{type:"button",role:"combobox","aria-controls":a.contentId,"ar Line truncated
<output_format>
`+ir+`
</output_format>`);let{processedPrompt:ea,includedFiles:ta}=await lce(Je||"","",U.vault,U.workspace.getActiveFile()),xc=f==="copilot_plus"?await q.processUrls(h||""):{urlContext:"",imageUrls:[]},Cd=new Set(ta.map(_f=>_f.path)),qi=await K.processContextNotes(Cd,o,U.vault,se,I,ce,f),lp=K.processSelectedTextContexts(),yf=ea+xc.urlContext+qi+lp,bf=h;te&&(bf+=" "+te.join(`
`));let Sn={message:yf,originalMessage:bf,sender:Pi,isVisible:!1,timestamp:Pe,content:oe,context:{notes:se,urls:f==="copilot_plus"?[...et||[],...xc.imageUrls]:et||[],selectedTextContexts:z}};l(Sn),h&&n(h),a.autosaveChat&&Y(),await BBe(Sn,e,l,m,y,{debug:a.debug,updateLoadingMessage:P}),a.autosaveChat&&Y(),x(!1),P(t_.DEFAULT)},Y=(0,xr.useCallback)(async()=>{if(!U){console.error("App instance is not available.");return}let te=t.getMessages().filter(Pe=>Pe.isVisible);if(te.length===0){new pm.Notice("No messages to save.");return}let et=te[0].timestamp?.epoch||Date.now(),Re=te.map(Pe=>`**${Pe.sender}**: ${Pe.message}
</output_format>`);let{processedPrompt:ea,includedFiles:ta}=await fce(Je||"","",U.vault,U.workspace.getActiveFile()),xc=f==="copilot_plus"?await q.processUrls(h||""):{urlContext:"",imageUrls:[]},Cd=new Set(ta.map(_f=>_f.path)),qi=await K.processContextNotes(Cd,o,U.vault,se,I,ce,f),lp=K.processSelectedTextContexts(),yf=ea+xc.urlContext+qi+lp,bf=h;te&&(bf+=" "+te.join(`
`));let xn={message:yf,originalMessage:bf,sender:Pi,isVisible:!1,timestamp:Pe,content:oe,context:{notes:se,urls:f==="copilot_plus"?[...et||[],...xc.imageUrls]:et||[],selectedTextContexts:z}};l(xn),h&&n(h),a.autosaveChat&&Y(),await UBe(xn,e,l,m,y,{debug:a.debug,updateLoadingMessage:P}),a.autosaveChat&&Y(),x(!1),P(t_.DEFAULT)},Y=(0,xr.useCallback)(async()=>{if(!U){console.error("App instance is not available.");return}let te=t.getMessages().filter(Pe=>Pe.isVisible);if(te.length===0){new pm.Notice("No messages to save.");return}let et=te[0].timestamp?.epoch||Date.now(),Re=te.map(Pe=>`**${Pe.sender}**: ${Pe.message}
[Timestamp: ${Pe.timestamp?.display}]`).join(`
`);try{U.vault.getAbstractFileByPath(a.defaultSaveFolder)||await U.vault.createFolder(a.defaultSaveFolder);let{fileName:oe}=Vl(new Date(et)),se=te.find(qi=>qi.sender===Pi),ce=se?se.message.split(/\s+/).slice(0,10).join(" ").replace(/[\\/:*?"<>|]/g,"").trim():"Untitled Chat",Ce=a.defaultConversationNoteName||"{$date}_{$time}__{$topic}";Ce=Ce.replace("{$topic}",ce.slice(0,100).replace(/\s+/g,"_")).replace("{$date}",oe.split("_")[0]).replace("{$time}",oe.split("_")[1]);let Je=Ce.replace(/[\\/:*?"<>|]/g,"_"),ir=Mc(),ea=ir?`${ir.id}__`:"",ta=`${a.defaultSaveFolder}/${ea}${Je}.md`,xc=`---
@@ -1022,24 +1022,24 @@ tags:
${ir?` - project-${ir.name}`:""}
---
${Re}`,Cd=U.vault.getAbstractFileByPath(ta);Cd instanceof pm.TFile?await U.vault.modify(Cd,xc):(await U.vault.create(ta,xc),new pm.Notice(`Chat saved as note: ${ta}`))}catch(Pe){console.error("Error saving chat as note:",ei(Pe)),new pm.Notice("Failed to save chat as note. Check console for details.")}},[U,t,d,a.defaultConversationTag,a.defaultSaveFolder,a.defaultConversationNoteName]),ae=(0,xr.useCallback)(te=>{g&&(a.debug&&console.log(`stopping generation..., reason: ${te}`),g.abort(te),x(!1),P(t_.DEFAULT))},[g,a.debug]),Oe=(0,xr.useCallback)(async te=>{let et=te-1;if(et<0||u[et].sender!==Pi){new pm.Notice("Cannot regenerate the first message or a user message.");return}let Re=u[et],Pe=u.slice(0,te);c(),Pe.forEach(l),e.memoryManager.clearChatMemory();for(let oe=0;oe<Pe.length;oe+=2){let se=Pe[oe],ce=Pe[oe+1];se&&ce&&await e.memoryManager.getMemory().saveContext({input:se.message},{output:ce.message})}x(!0);try{await e.runChain(Re,new AbortController,m,l,{debug:a.debug})&&a.debug&&console.log("Message regenerated successfully")}catch(oe){console.error("Error regenerating message:",oe),new pm.Notice("Failed to regenerate message. Please try again.")}finally{x(!1)}a.autosaveChat&&Y()},[l,e,u,c,a.debug,a.autosaveChat,Y]),le=(0,xr.useCallback)(async(te,et)=>{let Re=u[te].message;if(Re===et)return;let Pe=[...u];for(let oe=te;oe<Pe.length;oe++)Pe[oe].originalMessage===Re&&(Pe[oe].message=et,Pe[oe].originalMessage=et,Pe[oe].context={notes:[],urls:[]});c(),Pe.forEach(l),await _N(Pe,e.memoryManager),Pe[te].sender===Pi&&te<Pe.length-1&&Oe(te+1),a.autosaveChat&&Y()},[l,e.memoryManager,u,c,Oe,a.autosaveChat,Y]);(0,xr.useEffect)(((te,et)=>()=>{let Re=ue().debug,Pe=async oe=>{let ce={message:await et(oe.detail.selectedText,oe.detail.eventSubtype),sender:Pi,isVisible:Re,timestamp:Vl(new Date)};Re&&l(ce),x(!0),await BBe(ce,e,l,m,y,{debug:Re,ignoreSystemMessage:!0}),x(!1)};return s?.addEventListener(te,Pe),()=>{s?.removeEventListener(te,Pe)}})(Br.APPLY_ADHOC_PROMPT,async(te,et)=>et?(await lce(et,te,U.vault,U.workspace.getActiveFile())).processedPrompt:te),[]),(0,xr.useEffect)(()=>{r&&r(Y)},[r,Y]);let ze=(0,xr.useCallback)(async te=>{let et=[...u];et.splice(te,1),c(),et.forEach(l),await _N(et,e.memoryManager)},[l,e.memoryManager,u,c]),rt=(0,xr.useCallback)(te=>{let et=a.projectList||[];if(et.findIndex(se=>se.name===te.name)>=0)throw new Error(`Project "${te.name}" already exists, please use a different name`);let Pe=[...et,te];return dt("projectList",Pe),Mc()?.id===te.id?Jce().then(()=>{new pm.Notice(`${te.name} added and context loaded`)}).catch(se=>{console.error("Error loading project context:",se),new pm.Notice(`${te.name} added but context loading failed`)}):new pm.Notice(`${te.name} added successfully`),!0},[a.projectList]),cr=(0,xr.useCallback)((te,et)=>{let Re=a.projectList||[];if(!Re.find(ce=>ce.name===te.name))throw new Error(`Project "${te.name}" does not exist`);let oe=Re.map(ce=>ce.name===te.name?et:ce);return dt("projectList",oe),Mc()?.id===te.id?(UR(et),Jce().then(()=>{new pm.Notice(`${te.name} updated and context reloaded`)}).catch(ce=>{console.error("Error reloading project context:",ce),new pm.Notice(`${te.name} updated but context reload failed`)})):new pm.Notice(`${te.name} updated successfully`),!0},[a.projectList]),wn=(0,xr.useCallback)(te=>{b(et=>`${et} ${te} `)},[]),Le=(0,xr.useCallback)(te=>{t8e(te)},[]),pt=(0,xr.useCallback)(async()=>{ae("new-chat"),await i.handleNewChat(),m(""),A([]),r8e(),J!=="copilot_plus"?R(!1):R(a.includeActiveNoteAsContext)},[ae,i,a.includeActiveNoteAsContext,J]),mt=(0,xr.useCallback)(()=>{i.loadCopilotChatHistory()},[i]);(0,xr.useEffect)(()=>{let te=et=>{let Re=et.detail?.reason||"new-chat";ae(Re)};return s?.addEventListener(Dh.ABORT_STREAM,te),()=>{s?.removeEventListener(Dh.ABORT_STREAM,te)}},[s,ae]),(0,xr.useEffect)(()=>{a.includeActiveNoteAsContext!==void 0&&(J==="copilot_plus"?R(a.includeActiveNoteAsContext):R(!1))},[a.includeActiveNoteAsContext,J]);let ht=()=>xr.default.createElement(xr.default.Fragment,null,xr.default.createElement("div",{className:"tw-flex tw-size-full tw-flex-col tw-overflow-hidden"},xr.default.createElement(c9t,{currentVersion:i.manifest.version}),xr.default.createElement(l9t,{chatHistory:u,currentAiMessage:p,loading:S,loadingMessage:O,app:U,onRegenerate:Oe,onEdit:le,onDelete:ze,onInsertToChat:wn,onReplaceChat:b,showHelperComponents:J!=="project"}),xr.default.createElement(B6t,{onNewChat:pt,onSaveAsNote:()=>Y(),onLoadHistory:mt,onModeChange:te=>{Q(J),te==="project"&&k(!1)}}),xr.default.createElement(I5t,{ref:H,inputMessage:h,setInputMessage:b,handleSendMessage:W,isGenerating:S,onStopGenerating:()=>ae("user-stopped"),app:U,contextNotes:E,setContextNotes:A,includeActiveNote:I,setIncludeActiveNote:R,mention:q,selectedImages:N,onAddImage:te=>j(et=>[...et,...te]),setSelectedImages:j,disableModelSwitch:J==="project",selectedTextContexts:z,onRemoveSelectedText:Le})));return xr.default.createElement("div",{className:"tw-flex tw-size-full tw-flex-col tw-over Line truncated
${Re}`,Cd=U.vault.getAbstractFileByPath(ta);Cd instanceof pm.TFile?await U.vault.modify(Cd,xc):(await U.vault.create(ta,xc),new pm.Notice(`Chat saved as note: ${ta}`))}catch(Pe){console.error("Error saving chat as note:",ei(Pe)),new pm.Notice("Failed to save chat as note. Check console for details.")}},[U,t,d,a.defaultConversationTag,a.defaultSaveFolder,a.defaultConversationNoteName]),ae=(0,xr.useCallback)(te=>{g&&(a.debug&&console.log(`stopping generation..., reason: ${te}`),g.abort(te),x(!1),P(t_.DEFAULT))},[g,a.debug]),Oe=(0,xr.useCallback)(async te=>{let et=te-1;if(et<0||u[et].sender!==Pi){new pm.Notice("Cannot regenerate the first message or a user message.");return}let Re=u[et],Pe=u.slice(0,te);c(),Pe.forEach(l),e.memoryManager.clearChatMemory();for(let oe=0;oe<Pe.length;oe+=2){let se=Pe[oe],ce=Pe[oe+1];se&&ce&&await e.memoryManager.getMemory().saveContext({input:se.message},{output:ce.message})}x(!0);try{await e.runChain(Re,new AbortController,m,l,{debug:a.debug})&&a.debug&&console.log("Message regenerated successfully")}catch(oe){console.error("Error regenerating message:",oe),new pm.Notice("Failed to regenerate message. Please try again.")}finally{x(!1)}a.autosaveChat&&Y()},[l,e,u,c,a.debug,a.autosaveChat,Y]),le=(0,xr.useCallback)(async(te,et)=>{let Re=u[te].message;if(Re===et)return;let Pe=[...u];for(let oe=te;oe<Pe.length;oe++)Pe[oe].originalMessage===Re&&(Pe[oe].message=et,Pe[oe].originalMessage=et,Pe[oe].context={notes:[],urls:[]});c(),Pe.forEach(l),await vN(Pe,e.memoryManager),Pe[te].sender===Pi&&te<Pe.length-1&&Oe(te+1),a.autosaveChat&&Y()},[l,e.memoryManager,u,c,Oe,a.autosaveChat,Y]);(0,xr.useEffect)(((te,et)=>()=>{let Re=ue().debug,Pe=async oe=>{let ce={message:await et(oe.detail.selectedText,oe.detail.eventSubtype),sender:Pi,isVisible:Re,timestamp:Vl(new Date)};Re&&l(ce),x(!0),await UBe(ce,e,l,m,y,{debug:Re,ignoreSystemMessage:!0}),x(!1)};return s?.addEventListener(te,Pe),()=>{s?.removeEventListener(te,Pe)}})(Br.APPLY_ADHOC_PROMPT,async(te,et)=>et?(await fce(et,te,U.vault,U.workspace.getActiveFile())).processedPrompt:te),[]),(0,xr.useEffect)(()=>{r&&r(Y)},[r,Y]);let ze=(0,xr.useCallback)(async te=>{let et=[...u];et.splice(te,1),c(),et.forEach(l),await vN(et,e.memoryManager)},[l,e.memoryManager,u,c]),rt=(0,xr.useCallback)(te=>{let et=a.projectList||[];if(et.findIndex(se=>se.name===te.name)>=0)throw new Error(`Project "${te.name}" already exists, please use a different name`);let Pe=[...et,te];return dt("projectList",Pe),Mc()?.id===te.id?Xce().then(()=>{new pm.Notice(`${te.name} added and context loaded`)}).catch(se=>{console.error("Error loading project context:",se),new pm.Notice(`${te.name} added but context loading failed`)}):new pm.Notice(`${te.name} added successfully`),!0},[a.projectList]),cr=(0,xr.useCallback)((te,et)=>{let Re=a.projectList||[];if(!Re.find(ce=>ce.name===te.name))throw new Error(`Project "${te.name}" does not exist`);let oe=Re.map(ce=>ce.name===te.name?et:ce);return dt("projectList",oe),Mc()?.id===te.id?(zR(et),Xce().then(()=>{new pm.Notice(`${te.name} updated and context reloaded`)}).catch(ce=>{console.error("Error reloading project context:",ce),new pm.Notice(`${te.name} updated but context reload failed`)})):new pm.Notice(`${te.name} updated successfully`),!0},[a.projectList]),Sn=(0,xr.useCallback)(te=>{b(et=>`${et} ${te} `)},[]),je=(0,xr.useCallback)(te=>{i8e(te)},[]),mt=(0,xr.useCallback)(async()=>{ae("new-chat"),await i.handleNewChat(),m(""),A([]),a8e(),J!=="copilot_plus"?R(!1):R(a.includeActiveNoteAsContext)},[ae,i,a.includeActiveNoteAsContext,J]),ht=(0,xr.useCallback)(()=>{i.loadCopilotChatHistory()},[i]);(0,xr.useEffect)(()=>{let te=et=>{let Re=et.detail?.reason||"new-chat";ae(Re)};return s?.addEventListener(Dh.ABORT_STREAM,te),()=>{s?.removeEventListener(Dh.ABORT_STREAM,te)}},[s,ae]),(0,xr.useEffect)(()=>{a.includeActiveNoteAsContext!==void 0&&(J==="copilot_plus"?R(a.includeActiveNoteAsContext):R(!1))},[a.includeActiveNoteAsContext,J]);let ft=()=>xr.default.createElement(xr.default.Fragment,null,xr.default.createElement("div",{className:"tw-flex tw-size-full tw-flex-col tw-overflow-hidden"},xr.default.createElement(h9t,{currentVersion:i.manifest.version}),xr.default.createElement(m9t,{chatHistory:u,currentAiMessage:p,loading:S,loadingMessage:O,app:U,onRegenerate:Oe,onEdit:le,onDelete:ze,onInsertToChat:Sn,onReplaceChat:b,showHelperComponents:J!=="project"}),xr.default.createElement(V6t,{onNewChat:mt,onSaveAsNote:()=>Y(),onLoadHistory:ht,onModeChange:te=>{Q(J),te==="project"&&k(!1)}}),xr.default.createElement(D5t,{ref:H,inputMessage:h,setInputMessage:b,handleSendMessage:W,isGenerating:S,onStopGenerating:()=>ae("user-stopped"),app:U,contextNotes:E,setContextNotes:A,includeActiveNote:I,setIncludeActiveNote:R,mention:q,selectedImages:N,onAddImage:te=>j(et=>[...et,...te]),setSelectedImages:j,disableModelSwitch:J==="project",selectedTextContexts:z,onRemoveSelectedText:je})));return xr.default.createElement("div",{className:"tw-flex tw-size-full tw-flex-col tw-over Line truncated
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.
`},LIn={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 FIn(t){let{announcements:e=LIn,container:r,hiddenTextDescribedById:n,screenReaderInstructions:o=DIn}=t,{announce:i,announcement:a}=ZJt(),s=yL("DndLiveRegion"),[u,l]=(0,Ae.useState)(!1);if((0,Ae.useEffect)(()=>{l(!0)},[]),jIn((0,Ae.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=Ae.default.createElement(Ae.default.Fragment,null,Ae.default.createElement(JJt,{id:n,value:o.draggable}),Ae.default.createElement(YJt,{id:s,announcement:a}));return r?(0,wL.createPortal)(c,r):c}var Ul;(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"})(Ul||(Ul={}));function dfe(){}function Zz(t,e){return(0,Ae.useMemo)(()=>({sensor:t,options:e??{}}),[t,e])}function pfe(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return(0,Ae.useMemo)(()=>[...e].filter(n=>n!=null),[...e])}var jb=Object.freeze({x:0,y:0});function d7t(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}function f7t(t,e){let{data:{value:r}}=t,{data:{value:n}}=e;return r-n}function kIn(t,e){let{data:{value:r}}=t,{data:{value:n}}=e;return n-r}function XJt(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 iqe(t,e){if(!t||t.length===0)return null;let[r]=t;return e?r[e]:r}function QJt(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 z9=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=QJt(e,e.left,e.top),i=[];for(let a of n){let{id:s}=a,u=r.get(s);if(u){let l=d7t(QJt(u),o);i.push({id:s,data:{droppableContainer:a,value:l}})}}return i.sort(f7t)},p7t=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=XJt(e),i=[];for(let a of n){let{id:s}=a,u=r.get(s);if(u){let l=XJt(u),c=o.reduce((f,p,m)=>f+d7t(l[m],p),0),d=Number((c/4).toFixed(4));i.push({id:s,data:{droppableContainer:a,value:d}})}}return i.sort(f7t)};function $In(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 BIn=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=$In(s,e);u>0&&o.push({id:a,data:{droppableContainer:i,value:u}})}}return o.sort(kIn)};function qIn(t,e,r){return{...t,scaleX:e&&r?e.width/r.width:1,scaleY:e&&r?e.height/r.height:1}}function m7t(t,e){return t&&e?{x:t.left-e.left,y:t.top-e.top}:jb}function UIn(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 zIn=UIn(1);function HIn(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}function VIn(t,e,r){let n=HIn(e);if(!n)return t;let{scaleX:o,scaleY:i,x:a,y:s}=n,u=t.left-a-(1-o)*parseFloat(r),l=t.top-s-(1-i)*parseFloat(r.slice(r.indexOf(" ")+1)),c=o?t.width/o:t.width,d=i?t.height/i:t.height;return{width:c,height:d,top:l,right:u+c,bottom:l+d,left:u}}var WIn={ignoreTransform:!1};function CL(t,e){e===void 0&&(e=WIn);let r=t.getBoundingClientRect();if(e.ignoreTransform){let{transform:l,transformOrigin:c}=sp(t).getComputedStyle(t);l&&(r=VIn(r,l,c))}let{top:n,left:o,width:i,height:a,bottom:s,right:u}=r;return{top:n,left:o,width:i,height:a,bottom:s,right:u}}function e7t(t){return CL(t,{ignoreTransform:!0})}function KIn(t){let e=t.innerWidth,r=t.innerHeight;return{top:0,left:0,right:e,bottom:r,width:e,height:r}}function GIn(t,e){return e===void 0&&(e=sp(t).getComputedStyle(t)),e.position==="fixed"}function JIn(t,e){e===void 0&&(e=sp(t).getComputedStyle(t));let r=/(auto|scroll|overla Line truncated
`},qIn={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 UIn(t){let{announcements:e=qIn,container:r,hiddenTextDescribedById:n,screenReaderInstructions:o=BIn}=t,{announce:i,announcement:a}=r7t(),s=bL("DndLiveRegion"),[u,l]=(0,Ae.useState)(!1);if((0,Ae.useEffect)(()=>{l(!0)},[]),kIn((0,Ae.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=Ae.default.createElement(Ae.default.Fragment,null,Ae.default.createElement(e7t,{id:n,value:o.draggable}),Ae.default.createElement(t7t,{id:s,announcement:a}));return r?(0,SL.createPortal)(c,r):c}var Ul;(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"})(Ul||(Ul={}));function mfe(){}function Xz(t,e){return(0,Ae.useMemo)(()=>({sensor:t,options:e??{}}),[t,e])}function gfe(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return(0,Ae.useMemo)(()=>[...e].filter(n=>n!=null),[...e])}var jb=Object.freeze({x:0,y:0});function g7t(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}function y7t(t,e){let{data:{value:r}}=t,{data:{value:n}}=e;return r-n}function zIn(t,e){let{data:{value:r}}=t,{data:{value:n}}=e;return n-r}function n7t(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 sqe(t,e){if(!t||t.length===0)return null;let[r]=t;return e?r[e]:r}function o7t(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 H9=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=o7t(e,e.left,e.top),i=[];for(let a of n){let{id:s}=a,u=r.get(s);if(u){let l=g7t(o7t(u),o);i.push({id:s,data:{droppableContainer:a,value:l}})}}return i.sort(y7t)},b7t=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=n7t(e),i=[];for(let a of n){let{id:s}=a,u=r.get(s);if(u){let l=n7t(u),c=o.reduce((f,p,m)=>f+g7t(l[m],p),0),d=Number((c/4).toFixed(4));i.push({id:s,data:{droppableContainer:a,value:d}})}}return i.sort(y7t)};function HIn(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 VIn=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=HIn(s,e);u>0&&o.push({id:a,data:{droppableContainer:i,value:u}})}}return o.sort(zIn)};function WIn(t,e,r){return{...t,scaleX:e&&r?e.width/r.width:1,scaleY:e&&r?e.height/r.height:1}}function _7t(t,e){return t&&e?{x:t.left-e.left,y:t.top-e.top}:jb}function KIn(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 GIn=KIn(1);function JIn(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}function YIn(t,e,r){let n=JIn(e);if(!n)return t;let{scaleX:o,scaleY:i,x:a,y:s}=n,u=t.left-a-(1-o)*parseFloat(r),l=t.top-s-(1-i)*parseFloat(r.slice(r.indexOf(" ")+1)),c=o?t.width/o:t.width,d=i?t.height/i:t.height;return{width:c,height:d,top:l,right:u+c,bottom:l+d,left:u}}var ZIn={ignoreTransform:!1};function OL(t,e){e===void 0&&(e=ZIn);let r=t.getBoundingClientRect();if(e.ignoreTransform){let{transform:l,transformOrigin:c}=sp(t).getComputedStyle(t);l&&(r=YIn(r,l,c))}let{top:n,left:o,width:i,height:a,bottom:s,right:u}=r;return{top:n,left:o,width:i,height:a,bottom:s,right:u}}function i7t(t){return OL(t,{ignoreTransform:!0})}function XIn(t){let e=t.innerWidth,r=t.innerHeight;return{top:0,left:0,right:e,bottom:r,width:e,height:r}}function QIn(t,e){return e===void 0&&(e=sp(t).getComputedStyle(t)),e.position==="fixed"}function eMn(t,e){e===void 0&&(e=sp(t).getComputedStyle(t));let r=/(auto|scroll|overla Line truncated
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 Qi.useEffect(()=>{t&&(document.getElementById(t)||console.error(r))},[r,t]),null},ORn="DialogDescriptionWarning",PRn=({contentRef:t,descriptionId:e})=>{let n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${gYt(ORn).contentName}}.`;return Qi.useEffect(()=>{let o=t.current?.getAttribute("aria-describedby");e&&o&&(document.getElementById(e)||console.warn(n))},[n,t,e]),null},yYt=rYt,bYt=oYt,_Yt=aYt,vqe=sYt,wqe=uYt,Sqe=cYt,xqe=fYt,vYt=mYt;yn();Tn();var Ofe=yYt,wYt=bYt,TRn=_Yt;var SYt=xd.forwardRef(({className:t,...e},r)=>xd.createElement(vqe,{ref:r,className:_e("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}));SYt.displayName=vqe.displayName;var Z9=xd.forwardRef(({className:t,children:e,container:r,...n},o)=>xd.createElement(TRn,{container:r},xd.createElement(SYt,null),xd.createElement(wqe,{ref:o,className:_e("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,xd.createElement(vYt,{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"},xd.createElement(Vi,{className:"tw-size-4"}),xd.createElement("span",{className:"tw-sr-only"},"Close")))));Z9.displayName=wqe.displayName;var X9=({className:t,...e})=>xd.createElement("div",{className:_e("tw-flex tw-flex-col tw-space-y-0.5 tw-text-center sm:tw-text-left",t),...e});X9.displayName="DialogHeader";var ARn=({className:t,...e})=>xd.createElement("div",{className:_e("tw-flex tw-flex-col-reverse sm:tw-flex-row sm:tw-justify-end sm:tw-space-x-2",t),...e});ARn.displayName="DialogFooter";var Q9=xd.forwardRef(({className:t,...e},r)=>xd.createElement(Sqe,{ref:r,className:_e("tw-mt-0 tw-text-lg tw-font-semibold tw-leading-none tw-tracking-tight",t),...e}));Q9.displayName=Sqe.displayName;var eK=xd.forwardRef(({className:t,...e},r)=>xd.createElement(xqe,{ref:r,className:_e("tw-text-sm tw-text-muted",t),...e}));eK.displayName=xqe.displayName;Cn();function hn(t){let{title:e,description:r,className:n,disabled:o}=t,{modalContainer:i}=Vz(),a="onChange"in t?t.onChange:void 0,s=(0,va.useMemo)(()=>{if(a)return tJ(l=>{a(l)},1e3)},[a]),u=()=>{switch(t.type){case"text":case"number":return va.default.createElement(mo,{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 va.default.createElement(iC,{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 va.default.createElement(yE,{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 va.default.createElement(cz,{checked:t.checked,onCheckedChange:t.onCheckedChange,disabled:o});case"select":return va.default.createElement("div",{className:"tw-group tw-relative tw-w-full sm:tw-w-[200px]"},va.default.createElement("select",{value:t.value?.toString(),onChange:l=>t.onChange?.(l.target.value),disabled:o,className:_e("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")},t.placeholder&&va.default.createElement("option",{value:"",disabled:!0},t.placeholder),t.options.map(l=>va.default.createElement("option",{key:l.value,value:l.value.toString()},l.label))),va.default.createElement("div",{className:_e("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",o&&"tw-opacity-50")},va.default.createElement(Hi,{className:"tw-size-4"})));case"slider":return va.default.createElement(nC,{value:t.value||0,onChange:t.onChange,min:t.min,max:t.max,step:t.step,disabled:o,className:"tw-w-full sm:tw-w-[300px]"});case"di Line truncated
For more information, see https://radix-ui.com/primitives/docs/components/${e.docsSlug}`;return Qi.useEffect(()=>{t&&(document.getElementById(t)||console.error(r))},[r,t]),null},IRn="DialogDescriptionWarning",MRn=({contentRef:t,descriptionId:e})=>{let n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${wYt(IRn).contentName}}.`;return Qi.useEffect(()=>{let o=t.current?.getAttribute("aria-describedby");e&&o&&(document.getElementById(e)||console.warn(n))},[n,t,e]),null},SYt=sYt,xYt=lYt,CYt=dYt,Sqe=fYt,xqe=pYt,Cqe=hYt,Oqe=yYt,OYt=_Yt;bn();Tn();var Tfe=SYt,PYt=xYt,jRn=CYt;var EYt=xd.forwardRef(({className:t,...e},r)=>xd.createElement(Sqe,{ref:r,className:_e("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}));EYt.displayName=Sqe.displayName;var X9=xd.forwardRef(({className:t,children:e,container:r,...n},o)=>xd.createElement(jRn,{container:r},xd.createElement(EYt,null),xd.createElement(xqe,{ref:o,className:_e("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,xd.createElement(OYt,{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"},xd.createElement(Vi,{className:"tw-size-4"}),xd.createElement("span",{className:"tw-sr-only"},"Close")))));X9.displayName=xqe.displayName;var Q9=({className:t,...e})=>xd.createElement("div",{className:_e("tw-flex tw-flex-col tw-space-y-0.5 tw-text-center sm:tw-text-left",t),...e});Q9.displayName="DialogHeader";var NRn=({className:t,...e})=>xd.createElement("div",{className:_e("tw-flex tw-flex-col-reverse sm:tw-flex-row sm:tw-justify-end sm:tw-space-x-2",t),...e});NRn.displayName="DialogFooter";var eK=xd.forwardRef(({className:t,...e},r)=>xd.createElement(Cqe,{ref:r,className:_e("tw-mt-0 tw-text-lg tw-font-semibold tw-leading-none tw-tracking-tight",t),...e}));eK.displayName=Cqe.displayName;var tK=xd.forwardRef(({className:t,...e},r)=>xd.createElement(Oqe,{ref:r,className:_e("tw-text-sm tw-text-muted",t),...e}));tK.displayName=Oqe.displayName;yn();function hn(t){let{title:e,description:r,className:n,disabled:o}=t,{modalContainer:i}=Wz(),a="onChange"in t?t.onChange:void 0,s=(0,va.useMemo)(()=>{if(a)return rJ(l=>{a(l)},1e3)},[a]),u=()=>{switch(t.type){case"text":case"number":return va.default.createElement(mo,{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 va.default.createElement(aC,{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 va.default.createElement(yE,{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 va.default.createElement(dz,{checked:t.checked,onCheckedChange:t.onCheckedChange,disabled:o});case"select":return va.default.createElement("div",{className:"tw-group tw-relative tw-w-full sm:tw-w-[200px]"},va.default.createElement("select",{value:t.value?.toString(),onChange:l=>t.onChange?.(l.target.value),disabled:o,className:_e("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")},t.placeholder&&va.default.createElement("option",{value:"",disabled:!0},t.placeholder),t.options.map(l=>va.default.createElement("option",{key:l.value,value:l.value.toString()},l.label))),va.default.createElement("div",{className:_e("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",o&&"tw-opacity-50")},va.default.createElement(Hi,{className:"tw-size-4"})));case"slider":return va.default.createElement(oC,{value:t.value||0,onChange:t.onChange,min:t.min,max:t.max,step:t.step,disabled:o,className:"tw-w-full sm:tw-w-[300px]"});case"di Line truncated
Original name: ${a.title}
${a.content}`}):e.push(a)}await lm.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 ${QI()}.`;r.length>0&&(await IRn(r),i+=`
${a.content}`}):e.push(a)}await lm.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 ${QI()}.`;r.length>0&&(await DRn(r),i+=`
We found ${r.length} unsupported commands. They are saved in ${QI()}/unsupported. To fix them, please resolve the errors and move the note file out of the unsupported folder.`),dt("inlineEditCommands",[]),new sd(app,()=>{},i,"\u{1F680} New Copilot Custom Commands","OK","").open()}async function Cqe(){let t=Gx(),e=O3t.filter(n=>!t.some(o=>o.title===n.title)),r=[...t,...e];lm.getInstance().updateCommands(r)}async function CYt(){if(ue().suggestedDefaultCommands)return;Gx().length===0&&(new sd(app,()=>{Cqe()},"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(),dt("suggestedDefaultCommands",!0))}var MRn=({command:t,commands:e,onUpdate:r,onRemove:n})=>{let{attributes:o,listeners:i,setNodeRef:a,transform:s,transition:u,isDragging:l}=G9({id:t.title}),c={transform:Rb.Transform.toString(s),transition:u},d=()=>{n(t)};return it.default.createElement(BM,{ref:a,style:c,className:_e("tw-transition-colors",l&&"tw-relative tw-z-[100] tw-cursor-grabbing tw-shadow-lg tw-backdrop-blur-sm tw-border-accent/50")},it.default.createElement(gf,{className:"tw-w-10"},it.default.createElement("div",{...o,...i,className:"tw-flex tw-cursor-grab tw-items-center tw-justify-center"},it.default.createElement(d_,{className:"tw-size-4"}))),it.default.createElement(gf,null,t.title),it.default.createElement(gf,{className:"tw-text-center"},it.default.createElement(wd,{checked:t.showInContextMenu,onCheckedChange:f=>{r({...t,showInContextMenu:f===!0},t.title)},className:"tw-mx-auto"})),it.default.createElement(gf,{className:"tw-text-center"},it.default.createElement(wd,{checked:t.showInSlashMenu,onCheckedChange:f=>r({...t,showInSlashMenu:f===!0},t.title),className:"tw-mx-auto"})),it.default.createElement(gf,{className:"tw-text-center"},it.default.createElement("div",{className:"tw-flex tw-justify-center tw-space-x-1"},it.default.createElement(ge,{variant:"ghost",size:"icon",onClick:()=>{new Sfe(app,e,t,async p=>{await r(p,t.title)}).open()}},it.default.createElement(p_,{className:"tw-size-4"})),it.default.createElement(ge,{variant:"ghost",size:"icon",onClick:()=>{new sd(app,d,`Are you sure you want to delete the command "${t.title}"? This will permanently remove the command file and cannot be undone.`,"Delete Command","Delete","Cancel").open()}},it.default.createElement(Rm,{className:"tw-size-4"})))))},OYt=()=>{let t=P3t(),e=(0,it.useMemo)(()=>AW([...t]),[t]),[r,n]=it.default.useState(""),o=Rn(),i=pfe(Zz(VM,{activationConstraint:{distance:8}}),Zz(HM,{coordinateGetter:vfe})),a=GU(r,e),s=!a&&r.trim()!=="",u=async()=>{if(s)try{await lm.getInstance().createCommand(r.trim(),""),n(""),new tK.Notice(`Command "${r.trim()}" created successfully!`)}catch(p){console.error("Failed to create command:",p),new tK.Notice("Failed to create command. Please try again.")}},l=async(p,m)=>{await lm.getInstance().updateCommand(p,m)},c=async p=>{try{await lm.getInstance().deleteCommand(p),new tK.Notice(`Command "${p.title}" deleted successfully!`)}catch(m){throw console.error("Failed to delete command:",m),new tK.Notice("Failed to delete command. Please try again."),m}},d=async p=>{let{active:m,over:h}=p;if(!h||m.id===h.id)return;let b=e.findIndex(x=>x.title===m.id),g=e.findIndex(x=>x.title===h.id);if(b===-1||g===-1)return;let y=[...e],[S]=y.splice(b,1);y.splice(g,0,S);for(let x=0;x<y.length;x++)y[x]={...y[x],order:x*10};await lm.getInstance().updateCommands(y)},f=J9();return it.default.createElement("div",{className:"tw-space-y-4"},it.default.createElement("section",null,it.default.createElement("div",{className:"tw-mb-4 tw-flex tw-flex-col tw-gap-2"},it.default.createElement("div",{className:"tw-text-xl tw-font-bold"},"Custom Commands"),it.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Custom commands are preset prompts that you can trigger in the editor by right-clicking and selecting them from the context menu or by using a ",it.default.createElement("code",null,"/")," command in the chat to load them into your chat input.")),it.default.createElement(hn,{type:"text",title:"Custom Prompts Folder Name",description:"Folder where custom prompts are stored",value:o.customPromptsFolder,onChange:p=>{dt("customPromptsFolder",p),uce()},placeholder:"copilot-custom-prompts"}),it.default.createElement(hn,{type:"switch",title:"Custom Prompt Templating",description:"Process variables like {activenote}, {foldername}, or {#tag} in prompts. Disable for raw prompts.",checked:o.enableCustomPromptTemplating,onCheckedChange:p=>{dt("enableCustomPromptTemplating",p)}}),it.default.createElement(hn,{type:"select",title:"Custom Prompts Sort Strategy",description:"Sort order for slash command menu prompts",value:o.promptSortStrategy,onChange:p=>dt("promptSortStrategy",p),options:[{label:"Recency",value:"timestamp"},{label:"Alphabetical",value:"alphabetical"},{label:"Manual",value:"manual"}]}),it.defa Line truncated
We found ${r.length} unsupported commands. They are saved in ${QI()}/unsupported. To fix them, please resolve the errors and move the note file out of the unsupported folder.`),dt("inlineEditCommands",[]),new sd(app,()=>{},i,"\u{1F680} New Copilot Custom Commands","OK","").open()}async function Pqe(){let t=Jx(),e=I3t.filter(n=>!t.some(o=>o.title===n.title)),r=[...t,...e];lm.getInstance().updateCommands(r)}async function AYt(){if(ue().suggestedDefaultCommands)return;Jx().length===0&&(new sd(app,()=>{Pqe()},"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(),dt("suggestedDefaultCommands",!0))}var LRn=({command:t,commands:e,onUpdate:r,onRemove:n})=>{let{attributes:o,listeners:i,setNodeRef:a,transform:s,transition:u,isDragging:l}=J9({id:t.title}),c={transform:Rb.Transform.toString(s),transition:u},d=()=>{n(t)};return it.default.createElement(BM,{ref:a,style:c,className:_e("tw-transition-colors",l&&"tw-relative tw-z-[100] tw-cursor-grabbing tw-shadow-lg tw-backdrop-blur-sm tw-border-accent/50")},it.default.createElement(gf,{className:"tw-w-10"},it.default.createElement("div",{...o,...i,className:"tw-flex tw-cursor-grab tw-items-center tw-justify-center"},it.default.createElement(d_,{className:"tw-size-4"}))),it.default.createElement(gf,null,t.title),it.default.createElement(gf,{className:"tw-text-center"},it.default.createElement(wd,{checked:t.showInContextMenu,onCheckedChange:f=>{r({...t,showInContextMenu:f===!0},t.title)},className:"tw-mx-auto"})),it.default.createElement(gf,{className:"tw-text-center"},it.default.createElement(wd,{checked:t.showInSlashMenu,onCheckedChange:f=>r({...t,showInSlashMenu:f===!0},t.title),className:"tw-mx-auto"})),it.default.createElement(gf,{className:"tw-text-center"},it.default.createElement("div",{className:"tw-flex tw-justify-center tw-space-x-1"},it.default.createElement(ge,{variant:"ghost",size:"icon",onClick:()=>{new Ofe(app,e,t,async p=>{await r(p,t.title)}).open()}},it.default.createElement(p_,{className:"tw-size-4"})),it.default.createElement(ge,{variant:"ghost",size:"icon",onClick:()=>{new sd(app,d,`Are you sure you want to delete the command "${t.title}"? This will permanently remove the command file and cannot be undone.`,"Delete Command","Delete","Cancel").open()}},it.default.createElement(Rm,{className:"tw-size-4"})))))},IYt=()=>{let t=M3t(),e=(0,it.useMemo)(()=>IW([...t]),[t]),[r,n]=it.default.useState(""),o=Rn(),i=gfe(Xz(VM,{activationConstraint:{distance:8}}),Xz(HM,{coordinateGetter:xfe})),a=JU(r,e),s=!a&&r.trim()!=="",u=async()=>{if(s)try{await lm.getInstance().createCommand(r.trim(),""),n(""),new rK.Notice(`Command "${r.trim()}" created successfully!`)}catch(p){console.error("Failed to create command:",p),new rK.Notice("Failed to create command. Please try again.")}},l=async(p,m)=>{await lm.getInstance().updateCommand(p,m)},c=async p=>{try{await lm.getInstance().deleteCommand(p),new rK.Notice(`Command "${p.title}" deleted successfully!`)}catch(m){throw console.error("Failed to delete command:",m),new rK.Notice("Failed to delete command. Please try again."),m}},d=async p=>{let{active:m,over:h}=p;if(!h||m.id===h.id)return;let b=e.findIndex(x=>x.title===m.id),g=e.findIndex(x=>x.title===h.id);if(b===-1||g===-1)return;let y=[...e],[S]=y.splice(b,1);y.splice(g,0,S);for(let x=0;x<y.length;x++)y[x]={...y[x],order:x*10};await lm.getInstance().updateCommands(y)},f=Y9();return it.default.createElement("div",{className:"tw-space-y-4"},it.default.createElement("section",null,it.default.createElement("div",{className:"tw-mb-4 tw-flex tw-flex-col tw-gap-2"},it.default.createElement("div",{className:"tw-text-xl tw-font-bold"},"Custom Commands"),it.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Custom commands are preset prompts that you can trigger in the editor by right-clicking and selecting them from the context menu or by using a ",it.default.createElement("code",null,"/")," command in the chat to load them into your chat input.")),it.default.createElement(hn,{type:"text",title:"Custom Prompts Folder Name",description:"Folder where custom prompts are stored",value:o.customPromptsFolder,onChange:p=>{dt("customPromptsFolder",p),dce()},placeholder:"copilot-custom-prompts"}),it.default.createElement(hn,{type:"switch",title:"Custom Prompt Templating",description:"Process variables like {activenote}, {foldername}, or {#tag} in prompts. Disable for raw prompts.",checked:o.enableCustomPromptTemplating,onCheckedChange:p=>{dt("enableCustomPromptTemplating",p)}}),it.default.createElement(hn,{type:"select",title:"Custom Prompts Sort Strategy",description:"Sort order for slash command menu prompts",value:o.promptSortStrategy,onChange:p=>dt("promptSortStrategy",p),options:[{label:"Recency",value:"timestamp"},{label:"Alphabetical",value:"alphabetical"},{label:"Manual",value:"manual"}]}),it.defa Line truncated
detail: `+q)}return B}finally{clearTimeout(D)}},k;try{k=await $(!1)}catch(Q){console.log("First fetch attempt failed, trying with safeFetch...");try{k=await $(!0)}catch(J){let D=`
without CORS Error: `+ei(Q)+`
with CORS Error: `+ei(J);throw new Error(D)}}let z=await k.json(),V=IYt(I,z);l(Q=>({...Q,[I]:V})),d(null)}catch(N){console.error(`Error fetching models for ${I}:`,N),p(I),d(null),new Db.Notice(`Failed to load models for ${kf(I)}: ${ei(N)}`,5e3)}},A=async()=>{if(!m){new Db.Notice("Please select a model first");return}g(!0);try{let I=S(m.provider),R={name:m.name,provider:m.provider,apiKey:I,enabled:!0};if(await ac.instance.getCurrentChainManager().chatModelManager.ping(R),e.activeModels.find(j=>j.name===m.name&&j.provider===m.provider))new Db.Notice(`Model ${m.name} verified successfully! It already exists in your models list.`);else{let j=[...e.activeModels,R];dt("activeModels",j),new Db.Notice(`Model ${m.name} verified successfully and added to your models list!`)}}catch(I){console.error("Model verification failed:",I),new Db.Notice("Model verification failed: "+ei(I),1e4)}finally{g(!1)}};return Ht.default.createElement("div",{className:"tw-max-h-[600px] tw-overflow-y-auto tw-p-4 sm:tw-max-w-[500px]"},Ht.default.createElement("div",{className:"tw-mb-4"},Ht.default.createElement("h2",{className:"tw-text-xl tw-font-bold"},"AI Provider Settings"),Ht.default.createElement("p",{className:"tw-text-sm tw-text-muted"},"Configure your AI providers by adding their API keys.")),Ht.default.createElement("div",{className:"tw-space-y-6 tw-py-4"},Ht.default.createElement("div",{className:"tw-space-y-4"},x.map(I=>Ht.default.createElement(Ht.default.Fragment,{key:I.provider},Ht.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Ht.default.createElement("div",{className:"tw-flex tw-items-end tw-gap-2 tw-font-medium"},Ht.default.createElement("div",{className:"tw-truncate"},kf(I.provider))),Ht.default.createElement("div",{className:"tw-flex tw-flex-row tw-items-center tw-gap-2"},Ht.default.createElement("div",{className:"tw-flex-1"},Ht.default.createElement(iC,{className:"tw-max-w-full",value:I.apiKey,onChange:R=>O(I.provider,R),disabled:r.has(I.provider)})),Ht.default.createElement("div",{className:"tw-w-[72px]"},I.isVerified?Ht.default.createElement("span",{className:"tw-flex tw-h-9 tw-items-center tw-justify-center tw-text-sm tw-text-success"},"Verified"):Ht.default.createElement(ge,{onClick:()=>P(I.provider,I.apiKey),disabled:!I.apiKey||r.size>0,variant:"secondary",size:"sm",className:"tw-w-full tw-whitespace-nowrap"},r.has(I.provider)?Ht.default.createElement(Yl,{className:"tw-mr-2 tw-size-4 tw-animate-spin"}):"Verify")),Ht.default.createElement("div",{className:""},Ht.default.createElement(ge,{onClick:()=>{let R=a===I.provider?null:I.provider;s(R),R&&I.apiKey&&u[I.provider]===void 0&&c!==I.provider&&f!==I.provider&&E(I.provider,I.apiKey)},disabled:!I.apiKey||r.size>0,variant:"secondary",size:"sm",className:"tw-flex tw-w-full tw-items-center tw-justify-center tw-gap-1 tw-whitespace-nowrap tw-p-0.5"},"Add Model",a===I.provider?Ht.default.createElement(Ey,{className:"tw-ml-1 tw-size-4"}):Ht.default.createElement(Hi,{className:"tw-ml-1 tw-size-4"})))),Ht.default.createElement("div",null,Xb(I.provider).keyManagementURL&&Ht.default.createElement("a",{href:Xb(I.provider).keyManagementURL,target:"_blank",rel:"noopener noreferrer",className:"tw-text-[10px] tw-text-accent hover:tw-text-accent-hover sm:tw-text-xs"},"Get ",kf(I.provider)," Key"))),Ht.default.createElement(cE,{open:a===I.provider,className:"tw-mt-2"},Ht.default.createElement(dE,{className:"tw-rounded-md tw-p-3"},Ht.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Ht.default.createElement(Yn,{label:"Model",description:"Add the currently selected model to model List. After adding, please check the Model Tab."},Ht.default.createElement("div",null,Ht.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Ht.default.createElement("div",{className:"tw-flex-1"},Ht.default.createElement(zde,{options:u[I.provider]?.sort((R,N)=>R.name.localeCompare(N.name)).map(R=>({label:R.name,value:R.id}))||[],onChange:R=>{let N=R.target.value,j=u[I.provider]?.find($=>$.id===N);j&&h({id:j.id,name:j.name,provider:I.provider})},onClick:()=>{I.apiKey&&u[I.provider]===void 0&&c!==I.provider&&f!==I.provider&&E(I.provider,I.apiKey)},value:m?.provider===I.provider?m.id:"",placeholder:"Select Model",disabled:!I.apiKey||c===I.provider||f===I.provider&&u[I.provider]!==null})),Ht.default.createElement("div",{className:"tw-w-[72px]"},Ht.default.createElement(ge,{onClick:A,disabled:!m||m.provider!==I.provider||b,variant:"secondary",size:"sm",className:"tw-w-full tw-whitespace-nowrap"},b?Ht.default.createElement(Yl,{className:"tw-mr-2 tw-size-4 tw-animate-spin"}):"Add"))),Ht.default.createElement("div",{className:"tw-mt-1 tw-text-xs"},c===I.provider&&Ht.default.createElement("div",{className:"tw-p-1 tw-text-muted"},"Loading models..."),f===I.provider&&Ht.default.createElement("div",{className:"tw-p-1 tw-text-error"},"Failed to load models.",u[I.provider]===null&&" Check API Key or network."),u[I.provider]&&u[I.provider].length===0&&Ht.defaul Line truncated
with CORS Error: `+ei(J);throw new Error(D)}}let z=await k.json(),V=DYt(I,z);l(Q=>({...Q,[I]:V})),d(null)}catch(N){console.error(`Error fetching models for ${I}:`,N),p(I),d(null),new Db.Notice(`Failed to load models for ${kf(I)}: ${ei(N)}`,5e3)}},A=async()=>{if(!m){new Db.Notice("Please select a model first");return}g(!0);try{let I=S(m.provider),R={name:m.name,provider:m.provider,apiKey:I,enabled:!0};if(await ac.instance.getCurrentChainManager().chatModelManager.ping(R),e.activeModels.find(j=>j.name===m.name&&j.provider===m.provider))new Db.Notice(`Model ${m.name} verified successfully! It already exists in your models list.`);else{let j=[...e.activeModels,R];dt("activeModels",j),new Db.Notice(`Model ${m.name} verified successfully and added to your models list!`)}}catch(I){console.error("Model verification failed:",I),new Db.Notice("Model verification failed: "+ei(I),1e4)}finally{g(!1)}};return Ht.default.createElement("div",{className:"tw-max-h-[600px] tw-overflow-y-auto tw-p-4 sm:tw-max-w-[500px]"},Ht.default.createElement("div",{className:"tw-mb-4"},Ht.default.createElement("h2",{className:"tw-text-xl tw-font-bold"},"AI Provider Settings"),Ht.default.createElement("p",{className:"tw-text-sm tw-text-muted"},"Configure your AI providers by adding their API keys.")),Ht.default.createElement("div",{className:"tw-space-y-6 tw-py-4"},Ht.default.createElement("div",{className:"tw-space-y-4"},x.map(I=>Ht.default.createElement(Ht.default.Fragment,{key:I.provider},Ht.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Ht.default.createElement("div",{className:"tw-flex tw-items-end tw-gap-2 tw-font-medium"},Ht.default.createElement("div",{className:"tw-truncate"},kf(I.provider))),Ht.default.createElement("div",{className:"tw-flex tw-flex-row tw-items-center tw-gap-2"},Ht.default.createElement("div",{className:"tw-flex-1"},Ht.default.createElement(aC,{className:"tw-max-w-full",value:I.apiKey,onChange:R=>O(I.provider,R),disabled:r.has(I.provider)})),Ht.default.createElement("div",{className:"tw-w-[72px]"},I.isVerified?Ht.default.createElement("span",{className:"tw-flex tw-h-9 tw-items-center tw-justify-center tw-text-sm tw-text-success"},"Verified"):Ht.default.createElement(ge,{onClick:()=>P(I.provider,I.apiKey),disabled:!I.apiKey||r.size>0,variant:"secondary",size:"sm",className:"tw-w-full tw-whitespace-nowrap"},r.has(I.provider)?Ht.default.createElement(Yl,{className:"tw-mr-2 tw-size-4 tw-animate-spin"}):"Verify")),Ht.default.createElement("div",{className:""},Ht.default.createElement(ge,{onClick:()=>{let R=a===I.provider?null:I.provider;s(R),R&&I.apiKey&&u[I.provider]===void 0&&c!==I.provider&&f!==I.provider&&E(I.provider,I.apiKey)},disabled:!I.apiKey||r.size>0,variant:"secondary",size:"sm",className:"tw-flex tw-w-full tw-items-center tw-justify-center tw-gap-1 tw-whitespace-nowrap tw-p-0.5"},"Add Model",a===I.provider?Ht.default.createElement(Ey,{className:"tw-ml-1 tw-size-4"}):Ht.default.createElement(Hi,{className:"tw-ml-1 tw-size-4"})))),Ht.default.createElement("div",null,Xb(I.provider).keyManagementURL&&Ht.default.createElement("a",{href:Xb(I.provider).keyManagementURL,target:"_blank",rel:"noopener noreferrer",className:"tw-text-[10px] tw-text-accent hover:tw-text-accent-hover sm:tw-text-xs"},"Get ",kf(I.provider)," Key"))),Ht.default.createElement(cE,{open:a===I.provider,className:"tw-mt-2"},Ht.default.createElement(dE,{className:"tw-rounded-md tw-p-3"},Ht.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Ht.default.createElement(Yn,{label:"Model",description:"Add the currently selected model to model List. After adding, please check the Model Tab."},Ht.default.createElement("div",null,Ht.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Ht.default.createElement("div",{className:"tw-flex-1"},Ht.default.createElement(Wde,{options:u[I.provider]?.sort((R,N)=>R.name.localeCompare(N.name)).map(R=>({label:R.name,value:R.id}))||[],onChange:R=>{let N=R.target.value,j=u[I.provider]?.find($=>$.id===N);j&&h({id:j.id,name:j.name,provider:I.provider})},onClick:()=>{I.apiKey&&u[I.provider]===void 0&&c!==I.provider&&f!==I.provider&&E(I.provider,I.apiKey)},value:m?.provider===I.provider?m.id:"",placeholder:"Select Model",disabled:!I.apiKey||c===I.provider||f===I.provider&&u[I.provider]!==null})),Ht.default.createElement("div",{className:"tw-w-[72px]"},Ht.default.createElement(ge,{onClick:A,disabled:!m||m.provider!==I.provider||b,variant:"secondary",size:"sm",className:"tw-w-full tw-whitespace-nowrap"},b?Ht.default.createElement(Yl,{className:"tw-mr-2 tw-size-4 tw-animate-spin"}):"Add"))),Ht.default.createElement("div",{className:"tw-mt-1 tw-text-xs"},c===I.provider&&Ht.default.createElement("div",{className:"tw-p-1 tw-text-muted"},"Loading models..."),f===I.provider&&Ht.default.createElement("div",{className:"tw-p-1 tw-text-error"},"Failed to load models.",u[I.provider]===null&&" Check API Key or network."),u[I.provider]&&u[I.provider].length===0&&Ht.defaul Line truncated
/*! Bundled license information:
@langchain/core/dist/utils/fast-json-patch/src/helpers.js:
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "copilot",
"name": "Copilot",
"version": "2.9.3",
"version": "2.9.4",
"minAppVersion": "0.15.0",
"description": "Your AI Copilot: Chat with Your Second Brain, Learn Faster, Work Smarter.",
"author": "Logan Yang",
-1
View File
@@ -3321,7 +3321,6 @@
"资讯",
"人文",
"ChinaDaily",
"各种折腾",
"我的博客"
],
"renamedText": {
+19 -19
View File
@@ -32,17 +32,17 @@
}
},
{
"id": "3deeedcdbfd6f5e1",
"id": "7987b0c6b435b6c1",
"type": "leaf",
"state": {
"type": "markdown",
"state": {
"file": "80-笔记归档/归档说明.md",
"file": "40-Podcast/podnotes/和Emily一起练口语(附中英双语字幕)-【发音版】美国人说“我超喜欢”时,常会用这句话!.md",
"mode": "source",
"source": false
},
"icon": "lucide-file",
"title": "归档说明"
"title": "和Emily一起练口语(附中英双语字幕)-【发音版】美国人说“我超喜欢”时,常会用这句话!"
}
}
],
@@ -132,7 +132,7 @@
{
"id": "6eb65634f662a76d",
"type": "tabs",
"dimension": 48.65853658536585,
"dimension": 46.58536585365854,
"children": [
{
"id": "255862dc8754e160",
@@ -245,7 +245,7 @@
{
"id": "ad86bdfc0cc9f06b",
"type": "tabs",
"dimension": 51.34146341463415,
"dimension": 53.41463414634147,
"children": [
{
"id": "61523dba4992de80",
@@ -273,11 +273,12 @@
"state": {
"type": "copilot-chat-view",
"state": {},
"icon": "lucide-file",
"title": "插件不再活动"
"icon": "message-square",
"title": "Copilot"
}
}
]
],
"currentTab": 2
}
],
"direction": "horizontal",
@@ -310,10 +311,18 @@
"obsidian-memos:Thino": false
}
},
"active": "3deeedcdbfd6f5e1",
"active": "7987b0c6b435b6c1",
"lastOpenFiles": [
"40-Podcast/podnotes/陈说历史-雍正帝怎么死的?唐朝为何不建长城?方孝孺真的被诛十族?能否称刘邦为汉高祖?等.md",
"80-笔记归档/README-归档.md",
"80-笔记归档/81-工作日记/202508",
"80-笔记归档/82-待办计划/2025",
"80-笔记归档/81-工作日记/202507",
"README.md",
"80-笔记归档/82-待办计划",
"80-笔记归档/82-待办计划.md",
"80-笔记归档/81-工作日记",
"80-笔记归档/81-工作日记.md",
"80-笔记归档/归档说明.md",
"01-工作日记/2025-07-02.md",
"80-笔记归档",
"01-工作日记/2025-07-12.md",
@@ -324,7 +333,6 @@
"03-学习笔记/OB插件.md",
"02-技术评测/关于RSS.md",
"02-技术评测/笔记软件评测.md",
"README.md",
"00-待办计划/2025-07 待办事宜.md",
"10-WebClipper/AList的开源替代:OpenList.md",
"01-工作日记/2025-07-09.md",
@@ -332,26 +340,18 @@
"30-RSS/RSS阅读/阅读样本.md",
"20-我的收藏夹/21-浏览器收藏/开源项目/OnlyOffice/Hidocs文档在线预览平台提供office文档在线预览服务.md",
"40-Podcast/podnotes/和Emily一起练口语(附中英双语字幕)-【发音版】美国人说“我超喜欢”时,常会用这句话!.md",
"40-Podcast/podnotes/陈说历史-雍正帝怎么死的?唐朝为何不建长城?方孝孺真的被诛十族?能否称刘邦为汉高祖?等.md",
"01-工作日记/2025-07-08.md",
"40-Podcast/podnotes",
"40-Podcast",
"01-工作日记/2025-07-07.md",
"01-工作日记/2025-07-04.md",
"01-工作日记/2025-07-05.md",
"01-工作日记/2025-07-06.md",
"01-工作日记/未命名.md",
"screenshot 1.png",
"screenshot.png",
"工作日记",
"30-RSS/RSS阅读",
"08-Inbox/assets/68691ee74ca1b.png",
"08-Inbox/assets/yy88496nfr.png",
"08-Inbox/assets",
"09-Templates/copilot-custom-prompts",
"04-博客发布/040-系统技术",
"30-RSS/网文精选/assets",
"30-RSS/网文精选",
"10-WebClipper/assets/v2-9f9b51f2020f8fd18c421810cc179483_1440w.png",
"10-WebClipper/assets/v2-0bb091571c199e26882c3bbba78eaf15_1440w.png",
"10-WebClipper/assets/v2-f666b8a845692cd6fee65bfbc52a3c59_1440w.png",
View File
Whitespace-only changes.
File renamed without changes.