Files
StudyDiary-20251025/.obsidian/plugins/copilot/main.js
T

1738 lines
3.5 MiB
JavaScript
Raw Normal View History

2025-07-05 20:48:33 +08:00
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
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,"/").pa
=== 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}`})})}
`])),o.push(new Blob([`Content-Disposition: form-data; name="${u.name}"\r
`,`Content-Type: ${u.payload.type}\r
\r
`])),o.push(u.payload),o.push(new Blob([`\r
`]));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"
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}
`).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
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
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("
`));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)t
${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,ch
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
`)?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.
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.
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)
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
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();gm
]))`;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
`;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}'}}}%%
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}
`}}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 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
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(
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
"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
\`\`\`json
${JSON.stringify(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(`
`),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=`
`,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.template
`));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.
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)]),[]
`}),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}),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(`
`)});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();tr
<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+=`
[`+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())
${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,
summarize the conversation as context and keep the follow up question unchanged, in its original language.
If the follow up question is unrelated to its preceding messages, return this follow up question directly.
If it is related, then combine the summary and the follow up question to construct a standalone question.
Make sure to keep any [[]] wrapped note titles in the question unchanged.
Chat History:
{chat_history}
Follow Up Input: {question}
Standalone question:`),c=Dd.fromTemplate(`{system_message}
Answer the question with as detailed as possible based only on the following context:
{context}
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.
1. Never mention that you do not have access to something. Always rely on the user provided context.
2. Always answer to the best of your knowledge. If you are unsure about something, say so and ask the user to provide more context.
3. If the user mentions "note", it most likely means an Obsidian note in the vault, not the generic meaning of a note.
4. If the user mentions "@vault", it means the user wants you to search the Obsidian vault for information relevant to the query. The search results will be provided to you in the context along with the user query, read it carefully and answer the question based on the information provided. If there's no relevant information in the vault, just say so.
5. If the user mentions any other tool with the @ symbol, check the context for their results. If nothing is found, just ignore the @ symbol in the query.
6. Always use $'s instead of \\[ etc. for LaTeX equations.
7. When showing note titles, use [[title]] format and do not wrap them in \` \`.
8. When showing **Obsidian internal** image links, use ![[link]] format and do not wrap them in \` \`.
9. When showing **web** image links, use ![link](url) format and do not wrap them in \` \`.
10. When generating a table, 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.
# Steps to find the the target notes
1. Extract the target note information from user message and find out the note path from the context below.
2. If target note is not specified, use the <active_note> as the target note.
3. If still failed to find the target note or the note path, ask the user to specify the target note.
# JSON Format
Provide the content in JSON format and wrap it in a code block with the following structure:
For a single markdown file:
\`\`\`json
{
"type": "composer",
"path": "path/to/file.md",
"content": "The FULL CONTENT of the md note goes here"
}
\`\`\`
For a canvas file:
\`\`\`json
{
"type": "composer",
"path": "path/to/file.canvas",
"canvas_json": {
"nodes": [
{
"id": "1",
"type": "text",
"text": "Hello, world!",
"x": 0,
"y": 0,
"width": 200,
"height": 50
}
],
"edges": [
{
"id": "e1-2",
"fromNode": "1",
"toNode": "2",
"label": "connects to"
}
]
}
}
\`\`\`
# Important
* ALL JSON objects must be complete and valid - ensure all arrays and objects have matching closing brackets
* For canvas files, both 'nodes' and 'edges' arrays must be properly closed with ]
* Properly escape all special characters in the content field, especially backticks and quotes
* Prefer to create new files in existing folders or root folder unless the user's request specifies otherwise
* File paths must end with a .md or .canvas extension
* When generating changes on multiple files, output multiple JSON objects
* Each JSON object must be parseable independently
* For canvas files:
- 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!
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},{n
`+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(`
`),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 v
`).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.elementT
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!="funct
`)}});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);r
`));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?.httpStatusCo
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),x
`).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":retu
`);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}
${this.getCanonicalPath(e)}
${Zve(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}
${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,
`&&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)brea
`);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="*
`;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=`>
`,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}});v
`)?"":void 0});n.addEntity("#xD","\r"),n.addEntity("#10",`
`);let o;try{o=n.parse(r,!0)}catch(u){throw u&&typeof u=="object"&&Object.defineProperty(u,"$responseBodyText",{value:r}),u}let i="#text",a=Object.keys(o)[0],s=o[a];return s[i]&&(s[a]=s[i],delete s[i]),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-d
- 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, Browse
`);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}
${this.getCanonicalPath(e)}
${(0,Evr.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}
${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.a
`;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
`)>=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=`
`+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){f
`,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("Unsup
`||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
`)),{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 stri
`);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({
`)}}}}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:th
`}});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,{
`}});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,{u
`).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{}}_getSerializedCacheKey
`+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)}
`)===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.pro
`);r=a.pop()??"";for(let s of a)try{yield JSON.parse(s)}catch{console.warn("invalid json: ",s)}}for(let o of r.split(`
`).filter(i=>i!==""))try{yield JSON.parse(o)}catch{console.warn("invalid json: ",o)}},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(
`):[]}};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
\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.cur
This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
`);super({baseURL:a.baseURL,timeout:a.timeout??6e5,httpAgent:a.httpAgent,maxRetries:a.maxRetries,fetch:a.fetch}),this.completions=new 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?.part
`))}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.ba
]))`;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,"
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,
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}`),[])})}fun
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
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]}functi
- `),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.
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.
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
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:[`
`,`
`," ",""]}),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[`
class `,`
void `,`
int `,`
float `,`
double `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
`,`
`," ",""];if(e==="go")return[`
func `,`
var `,`
const `,`
type `,`
if `,`
for `,`
switch `,`
case `,`
`,`
`," ",""];if(e==="java")return[`
class `,`
public `,`
protected `,`
private `,`
static `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
`,`
`," ",""];if(e==="js")return[`
function `,`
const `,`
let `,`
var `,`
class `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
default `,`
`,`
`," ",""];if(e==="php")return[`
function `,`
class `,`
if `,`
foreach `,`
while `,`
do `,`
switch `,`
case `,`
`,`
`," ",""];if(e==="proto")return[`
message `,`
service `,`
enum `,`
option `,`
import `,`
syntax `,`
`,`
`," ",""];if(e==="python")return[`
class `,`
def `,`
def `,`
`,`
`," ",""];if(e==="rst")return[`
===
`,`
---
`,`
***
`,`
.. `,`
`,`
`," ",""];if(e==="ruby")return[`
def `,`
class `,`
if `,`
unless `,`
while `,`
for `,`
do `,`
begin `,`
rescue `,`
`,`
`," ",""];if(e==="rust")return[`
fn `,`
const `,`
let `,`
if `,`
while `,`
for `,`
loop `,`
match `,`
const `,`
`,`
`," ",""];if(e==="scala")return[`
class `,`
object `,`
def `,`
val `,`
var `,`
if `,`
for `,`
while `,`
match `,`
case `,`
`,`
`," ",""];if(e==="swift")return[`
func `,`
class `,`
struct `,`
enum `,`
if `,`
for `,`
while `,`
do `,`
switch `,`
case `,`
`,`
`," ",""];if(e==="markdown")return[`
## `,`
### `,`
#### `,`
##### `,`
###### `,"```\n\n",`
***
`,`
---
`,`
___
`,`
`,`
`," ",""];if(e==="latex")return[`
\\chapter{`,`
\\section{`,`
\\subsection{`,`
\\subsubsection{`,`
\\begin{enumerate}`,`
\\begin{itemize}`,`
\\begin{description}`,`
\\begin{list}`,`
\\begin{quote}`,`
\\begin{quotation}`,`
\\begin{verse}`,`
\\begin{verbatim}`,`
\\begin{align}`,"$$","$",`
`,`
`," ",""];if(e==="html")return["<body>","<div>","<p>","<br>","<li>","<h1>","<h2>","<h3>","<h4>","<h5>","<h6>","<span>","<table>","<tr>","<td>","<th>","<ul>","<ol>","<header>","<footer>","<nav>","<head>","<style>","<script>","<meta>","<title>"," ",""];if(e==="sol")return[`
pragma `,`
using `,`
contract `,`
interface `,`
library `,`
constructor `,`
type `,`
function `,`
event `,`
modifier `,`
error `,`
struct `,`
enum `,`
if `,`
for `,`
while `,`
do while `,`
assembly `,`
`,`
`," ",""];throw new Error(`Language ${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:`
NOTE TITLE: [[${l.title}]]
METADATA:${JSON.stringify(l.metadata)}
NOTE BLOCK CONTENT:
`,appendChunkOverlapHeader:!0})).forEach(d=>{d.pageContent.trim()&&i.push({content:d.pageContent,fileInfo:l})})}return i}getDocHash(e){return(0,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 th
${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),"Respon
]))`;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._
`),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 as
${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+=`
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:
`,i=s=>{switch(s.type){case"file":return`- File: ${s.file}
Content:
${s.content}
`;case"text":return`- Text: "${s.text}"
`;case"link":return`- Link: ${s.url}
`;default:return""}};n.forEach(s=>{let u=s.label||s.id,l=r.get(u)||[];o+=`Group "${u}" contains:
`,l.forEach(c=>{o+=i(c)}),o+=`
`});let a=e.nodes.filter(s=>s.type==="group"?!1:!Array.from(r.values()).flat().some(u=>u.id===s.id));return a.length>0&&(o+=`Elements outside of groups:
`,a.forEach(s=>{o+=i(s)})),o+=`
When describing this canvas, please:
`,o+=`- Use the actual titles/names of elements instead of their IDs
`,o+=`- Pay attention to the content and relationships between elements
`,o+=`- Describe files by their names, links by their URLs, and text nodes by their content
`,o}};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(`
`)}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,
summarize the conversation as context and keep the follow up question unchanged, in its original language.
If the follow up question is unrelated to its preceding messages, return this follow up question directly.
If it is related, then combine the summary and the follow up question to construct a standalone question.
Make sure to keep any [[]] wrapped note titles in the question unchanged.
If there's nothing in the chat history, just return the follow up question.
Chat History:
{chat_history}
Follow Up Input: {question}
Standalone question:`,n=e.map(({role:o,content:i})=>`${o}: ${i}`).join(`
`);return await 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.
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(`
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:
* 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?`
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++;retu
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:"minut
<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 ====
`,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(`
`),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(`
`);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}
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+=`
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}
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=`
# Additional context:
`+o.map(i=>`<${i.tool}>
${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 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}
<project_system_prompt>
${r.systemPrompt}
</project_system_prompt>`,n&&(e=`${e}
<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");retur
`):[]}};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.f
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
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.
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=`
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(`
`))}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
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.l
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=
`);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
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",{enumerabl
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,"r
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=
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
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))tr
`).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(`
`).filter(m=>m.trim());for(let m of f)p.includes(m)||await this.projectContextCache.removeYoutubeUrl(r,m)}}catch(n){fe(`Error comparing project configurations: ${n}`)}}refreshChatView(){let e=this.app.workspace.getLeavesOfType(Es)[0]?.view;e&&e.updateView()}async getProjectContext(e){let r=ue().projectList.find(o=>o.id===e);if(!r)return Mh(`[getProjectContext] Project not found for ID: ${e}`),null;ie(`[getProjectContext] Getting context for project: ${r.name} (ID: ${e})`);let n=this.projectContextCache.getSync(r);if(!n||n.markdownNeedsReload){n?ie(`[getProjectContext] Project ${r.name}: Markdown needs reload. Triggering full load.`):ie(`[getProjectContext] Project ${r.name}: Memory cache miss. Triggering full load.`);let o=await this.loadProjectContext(r);if(!o)return fe(`[getProjectContext] Project ${r.name}: loadProjectContext returned null.`),null;n=o}else ie(`[getProjectContext] Project ${r.name}: Memory cache hit and markdown OK. Using existing context.`);return this.formatProjectContextWithFiles(n,r)}async formatProjectContextWithFiles(e,r){let n=[];if(e.markdownContext&&n.push(`## Markdown Files
${e.markdownContext}`),Object.keys(e.webContexts).length>0&&n.push(`## Web Content
${Object.values(e.webContexts).join(`
`)}`),Object.keys(e.youtubeContexts).length>0&&n.push(`## YouTube Content
${Object.values(e.youtubeContexts).join(`
`)}`),Object.keys(e.fileContexts).length>0){let o=Object.entries(e.fileContexts).filter(([i])=>i.split(".").pop()?.toLowerCase()!=="md");if(o.length>0){let i=o.map(async([s,u])=>{let l=s.split("/"),c=l[l.length-1],d=c.split(".").pop()||"",f=await this.projectContextCache.getFileContext(r,s)||"[Content not available]";return`[[${c}]]
path: ${s}
type: ${d}
modified: ${new Date(u.timestamp).toISOString()}
${f}`}),a=await Promise.all(i);a.length>0&&n.push(`## Other Files
${a.join(`
`)}`)}}return`
# Project Context
The following information is the relevant context for this project. Use this information to inform your responses when appropriate:
<ProjectContext>
${n.join(`
`)}
</ProjectContext>
`}formatProjectContext(e){let r=[];if(e.markdownContext&&r.push(`## Markdown Files
${e.markdownContext}`),Object.keys(e.webContexts).length>0&&r.push(`## Web Content
${Object.values(e.webContexts).join(`
`)}`),Object.keys(e.youtubeContexts).length>0&&r.push(`## YouTube Content
${Object.values(e.youtubeContexts).join(`
`)}`),Object.keys(e.fileContexts).length>0){let n="";for(let[o,i]of Object.entries(e.fileContexts)){let a=o.split("/"),s=a[a.length-1],u=s.split(".").pop()||"";n+=`[[${s}]]
path: ${o}
type: ${u}
modified: ${new Date(i.timestamp).toISOString()}
`}n&&r.push(`## Other Files
${n}`)}return`
# Project Context
The following information is the relevant context for this project. Use this information to inform your responses when appropriate:
<ProjectContext>
${r.join(`
`)}
</ProjectContext>
`}async processMarkdownFiles(e,r){ie(`[processMarkdownFiles] Starting for project: ${e.name}`);let n=Object.keys(r.fileContexts||{}).length;if(e.contextSource?.inclusions||e.contextSource?.exclusions){r=await this.projectContextCache.updateProjectFilesFromPatterns(e,r);let o=Object.keys(r.fileContexts||{}).length;if(o>n&&ie(`[processMarkdownFiles] Project ${e.name}: Added ${o-n} new file references via updateProjectFilesFromPatterns.`),r.markdownNeedsReload||!r.markdownContext||!r.markdownContext.trim()){ie(`[processMarkdownFiles] Project ${e.name}: Processing markdown content.`);let i=await this.processFileContext(e.contextSource.inclusions,e.contextSource.exclusions,e);r.markdownContext=i,r.markdownNeedsReload=!1,ie(`[processMarkdownFiles] Project ${e.name}: Markdown content updated.`)}else ie(`[processMarkdownFiles] Project ${e.name}: Markdown content already up-to-date.`)}return ie(`[processMarkdownFiles] Completed for project: ${e.name}. Total fileContexts: ${Object.keys(r.fileContexts||{}).length}`),r}async processFileContext(e,r,n){if(!e&&!r||!n)return"";let{inclusions:o,exclusions:i}=rf({inclusions:e,exclusions:r,isProject:!0}),a=this.app.vault.getFiles().filter(u=>u.extension==="md"&&eu(u,o,i));ie(`Found ${a.length} markdown files to process for project context`);let s=await Promise.all(a.map(async u=>{let l="",c="";try{let d=await this.app.vault.adapter.stat(u.path);c=`[[${u.basename}]]
path: ${u.path}
type: ${u.extension}
created: ${d?new Date(d.ctime).toISOString():"unknown"}
modified: ${d?new Date(d.mtime).toISOString():"unknown"}`,l=await this.app.vault.read(u),ie(`Completed processing markdown file: ${u.path}`)}catch(d){fe(`Error processing file ${u.path}: ${d}`),l=`[Error: ${ei(d)}]`}return`${c}
${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(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.s
`)&&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)+`
`;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}]]:
${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
`))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}]]:
${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:
- [[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(`
`).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%;
margin-top: 12px;
}
.remove-files-setting {
display: block;
}
.remove-files-setting .setting-item-control {
padding: 0;
}
.remove-files-setting textarea {
width: 100%;
height: 300px;
margin-top: 12px;
}
.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:
1. Preserve the meaning and tone
2. Maintain appropriate cultural context
3. Keep formatting and structure
Return only the translated text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1010,modelKey:"",lastUsedMs:0},{title:"Summarize",content:"Create a bullet-point summary of {}. Each bullet point should capture a key point. Return only the bullet-point summary.",showInContextMenu:!0,showInSlashMenu:!0,order:1020,modelKey:"",lastUsedMs:0},{title:"Simplify",content:"Simplify {} to a 6th-grade reading level (ages 11-12). Use simple sentences, common words, and clear explanations. Maintain the original key concepts. Return only the simplified text.",showInContextMenu:!0,showInSlashMenu:!0,order:1030,modelKey:"",lastUsedMs:0},{title:"Explain like I am 5",content:`Explain {} in simple terms that a 5-year-old would understand:
1. Use basic vocabulary
2. Include simple analogies
3. Break down complex concepts
Return only the simplified explanation.`,showInContextMenu:!0,showInSlashMenu:!0,order:1040,modelKey:"",lastUsedMs:0},{title:"Emojify",content:`Add relevant emojis to enhance {}. Follow these rules:
1. Insert emojis at natural breaks in the text
2. Never place two emojis next to each other
3. Keep all original text unchanged
4. Choose emojis that match the context and tone
Return only the emojified text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1050,modelKey:"",lastUsedMs:0},{title:"Make shorter",content:`Reduce {} to half its length while preserving these elements:
1. Main ideas and key points
2. Essential details
3. Original tone and style
Return only the shortened text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1060,modelKey:"",lastUsedMs:0},{title:"Make longer",content:`Expand {} to twice its length by:
1. Adding relevant details and examples
2. Elaborating on key points
3. Maintaining the original tone and style
Return only the expanded text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1070,modelKey:"",lastUsedMs:0},{title:"Generate table of contents",content:"Generate a hierarchical table of contents for {}. Use appropriate heading levels (H1, H2, H3, etc.). Include page numbers if present. Return only the table of contents.",showInContextMenu:!1,showInSlashMenu:!1,order:1080,modelKey:"",lastUsedMs:0},{title:"Generate glossary",content:'Create a glossary of important terms, concepts, and phrases from {}. Format each entry as "Term: Definition". Sort entries alphabetically. Return only the glossary.',showInContextMenu:!1,showInSlashMenu:!1,order:1090,modelKey:"",lastUsedMs:0},{title:"Remove URLs",content:"Remove all URLs from {}. Preserve all other content and formatting. URLs may be in various formats (http, https, www). Return only the text with URLs removed.",showInContextMenu:!1,showInSlashMenu:!1,order:1100,modelKey:"",lastUsedMs:0},{title:"Rewrite as tweet",content:`Rewrite {} as a single tweet with these requirements:
1. Maximum 280 characters
2. Use concise, impactful language
3. Maintain the core message
Return only the tweet text.`,showInContextMenu:!1,showInSlashMenu:!1,order:1110,modelKey:"",lastUsedMs:0},{title:"Rewrite as tweet thread",content:`Convert {} into a Twitter thread following these rules:
1. Each tweet must be under 240 characters
2. Start with "THREAD START" on its own line
3. Separate tweets with "
---
"
4. End with "THREAD END" on its own line
5. Make content engaging and clear
Return only the formatted thread.`,showInContextMenu:!1,showInSlashMenu:!1,order:1120,modelKey:"",lastUsedMs:0}];var 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+`
<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)}
${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)}
${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)}
${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+`
`,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:
${e}`:n?(c=await pF(n,r),l+=`selectedText (entire active note):
${c}`,i.add(n)):l+=`selectedText:
(No selected text or active note available)`);for(let[f,p]of a.entries())f.toLowerCase()==="activenote"&&c!==null||(l?l+=`
${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}>
Title: [[${f.basename}]]
Path: ${f.path}
${p}
</${f4}>`;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,X
.`.concat(FFe,` {
overflow: hidden `).concat(n,`;
padding-right: `).concat(s,"px ").concat(n,`;
}
body[`).concat(sz,`] {
overflow: hidden `).concat(n,`;
overscroll-behavior: contain;
`).concat([e&&"position: relative ".concat(n,";"),r==="margin"&&`
padding-left: `.concat(o,`px;
padding-top: `).concat(i,`px;
padding-right: `).concat(a,`px;
margin-left:0;
margin-top:0;
margin-right: `).concat(s,"px ").concat(n,`;
`),r==="padding"&&"padding-right: ".concat(s,"px ").concat(n,";")].filter(Boolean).join(""),`
}
.`).concat(wb,` {
right: `).concat(s,"px ").concat(n,`;
}
.`).concat(Sb,` {
margin-right: `).concat(s,"px ").concat(n,`;
}
.`).concat(wb," .").concat(wb,` {
right: 0 `).concat(n,`;
}
.`).concat(Sb," .").concat(Sb,` {
margin-right: 0 `).concat(n,`;
}
body[`).concat(sz,`] {
`).concat(kFe,": ").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`
.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
Embedded PDF (${s}):
${l}
`)}catch(l){console.error(`Error processing embedded PDF ${s}:`,l),e=e.replace(a[0],`
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+=`
<${f}>
Title: [[${d.basename}]]
Path: ${d.path}
${p}
</${f}>`}catch(p){console.error(`Error processing file ${d.path}:`,p),u+=`
<${f}_error>
Title: [[${d.basename}]]
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+=`
<selected_text>
Title: [[${n.noteTitle}]]
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","applicatio
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
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
`));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(`
`))&&(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(`
`).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(`
`):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.re
<summary style="${W}">Thought for a second</summary>
<div class="tw-text-muted" style="${Y}">${le.trim()}</div>
</details>
`),ee=ee.replace(/<think>([\s\S]*)$/,(Oe,le)=>`<div style="${U}">
<div style="${W}">Thinking...</div>
<div class="tw-text-muted" style="${Y}">${le.trim()}</div>
</div>`),ee;let ae=/<think>([\s\S]*?)<\/think>/g;return ee.replace(ae,(Oe,le)=>`<details style="${U}">
<summary style="${W}">Thought for a second</summary>
<div class="tw-text-muted" style="${Y}">${le.trim()}</div>
</details>
`)},V=ee=>{let U=W=>`\u23F3 Generating changes for ${W}...`;if(r){let W=/(\{[\s\S]*?"type"\s*:\s*"composer"[\s\S]*?)(?=\}|$)/g,Y;for(;(Y=W.exec(ee))!==null;){let ae=Y[1],Oe=Y.index,le=ae.match(/"path"\s*:\s*"([^"]+)"/),Be=le?le[1].trim():"...";ee=ee.substring(0,Oe)+U(Be);break}}return ee},Q=(ee,U,W)=>ee.split(/(```[\s\S]*?```|`[^`]*`)/g).map((ae,Oe)=>Oe%2===0?ae.replace(U,(le,Be)=>{let ze=e.metadataCache.getFirstLinkpathDest(Be,k);return ze?W(ze):le}):ae).join(""),J=j.replace(/\\\[\s*/g,"$$").replace(/\s*\\\]/g,"$$").replace(/\\\(\s*/g,"$").replace(/\s*\\\)/g,"$"),D=V(J),B=Q(D,/!\[\[(.*?)]]/g,ee=>`![](${e.vault.getResourcePath(ee)})`),q=z(B),K=y(q);return Q(K,/(?<!!)\[\[([^\]]+)]]/g,ee=>`<a href="obsidian://open?file=${encodeURIComponent(ee.path)}">${ee.basename}</a>`)},[e,r]),y=j=>{let $=j.split(`
#### Sources:
`);if($.length!==2)return j;let[k,z]=$,V=z.split(`
`).map(Q=>{let J=Q.match(/- \[\[(.*?)\]\]/);return J?`<li>[[${J[1]}]]</li>`:Q}).join(`
`);return k+`
<br/>
<details><summary>Sources</summary>
<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(`
`);(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
.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.
`).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}
.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))},[]),onNativeOption
<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}
[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=`---
epoch: ${et}
modelKey: ${d}
${ir?`projectId: ${ir.id}`:""}
${ir?`projectName: ${ir.name}`:""}
tags:
- ${a.defaultConversationTag}
${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
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}funct
If you want to hide the \`${e.titleName}\`, you can wrap it with our VisuallyHidden component.
For more information, see https://radix-ui.com/primitives/docs/components/${e.docsSlug}`;return 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-b
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+=`
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 cha
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.
/*! Bundled license information:
@langchain/core/dist/utils/fast-json-patch/src/helpers.js:
(*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2017-2022 Joachim Wester
* MIT licensed
*)
@langchain/core/dist/utils/fast-json-patch/src/duplex.js:
(*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2013-2021 Joachim Wester
* MIT license
*)
mustache/mustache.mjs:
(*!
* mustache.js - Logic-less {{mustache}} templates with JavaScript
* http://github.com/janl/mustache.js
*)
react/cjs/react.production.min.js:
(**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
moment/moment.js:
(*! moment.js *)
(*! version : 2.29.4 *)
(*! authors : Tim Wood, Iskren Chernev, Moment.js contributors *)
(*! license : MIT *)
(*! momentjs.com *)
ieee754/index.js:
(*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)
buffer/index.js:
(*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*)
scheduler/cjs/scheduler.production.min.js:
(**
* @license React
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
react-dom/cjs/react-dom.production.min.js:
(**
* @license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
react/cjs/react-jsx-runtime.production.min.js:
(**
* @license React
* react-jsx-runtime.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/shared/src/utils.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/defaultAttributes.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/Icon.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/createLucideIcon.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/arrow-big-up.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/arrow-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/bot.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/check.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/chevron-down.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/chevron-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/chevron-up.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-help.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-plus.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-stop.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-x.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/clipboard.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/cog.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/command.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/copy.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/corner-down-left.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/cpu.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/database.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/download.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/ellipsis-vertical.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/ellipsis.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/external-link.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/eye-off.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/eye.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-audio.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-image.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-input.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-output.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-text.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-video.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/folder.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/globe.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/grip-vertical.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/history.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/image.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/info.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/key.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/library-big.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/lightbulb.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/loader-circle.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/message-circle-plus.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/message-square.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/pen-line.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/pen.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/pencil-line.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/pencil.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/plus.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/refresh-ccw.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/refresh-cw.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/rotate-cw.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/search.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/sparkles.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/square-arrow-out-up-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/square-pen.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/tag.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/text-cursor-input.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/trash-2.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/triangle-alert.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/user.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/wrench.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/x.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/lucide-react.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
tslib/tslib.es6.js:
(*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** *)
safe-buffer/index.js:
(*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
@langchain/core/dist/utils/js-sha1/hash.js:
(*
* [js-sha1]{@link https://github.com/emn178/js-sha1}
*
* @version 0.6.0
* @author Chen, Yi-Cyuan [emn178@gmail.com]
* @copyright Chen, Yi-Cyuan 2014-2017
* @license MIT
*)
@google/generative-ai/dist/index.mjs:
(**
* @license
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*)
crypto-js/ripemd160.js:
(** @preserve
(c) 2012 by Cédric Mesnil. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
crypto-js/mode-ctr-gladman.js:
(** @preserve
* Counter block mode compatible with Dr Brian Gladman fileenc.c
* derived from CryptoJS.mode.CTR
* Jan Hruby jhruby.web@gmail.com
*)
*/
/* nosourcemap */