vars8t=Object.create;var_$=Object.defineProperty;varu8t=Object.getOwnPropertyDescriptor;varl8t=Object.getOwnPropertyNames;varc8t=Object.getPrototypeOf,d8t=Object.prototype.hasOwnProperty;varf8t=(e,t,r)=>tine?_$(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;varC=(e,t)=>()=>(e&&(t=e(e=0)),t);varb=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Kd=(e,t)=>{for(varrint)_$(e,r,{get:t[r],enumerable:!0})},B1e=(e,t,r,n)=>{if(t&&typeoft=="object"||typeoft=="function")for(letoofl8t(t))!d8t.call(e,o)&&o!==r&&_$(e,o,{get:()=>t[o],enumerable:!(n=u8t(t,o))||n.enumerable});returne};varB=(e,t,r)=>(r=e!=null?s8t(c8t(e)):{},B1e(t||!e||!e.__esModule?_$(r,"default",{value:e,enumerable:!0}):r,e)),il=e=>B1e(_$({},"__esModule",{value:!0}),e);varNl=(e,t,r)=>f8t(e,typeoft!="symbol"?t+"":t,r);functionh8t(e){U1e=e}functiong6(){returnU1e}functionHe(e,t){letr=g6(),n=y6({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===bD?void0:bD].filter(o=>!!o)});e.common.issues.push(n)}functionb6(e,t,r,n){if(r==="a"&&!n)thrownewTypeError("Private accessor was defined without a getter");if(typeoft=="function"?e!==t||!n:!t.has(e))thrownewTypeError("Cannot read private member from an object whose class did not declare it");returnr==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)}functionz1e(e,t,r,n,o){if(n==="m")thrownewTypeError("Private method is not writable");if(n==="a"&&!o)thrownewTypeError("Private accessor was defined without a setter");if(typeoft=="function"?e!==t||!o:!t.has(e))thrownewTypeError("Cannot write private member to an object whose class did not declare it");returnn==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r}functiongr(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))thrownewError(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);returnt?{errorMap:t,description:o}:{errorMap:(a,s)=>{varu,l;let{message:c}=e;returna.code==="invalid_enum_value"?{message:c??s.defaultError}:typeofs.data>"u"?{message:(u=c??n)!==null&&u!==void0?u:s.defaultError}:a.code!=="invalid_type"?{message:s.defaultError}:{message:(l=c??r)!==null&&l!==void0?l:s.defaultError}},description:o}}functionV1e(e){lett="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";returne.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`),t}functionR8t(e){returnnewRegExp(`^${V1e(e)}$`)}functionW1e(e){lett=`${H1e}T${V1e(e)}`,r=[];returnr.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,newRegExp(`^${t}$`)}functionD8t(e,t){return!!((t==="v4"||!t)&&O8t.test(e)||(t==="v6"||!t)&&P8t.test(e))}functionj8t(e,t){if(!w8t.test(e))return!1;try{let[r]=e.split("."),n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeofo!="object"||o===null||!o.typ||!o.alg||t&&o.alg!==t)}catch{return!1}}functionN8t(e,t){return!!((t==="v4"||!t)&&E8t.test(e)||(t==="v6"||!t)&&T8t.test(e))}functionL8t(e,t){letr=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,i=parseInt(e.toFixed(o).replace(".","")),a=parseInt(t.toFixed(o).replace(".",""));returni%a/Math.pow(10,o)}functiongD(e){if(einstanceofZd){lett={};for(letrine.shape){letn=e.shape[r];t[r]=Yd.create(gD(n))}returnnewZd({...e._def,shape:()=>t})}elsereturneinstanceofhS?newhS({...e._def,type:gD(e.element)}):einstanceofYd?Yd.create(gD(e.unwrap())):einstanceofQg?Qg.create(gD(e.unwrap())):einstanceofXg?Xg.create(e.items.map(t=>gD(t))):e}functionxae(e,t){letr=fS(e),n=fS(t);if(e===t)return{valid:!0,data:e};if(r===Qe.object&&n===Qe.object){leto=Sn.objectKeys(t),i=Sn.objectKeys(e).filter(s=>o.indexOf(s)!==-1),a={...e,...t};for(letsofi){letu=xae(e[s],t[s]);if(!u.valid)return{valid:!1};a[s]=u.data}return{valid:!0,data:a}}elseif(r===Qe.array&&n===Qe.array){if(e.length!==t.length)return{valid:!1};leto=[];for(leti=0;i<e.length;i++){leta=e[i],s=t[i],u=xae(a,s);if(!u.valid)return{valid:!
Context:${r}`)}}async updateRun(t,r){en(t),r.inputs&&(r.inputs=this.processInputs(r.inputs)),r.outputs&&(r.outputs=this.processOutputs(r.outputs));let n={...r,id:t};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(wt(),`${this.apiUrl}/runs/${t}`,{method:"PATCH",headers:o,body:ef(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(i,"update run",!0)}async readRun(t,{loadChildRuns:r}={loadChildRuns:!1}){en(t);let n=await this._get(`/runs/${t}`);return r&&n.child_run_ids&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:t,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:yS("PROJECT")||"default"})).id;let i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${o}/r/${r.id}?poll=true`}else if(t!==void 0){let o=await this.readRun(t);if(!o.app_path)throw new Error(`Run${t}hasnoapp_path`);return`${this.getHostUrl()}${o.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(t){let r=await J5t(this.listRuns({id:t.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(`Childrun${i.id}hasnoparent`);i.parent_run_id in n||(n[i.parent_run_id]=[]),n[i.parent_run_id].push(i),o[i.id]=i}t.child_runs=n[t.id]||[];for(let i in n)i!==t.id&&(o[i].child_runs=n[i]);return t}async*listRuns(t){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:h,traceFilter:m,treeFilter:_,limit:g,select:v}=t,S=[];if(r&&(S=Array.isArray(r)?r:[r]),n){let E=Array.isArray(n)?n:[n],M=await Promise.all(E.map(A=>this.readProject({projectName:A}).then(j=>j.id)));S.push(...M)}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:h,trace_filter:m,tree_filter:_,execution_order:u,parent_run:o,start_time:s?s.toISOString():null,error:d,id:f,limit:g,trace:i,select:v||x,is_root:l},T=0;for await(let E of this._getCursorPaginatedList("/runs/query",O))if(g){if(T>=g)break;if(E.length+T>g){yield*E.slice(0,g-T);break}T+=E.length,yield*E}else yield*E}async getRunStats({id:t,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:h,isRoot:m,dataSourceType:_}){let g=a||[];i&&(g=[...a||[],...await Promise.all(i.map(T=>this.readProject({projectName:T}).then(E=>E.id)))]);let S=Object.fromEntries(Object.entries({id:t,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:h,is_root:m,data_source_type:_}).filter(([T,E])=>E!==void 0));return await(await this.caller.call(wt(),`${this.apiUrl}/runs/stats`,{method:"POST",headers:this.headers,body:JSON.stringify(S),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json()}async shareRun(t,{shareId:r}={}){let n={run_id:t,share_token:r||dO()};en(t);let i=await(await this.caller.call(wt(),`${this.apiUrl}/runs/${t}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(
Status:${i.status}
Message:${a.detail.join(`
`)}`):newError(`Failed to list shared examples: ${i.status}${i.statusText}`);returna.map(s=>({...s,_hostUrl:this.getHostUrl()}))}asynccreateProject({projectName:t,description:r=null,metadata:n=null,upsert:o=!1,projectExtra:i=null,referenceDatasetId:a=null}){lets=o?"?upsert=true":"",u=`${this.apiUrl}/sessions${s}`,l=i||{};n&&(l.metadata=n);letc={name:t,extra:l,description:r};a!==null&&(c.reference_dataset_id=a);letd=awaitthis.caller.call(wt(),u,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(c),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});returnawaitqr(d,"create project"),awaitd.json()}asyncupdateProject(t,{name:r=null,description:n=null,metadata:o=null,projectExtra:i=null,endTime:a=null}){lets=`${this.apiUrl}/sessions/${t}`,u=i;o&&(u={...u||{},metadata:o});letl={name:r,extra:u,description:n,end_time:a?newDate(a).toISOString():null},c=awaitthis.caller.call(wt(),s,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});returnawaitqr(c,"update project"),awaitc.json()}asynchasProject({projectId:t,projectName:r}){letn="/sessions",o=newURLSearchParams;if(t!==void0&&r!==void0)thrownewError("Must provide either projectName or projectId, not both");if(t!==void0)en(t),n+=`/${t}`;elseif(r!==void0)o.append("name",r);elsethrownewError("Must provide projectName or projectId");leti=awaitthis.caller.call(wt(),`${this.apiUrl}${n}?${o}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});try{leta=awaiti.json();returni.ok?Array.isArray(a)?a.length>0:!0:!1}catch{return!1}}asyncreadProject({projectId:t,projectName:r,includeStats:n}){leto="/sessions",i=newURLSearchParams;if(t!==void0&&r!==void0)thrownewError("Must provide either projectName or projectId, not both");if(t!==void0)en(t),o+=`/${t}`;elseif(r!==void0)i.append("name",r);elsethrownewError("Must provide projectName or projectId");n!==void0&&i.append("include_stats",n.toString());leta=awaitthis._get(o,i),s;if(Array.isArray(a)){if(a.length===0)thrownewError(`Project[id=${t}, name=${r}] not found`);s=a[0]}elses=a;returns}asyncgetProjectUrl({projectId:t,projectName:r}){if(t===void0&&r===void0)thrownewError("Must provide either projectName or projectId");letn=awaitthis.readProject({projectId:t,projectName:r}),o=awaitthis._getTenantId();return`${this.getHostUrl()}/o/${o}/projects/p/${n.id}`}asyncgetDatasetUrl({datasetId:t,datasetName:r}){if(t===void0&&r===void0)thrownewError("Must provide either datasetName or datasetId");letn=awaitthis.readDataset({datasetId:t,datasetName:r}),o=awaitthis._getTenantId();return`${this.getHostUrl()}/o/${o}/datasets/${n.id}`}async_getTenantId(){if(this._tenantId!==null)returnthis._tenantId;lett=newURLSearchParams({limit:"1"});forawait(letrofthis._getPaginated("/sessions",t))returnthis._tenantId=r[0].tenant_id,r[0].tenant_id;thrownewError("No projects found to resolve tenant.")}async*listProjects({projectIds:t,name:r,nameContains:n,referenceDatasetId:o,referenceDatasetName:i,referenceFree:a,metadata:s}={}){letu=newURLSearchParams;if(t!==void0)for(letloft)u.append("id",l);if(r!==void0&&u.append("name",r),n!==void0&&u.append("name_contains",n),o!==void0)u.append("reference_dataset",o);elseif(i!==void0){letl=awaitthis.readDataset({datasetName:i});u.append("reference_dataset",l.id)}a!==void0&&u.append("reference_free",a.toString()),s!==void0&&u.append("metadata",JSON.stringify(s));forawait(letlofthis._getPaginated("/sessions",u))yield*l}asyncdeleteProject({projectId:t,projectName:r}){letn;if(t===void0&&r===void0)thrownewError("Must provide projectName or projectId");if(t!==void0&&r!==void0)thrownewError("Must provide either projectName or projectId, not both");t===void0?n=(awaitthis.readProject({projectName:r})).id:n=t,en(n);leto=awaitthis.caller.call(wt(),`${this.apiUrl}/sessions/${n}`,{method:"DELETE",headers:this.headers,
`).map(s=>JSON.parse(s))}async*listDatasets({limit:t=100,offset:r=0,datasetIds:n,datasetName:o,datasetNameContains:i,metadata:a}={}){let s="/datasets",u=new URLSearchParams({limit:t.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(t){let{datasetId:r,datasetName:n,...o}=t;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let i=r??(await this.readDataset({datasetName:n})).id;en(i);let a=await this.caller.call(wt(),`${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 qr(a,"update dataset"),await a.json()}async deleteDataset({datasetId:t,datasetName:r}){let n="/datasets",o=t;if(t!==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)en(o),n+=`/${o}`;else throw new Error("Must provide datasetName or datasetId");let i=await this.caller.call(wt(),this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(i,`delete${n}`),await i.json()}async indexDataset({datasetId:t,datasetName:r,tag:n}){let o=t;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),en(o);let i={tag:n},a=await this.caller.call(wt(),`${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 qr(a,"index dataset"),await a.json()}async similarExamples(t,r,n,{filter:o}={}){let i={limit:n,inputs:t};o!==void 0&&(i.filter=o),en(r);let a=await this.caller.call(wt(),`${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 qr(a,"fetch similar examples"),(await a.json()).examples}async createExample(t,r,{datasetId:n,datasetName:o,createdAt:i,exampleId:a,metadata:s,split:u,sourceRunId:l}){let c=n;if(c===void 0&&o===void 0)throw new Error("Must provide either datasetName or datasetId");if(c!==void 0&&o!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");c===void 0&&(c=(await this.readDataset({datasetName:o})).id);let f={dataset_id:c,inputs:t,outputs:r,created_at:(i||new Date)?.toISOString(),id:a,metadata:s,split:u,source_run_id:l},p=await this.caller.call(wt(),`${this.apiUrl}/examples`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(f),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(p,"create example"),await p.json()}async createExamples(t){let{inputs:r,outputs:n,metadata:o,sourceRunIds:i,exampleIds:a,datasetId:s,datasetName:u}=t,l=s;if(l===void 0&&u===void 0)throw new Error("Must provide either datasetName or datasetId");if(l!==void 0&&u!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");l===void 0&&(l=(await this.readDataset({datasetName:u})).id);let c=r.map((p,h)=>({dataset_id:l,inputs:p,outputs:n?n[h]:void 0,metadata:o?o[h]:void 0,split:t.splits?t.splits[h]:void 0,id:a?a[h]:void 0,source_run_id:i?i[h]:void 0})),d=await this.caller.call(wt(),`${this.apiUrl}/examples/bulk`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(c),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(d,"create examples"),await d.json()}async createLLMExample(t,r,n){return this.createExample({input:t},{output:r},n)}async createChatExample(t,r,n){let
https://smith.langchain.com/prompts`);let[o,i,a]=gS(t);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(wt(),`${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 qr(u,"create prompt");let{repo:l}=await u.json();return l}async createCommit(t,r,n){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");let[o,i,a]=gS(t),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(wt(),`${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 qr(l,"create commit");let c=await l.json();return this._getPromptUrl(`${o}/${i}${c.commit_hash?`:${c.commit_hash}`:""}`)}async updateExamplesMultipart(t,r=[]){if(!await this._getMultiPartSupport())throw new Error("Your LangSmith version does not allow using the multipart examples endpoint, please update to the latest version.");let n=new FormData;for(let a of r){let s=a.id,u={...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split}},l=ef(u),c=new Blob([l],{type:"application/json"});if(n.append(s,c),a.inputs){let d=ef(a.inputs),f=new Blob([d],{type:"application/json"});n.append(`${s}.inputs`,f)}if(a.outputs){let d=ef(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,h;Array.isArray(f)?[p,h]=f:(p=f.mimeType,h=f.data);let m=new Blob([h],{type:`${p}; length=${h.byteLength}`});n.append(`${s}.attachment.${d}`,m)}if(a.attachments_operations){let d=ef(a.attachments_operations),f=new Blob([d],{type:"application/json"});n.append(`${s}.attachments_operations`,f)}}return await(await this.caller.call(wt(),`${this.apiUrl}/v1/platform/datasets/${t}/examples`,{method:"PATCH",headers:this.headers,body:n})).json()}async uploadExamplesMultipart(t,r=[]){if(!await this._getMultiPartSupport())throw new Error("Your LangSmith version does not allow using the multipart examples endpoint, please update to the latest version.");let n=new FormData;for(let a of r){let s=(a.id??dO()).toString(),u={created_at:a.created_at,...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split}},l=ef(u),c=new Blob([l],{type:"application/json"});n.append(s,c);let d=ef(a.inputs),f=new Blob([d],{type:"application/json"});if(n.append(`${s}.inputs`,f),a.outputs){let p=ef(a.outputs),h=new Blob([p],{type:"application/json"});n.append(`${s}.outputs`,h)}if(a.attachments)for(let[p,h]of Object.entries(a.attachments)){let m,_;Array.isArray(h)?[m,_]=h:(m=h.mimeType,_=h.data);let g=new Blob([_],{type:`${m}; length=${_.byteLength}`});n.append(`${s}.attachment.${p}`,g)}}return await(await this.caller.call(wt(),`${this.apiUrl}/v1/platform/datasets/${t}/examples`,{method:"POST",headers:this.headers,body:n})).json()}async updatePrompt(t,r){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");let[n,o]=gS(t);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);let i={};if(r?.description!==void 0&&(i.description=r.description),r?.readme!==void 0&&(i.readme=r.readme),r?.tags!==void 0&&(i.tags=r.tags),r?.isPublic!==void 0&&(i.is_public=r.isPublic),r?.isArchived!==void 0&&(i.is_archived=r.isArchived),Object.keys(i).length===0)throw new Error("No valid update options provided");let a=await this.caller.call(wt(),`${this.apiUrl}/repos/${n}/${o}`,{method:"PATCH",body:JSON.stringify(i),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.t
`)}var c9t,DM,L$=C(()=>{c9t=Object.prototype.hasOwnProperty;DM=class extends Error{constructor(t,r,n,o,i){super(BNe(t,{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=BNe(t,{name:r,index:n,operation:o,tree:i})}}});var mse={};Kd(mse,{JsonPatchError:()=>Pa,_areEquals:()=>F$,applyOperation:()=>jM,applyPatch:()=>fO,applyReducer:()=>p9t,deepClone:()=>d9t,getValueByPointer:()=>uV,validate:()=>$Ne,validator:()=>lV});function uV(e,t){if(t=="")return e;var r={op:"_get",path:t};return jM(e,r),r.value}function jM(e,t,r=!1,n=!0,o=!0,i=0){if(r&&(typeof r=="function"?r(t,0,e,t.path):lV(t,0)),t.path===""){let a={newDocument:e};if(t.op==="add")return a.newDocument=t.value,a;if(t.op==="replace")return a.newDocument=t.value,a.removed=e,a;if(t.op==="move"||t.op==="copy")return a.newDocument=uV(e,t.from),t.op==="move"&&(a.removed=e),a;if(t.op==="test"){if(a.test=F$(e,t.value),a.test===!1)throw new Pa("Test operation failed","TEST_OPERATION_FAILED",i,t,e);return a.newDocument=e,a}else{if(t.op==="remove")return a.removed=e,a.newDocument=null,a;if(t.op==="_get")return t.value=e,a;if(r)throw new Pa("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,t,e);return a}}else{n||(e=Dc(e));let s=(t.path||"").split("/"),u=e,l=1,c=s.length,d,f,p;for(typeof r=="function"?p=r:p=lV;;){if(f=s[l],f&&f.indexOf("~")!=-1&&(f=N$(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=t.path),d!==void 0&&p(t,0,e,d)),l++,Array.isArray(u)){if(f==="-")f=u.length;else{if(r&&!sV(f))throw new Pa("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,t,e);sV(f)&&(f=~~f)}if(l>=c){if(r&&t.op==="add"&&f>u.length)throw new Pa("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,t,e);let h=f9t[t.op].call(t,u,f,e);if(h.test===!1)throw new Pa("Test operation failed","TEST_OPERATION_FAILED",i,t,e);return h}}else if(l>=c){let h=TD[t.op].call(t,u,f,e);if(h.test===!1)throw new Pa("Test operation failed","TEST_OPERATION_FAILED",i,t,e);return h}if(u=u[f],r&&l<c&&(!u||typeof u!="object"))throw new Pa("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,t,e)}}}function fO(e,t,r,n=!0,o=!0){if(r&&!Array.isArray(t))throw new Pa("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(e=Dc(e));let i=new Array(t.length);for(let a=0,s=t.length;a<s;a++)i[a]=jM(e,t[a],r,!0,o,a),e=i[a].newDocument;return i.newDocument=e,i}function p9t(e,t,r){let n=jM(e,t);if(n.test===!1)throw new Pa("Test operation failed","TEST_OPERATION_FAILED",r,t,e);return n.newDocument}function lV(e,t,r,n){if(typeof e!="object"||e===null||Array.isArray(e))throw new Pa("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,r);if(TD[e.op]){if(typeof e.path!="string")throw new Pa("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,r);if(e.path.indexOf("/")!==0&&e.path.length>0)throw new Pa('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,r);if((e.op==="move"||e.op==="copy")&&typeof e.from!="string")throw new Pa("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,r);if((e.op==="add"||e.op==="replace"||e.op==="test")&&e.value===void 0)t
${t.stack}`:""):typeof t=="string"?t:`${t}`}_addChildRun(t,r){t.child_runs.push(r)}_addRunToRunMap(t){let r=T9t(t.start_time,t.id,t.execution_order),n={...t};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(t){let r=t.parent_run_id!==void 0&&this.runMap.get(t.parent_run_id);r?r.child_execution_order=Math.max(r.child_execution_order,t.child_execution_order):await this.persistRun(t),this.runMap.delete(t.id),await this.onRunUpdate?.(t)}_getExecutionOrder(t){let r=t!==void 0&&this.runMap.get(t);return r?r.child_execution_order+1:1}_createRunForLLMStart(t,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??t.id[t.id.length-1],parent_run_id:o,start_time:c,serialized:t,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(t,r,n,o,i,a,s,u){let l=this.runMap.get(n)??this._createRunForLLMStart(t,r,n,o,i,a,s,u);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}_createRunForChatModelStart(t,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??t.id[t.id.length-1],parent_run_id:o,start_time:c,serialized:t,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(t,r,n,o,i,a,s,u){let l=this.runMap.get(n)??this._createRunForChatModelStart(t,r,n,o,i,a,s,u);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}async handleLLMEnd(t,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=t,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(t,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(t),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(t,r,n,o,i,a,s,u){let l=this._getExecutionOrder(o),c=Date.now(),d={id:n,name:u??t.id[t.id.length-1],parent_run_id:o,start_time:c,serialized:t,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(t,r,n,o,i,a,s,u){let l=this.runMap.get(n)??this._createRunForChainStart(t,r,n,o,i,a,s,u);return await this.onRunCreate?.(l),await this.onChainStart?.(l),l}async handleChainEnd(t,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=xse(t,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=xse(i.inputs,"input")),await this.onChainEnd?.(a),await this._endTrace(a),a}async handleChainError(t,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(t),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=xse(i.inputs,"input")),await this.onChainError?.(a),await this._endTrace(a),a}_createRunForToolStart(t,r,n,o,i,a,s){let u=this._getExecutionOrder(o),l=Date.now(),c={id:n,name:s??t.id[t.id.length-1],parent_run_id:o,start_time:l,serialized:t,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{input:r},execution_order:u,ch
]`;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(`Couldnotconvertregexpatternat${t.currentPath.join("/")}toaflag-independentform!Fallingbacktotheflag-ignorantsource`),e.source}return o}var nue,Fm,H9t,MV=C(()=>{_O();Fm={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:()=>(nue===void 0&&(nue=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),nue),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-_]*$/};H9t=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function IV(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===re.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:Lt(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:Lt(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??{}};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===re.ZodString&&e.keyType._def.checks?.length){let{type:n,...o}=TV(e.keyType._def,t);return{...r,propertyNames:o}}else{if(e.keyType?._def.typeName===re.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===re.ZodBranded&&e.keyType._def.type._def.typeName===re.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...o}=EV(e.keyType._def,t);return{...r,propertyNames:o}}}return r}var AV=C(()=>{bd();os();MV();PV()});function QLe(e,t){if(t.mapStrategy==="record")return IV(e,t);let r=Lt(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},n=Lt(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var iue=C(()=>{os();AV()});function eFe(e){let t=e.values,n=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[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 aue=C(()=>{});function tFe(){return{not:{}}}var sue
`}}let c={};for(let p of t){let h=p.source.split(":"),m=p.target.split(":"),_=h.filter((g,v)=>g===m[v]).join(":");c[_]||(c[_]=[]),c[_].push(p)}let d=new Set;function f(p,h){let m=p.length===1&&p[0].source===p[0].target;if(h&&!m){let _=h.split(":").pop();if(d.has(_))throw new Error(`Foundduplicatesubgraph'${_}'--thislikelymeansthatyou'rereusingasubgraphnodewiththesamename.Pleaseadjustyourgraphtohavesubgraphnodeswithuniquenames.`);d.add(_),l+=`subgraph${_}
`}for(let _ in c)_.startsWith(`${h}:`)&&_!==h&&f(c[_],_);h&&!m&&(l+=`end
`)}f(c[""]??[],"");for(let p in c)!p.includes(":")&&p!==""&&f(c[p],p);return a&&(l+=X9t(i??{})),l}async function yFe(e,t){let{backgroundColor:r="white"}=t??{},n=btoa(e);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 Z9t,bFe=C(()=>{Z9t=["*","_","`"]});function Q9t(e,t){if(e!==void 0&&!CD(e))return e;if(Y$(t))try{let r=t.getName();return r=r.startsWith("Runnable")?r.slice(8):r,r}catch{return t.getName()}else return t.name??"UnknownSchema"}function eWt(e){return Y$(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...Li(e.data.schema),title:e.data.name}}}function _Fe(e,t=[]){let r=new Set(e.edges.filter(o=>!t.includes(o.source)).map(o=>o.target)),n=[];for(let o of Object.values(e.nodes))!t.includes(o.id)&&!r.has(o.id)&&n.push(o);return n.length===1?n[0]:void 0}function vFe(e,t=[]){let r=new Set(e.edges.filter(o=>!t.includes(o.target)).map(o=>o.source)),n=[];for(let o of Object.values(e.nodes))!t.includes(o.id)&&!r.has(o.id)&&n.push(o);return n.length===1?n[0]:void 0}var X$,wFe=C(()=>{oh();O$();Use();bFe();X$=class e{constructor(t){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.nodes=t?.nodes??this.nodes,this.edges=t?.edges??this.edges}toJSON(){let t={};return Object.values(this.nodes).forEach((r,n)=>{t[r.id]=CD(r.id)?n:r.id}),{nodes:Object.values(this.nodes).map(r=>({id:t[r.id],...eWt(r)})),edges:this.edges.map(r=>{let n={source:t[r.source],target:t[r.target]};return typeof r.data<"u"&&(n.data=r.data),typeof r.conditional<"u"&&(n.conditional=r.conditional),n})}}addNode(t,r,n){if(r!==void 0&&this.nodes[r]!==void 0)throw new Error(`Node with id ${r} already exists`);let o=r??Xd(),i={id:o,data:t,name:Q9t(r,t),metadata:n};return this.nodes[o]=i,i}removeNode(t){delete this.nodes[t.id],this.edges=this.edges.filter(r=>r.source!==t.id&&r.target!==t.id)}addEdge(t,r,n,o){if(this.nodes[t.id]===void 0)throw new Error(`Source node ${t.id} not in graph`);if(this.nodes[r.id]===void 0)throw new Error(`Target node ${r.id} not in graph`);let i={source:t.id,target:r.id,data:n,conditional:o};return this.edges.push(i),i}firstNode(){return _Fe(this)}lastNode(){return vFe(this)}extend(t,r=""){let n=r;Object.values(t.nodes).map(l=>l.id).every(CD)&&(n="");let i=l=>n?`${n}:${l}`:l;Object.entries(t.nodes).forEach(([l,c])=>{this.nodes[i(l)]={...c,id:i(l)}});let a=t.edges.map(l=>({...l,source:i(l.source),target:i(l.target)}));this.edges=[...this.edges,...a];let s=t.firstNode(),u=t.lastNode();return[s?{id:i(s.id),data:s.data}:void 0,u?{id:i(u.id),data:u.data}:void 0]}trimFirstNode(){let t=this.firstNode();t&&_Fe(this,[t.id])&&this.removeNode(t)}trimLastNode(){let t=this.lastNode();t&&vFe(this,[t.id])&&this.removeNode(t)}reid(){let t=Object.fromEntries(Object.values(this.nodes).map(o=>[o.id,o.name])),r=new Map;Object.values(t).forEach(o=>{r.set(o,(r.get(o)||0)+1)});let n=o=>{let i=t[o];return CD(o)&&r.get(i)===1?i:o};return new e({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(t){let{withStyles:r,curveStyle:n,nodeColors:o={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:i}=t??{},a=this.reid(),s=a.firstNode(),u=a.lastNode();returngFe(a.nodes,a.edges,{firstNode:s?.id,lastNode:u?.id,withStyles:r,curveStyle:n,nodeColors:o,wrapLabelNWords:i})}asyncdrawMermaidPng(t){letr=this.drawMermaid(t);returnyFe(r,{backgroundColor:t?.backgroundColor})}}});functionSFe(e){lett=newTextEncoder,r=newReadableStream({asyncstart(n){forawait(letoofe)n.enqueue(t.encode(`event: data
Forexample,theexample"JSON Schema"instance{{"properties":{{"foo":{{"description":"a list of test words","type":"array","items":{{"type":"string"}}}}}},"required":["foo"]}}}}
wouldmatchanobjectwithonerequiredproperty,"foo".The"type"propertyspecifies"foo"mustbean"array",andthe"description"propertysemanticallydescribesitas"a list of test words".Theitemswithin"foo"mustbestrings.
`)};Od.prototype.renderPartial=function(t,r,n,o){if(n){var i=this.getConfigTags(o),a=Nue(n)?n(t[1]):n[t[1]];if(a!=null){var s=t[6],u=t[5],l=t[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)}}};Od.prototype.unescapedValue=function(t,r){var n=r.lookup(t[1]);if(n!=null)return n};Od.prototype.escapedValue=function(t,r,n){var o=this.getConfigEscape(n)||ih.escape,i=r.lookup(t[1]);if(i!=null)return typeof i=="number"&&o===ih.escape?String(i):o(i)};Od.prototype.rawValue=function(t){return t[1]};Od.prototype.getConfigTags=function(t){return VD(t)?t:t&&typeof t=="object"?t.tags:void 0};Od.prototype.getConfigEscape=function(t){if(t&&typeof t=="object"&&!VD(t))return t.escape};ih={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(e){oq.templateCache=e},get templateCache(){return oq.templateCache}},oq=new Od;ih.clearCache=function(){return oq.clearCache()};ih.parse=function(t,r){return oq.parse(t,r)};ih.render=function(t,r,n,o){if(typeof t!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+NWt(t)+'" was given as the first argument for mustache#render(template, view, partials)');return oq.render(t,r,n,o)};ih.escape=UWt;ih.Scanner=iq;ih.Context=HD;ih.Writer=Od;HV=ih});function WFe(){HV.escape=e=>e}var aq,YWt,VV,ZWt,XWt,Lue,QWt,Bm,JFe,JM,WD=C(()=>{VFe();$$();aq=e=>{let t=e.split(""),r=[],n=(i,a)=>{for(let s=a;s<t.length;s+=1)if(i.includes(t[s]))return s;return-1},o=0;for(;o<t.length;)if(t[o]==="{"&&o+1<t.length&&t[o+1]==="{")r.push({type:"literal",text:"{"}),o+=2;else if(t[o]==="}"&&o+1<t.length&&t[o+1]==="}")r.push({type:"literal",text:"}"}),o+=2;else if(t[o]==="{"){let i=n("}",o);if(i<0)throw new Error("Unclosed '{' in template.");r.push({type:"variable",name:t.slice(o+1,i).join("")}),o=i+1}else{if(t[o]==="}")throw new Error("Single '}' in template.");{let i=n("{}",o),a=(i<0?t.slice(o):t.slice(o,i)).join("");r.push({type:"literal",text:a}),o=i<0?t.length:i}}return r},YWt=e=>e.map(t=>t[0]==="name"?{type:"variable",name:t[1].includes(".")?t[1].split(".")[0]:t[1]}:["#","&","^",">"].includes(t[0])?{type:"variable",name:t[1]}:{type:"literal",text:t[1]}),VV=e=>{WFe();let t=HV.parse(e);return YWt(t)},ZWt=(e,t)=>aq(e).reduce((r,n)=>{if(n.type==="variable"){if(n.name in t){let o=typeof t[n.name]=="string"?t[n.name]:JSON.stringify(t[n.name]);return r+o}throw new Error(`(f-string)Missingvalueforinput${n.name}`)}return r+n.text},""),XWt=(e,t)=>(WFe(),HV.render(e,t)),Lue={"f-string":ZWt,mustache:XWt},QWt={"f-string":aq,mustache:VV},Bm=(e,t,r)=>{try{return Lue[t](e,r)}catch(n){throw hO(n,"INVALID_PROMPT_INPUT")}},JFe=(e,t)=>QWt[t](e),JM=(e,t,r)=>{if(!(t in Lue)){let n=Object.keys(Lue);throw new Error(`Invalidtemplateformat.Got\`${t}\`;
shouldbeoneof${n}`)}try{let n=r.reduce((o,i)=>(o[i]="foo",o),{});Array.isArray(e)?e.forEach(o=>{if(o.type==="text")Bm(o.text,t,n);else if(o.type==="image_url")if(typeof o.image_url=="string")Bm(o.image_url,t,n);else{let i=o.image_url.url;Bm(i,t,n)}else throw new Error(`Invalidmessagetemplatereceived.${JSON.stringify(o,null,2)}`)}):Bm(e,t,n)}catch(n){throw new Error(`Invalidpromptschema:${n.message}`)}}});var Fue={};Kd(Fue,{PromptTemplate:()=>Ed});var Ed,JD=C(()=>{nq();WD();Ed=class e extends MS{static lc_name(){return"PromptTemplate"}constructor(t){if(super(t),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}),t.templateFormat==="mustache"&&t.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,t),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))),JM(this.template,this.templateFormat,r)}}_getPromptType(){return"prompt"}async format(t){let r=await this.mergePartialAndUserVariables(t);return Bm(this.template,this.templateFormat,r)}static fromExamples(t,r,n,o=`
`,i=""){let a=[i,...t,r].join(o);return new e({inputVariables:n,template:a})}static fromTemplate(t,r){let{templateFormat:n="f-string",...o}=r??{},i=new Set;return JFe(t,n).forEach(a=>{a.type==="variable"&&i.add(a.name)}),new e({inputVariables:[...i],templateFormat:n,template:t,...o})}async partial(t){let r=this.inputVariables.filter(i=>!(i in t)),n={...this.partialVariables??{},...t},o={...this,inputVariables:r,partialVariables:n};return new e(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(t){if(!t.template)throw new Error("Prompt template must have a template");return new e({inputVariables:t.input_variables,template:t.template,templateFormat:t.template_format})}}});var GD,kue=C(()=>{rq();zD();WD();GD=class e extends ay{static lc_name(){return"ImagePromptTemplate"}constructor(t){if(super(t),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=t.template,this.templateFormat=t.templateFormat??this.templateFormat,this.validateTemplate=t.validateTemplate??this.validateTemplate,this.additionalContentFields=t.additionalContentFields,this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),JM([{type:"image_url",image_url:this.template}],this.templateFormat,r)}}_getPromptType(){return"prompt"}async partial(t){let r=this.inputVariables.filter(i=>!(i in t)),n={...this.partialVariables??{},...t},o={...this,inputVariables:r,partialVariables:n};return new e(o)}async format(t){let r={};for(let[a,s]of Object.entries(this.template))typeof s=="string"?r[a]=Bm(s,this.templateFormat,t):r[a]=s;let n=t.url||r.url,o=t.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(t){let r=await this.format(t);return new zV(r)}}});function eJt(e){return typeof e.formatMessages=="function"}function tJt(e,t){if(eJt(e)||th(e))return e;if(Array.isArray(e)&&e[0]==="placeholder"){let o=e[1];if(t?.templateFormat==="mustache"&&typeof o=="string"&&o.slice(0,2)==="{{"&&o.slice(-2)==="}}"){let i=o.slice(2,-2);return new xO({variableName:i,optional:!0})}else if(typeof o=="string"&&o[0]==="{"&&o[o.length-1]==="}"){let i=o.slice(1,-1);return new xO({variableName:i,optional:!0})}throw new Error(`Invalidplaceholdertemplateforformat${t?.templateFormat??'"f-string"'}:"${e[1]}".Expectedavariablenamesurroundedby${t?.templateFormat==="mustache"?"double":"single"}curlybraces.`)}let r=Nm(e),n;if(typeof r.content=="string"?n=r.content:n=r.content.map(o=>"text"in o?{...o,text:o.text}:"image_url"in o?{...o,image_url:o.image_url}:o),r._getType()==="human")return CO.fromTemplate(n,t);if(r._getType()==="ai")return que.fromTemplate(n,t);if(r._getType()==="system")return KD.fromTemplate(n,t);if(xd.isInstance(r))return $ue.fromTemplate(r.content,r.role,t);throw new Error(`Couldnotcoercemessageprompttemplatefrominput.Receivedmessagetype:"${r._getType()}".`)}function rJt(e){return e.constructor.lc_name()==="MessagesPlaceholder"}var sq,xO,Bue,uq,$ue,lq,CO,que,KD,ah,cq=C(()=>{UM();rq();sf();nq();zD();JD();kue();WD();$$();sq=class extends nn{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","chat"]}),Object.defineProperty(this,"lc_se
`));throw a.name="InputFormatError",a.lc_error_code=o.lc_error_code,a}return n}},Bue=class extends sq{constructor(t){"prompt"in t||(t={prompt:t}),super(t),Object.defineProperty(this,"prompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.prompt=t.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(t){return[await this.format(t)]}},uq=class extends ay{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){let r=await this.formatMessages(t);return new UD(r)}},$ue=class extends Bue{static lc_name(){return"ChatMessagePromptTemplate"}constructor(t,r){"prompt"in t||(t={prompt:t,role:r}),super(t),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=t.role}async format(t){return new xd(await this.prompt.format(t),this.role)}static fromTemplate(t,r,n){return new this(Ed.fromTemplate(t,{templateFormat:n?.templateFormat}),r)}},lq=class extends sq{static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}constructor(t,r){if("prompt"in t||(t={prompt:t}),super(t),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=t.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(t){let r=this.constructor;if(r._messageClass()){let n=r._messageClass();return new n({content:t})}else if(r.chatMessageClass){let n=r.chatMessageClass();return new n({content:t,role:this.getRoleFromMessageClass(n.lc_name())})}else throw new Error("No message class defined")}getRoleFromMessageClass(t){switch(t){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(t,r){if(typeof t=="string")return new this(Ed.fromTemplate(t,r));let n=[];for(let o of t)if(typeof o=="string"||typeof o=="object"&&"text"in o){let i="";typeof o=="string"?i=o:typeof o.text=="string"&&(i=o.text??"");let a={...r,...typeof o!="string"?{additionalContentFields:o}:{}};n.push(Ed.fromTemplate(i,a))}else if(typeof o=="object"&&"image_url"in o){let i=o.image_url??"",a,s=[];if(typeof i=="string"){let u;r?.templateFormat==="mustache"?u=VV(i):u=aq(i);let l=u.flatMap(c=>c.type==="variable"?[c.name]:[]);if((l?.length??0)>0){if(l.length>1)throw new Error(`Onlyoneformatvariableallowedperimagetemplate.
Got:${l}
From:${i}`);s=[l[0]]}else s=[];i={url:i},a=new GD({template:i,inputVariables:s,templateFormat:r?.templateFormat,additionalContentFields:o})}else if(typeof i=="object"){if("url"in i){let u;r?.templateFormat==="mustache"?u=VV(i.url):u=aq(i.url),s=u.flatMap(l=>l.type==="variable"?[l.name]:[])}else s=[];a=new GD({template:i,inputVariables:s,templateFormat:r?.templateFormat,additionalContentFields:o})}else throw new Error("Invalid image template");n.push(a)}return new this({prompt:n,additionalOptions:r})}async format(t){if(this.prompt instanceof MS){let r=await this.prompt.format(t);return this.createMessage(r)}else{let r=[];for(let n of this.prompt){let o={};if(!("inputVariables"in n))throw new Error(`Prompt${n}doesnothaveinputVariablesdefined.`);for(let i of n.inputVariables)o||(o={[i]:t[i]}),o={...o,[i]:t[i]};if(n instanceof MS){let i=await n.format(o),a;"additionalContentFields"in n&&(a=n.additionalContentFields),r.push({...a,type:"text",text:i})}else if(n instanceof GD){let i=await n.format(o),a;"additionalContentFields"in n&&(a=n.additionalContentFields),r.push({...a,type:"image_url",image_url:i})}}return this.createMessage(r)}}async formatMessages(t){return[await this.format(t)]}},CO=class extends lq{static _messageClass(){return Ua}static lc_name(){return"HumanMessagePromptTemplate"}},que=class extends lq{static _messageClass(){return Po}static lc_name(){return"AIMessagePromptTemplate"}},KD=class extends lq{static _messageClass(){return SS}static lc_name(){return"SystemMessagePromptTemplate"}};ah=class e extends uq{static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}constructor(t){if(super(t),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"}),t.templateFormat==="mustache"&&t.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,t),this.validateTemplate){let r=new Set;for(let s of this.promptMessages)if(!(s instanceof Lu))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(`Inputvariables\`${[...i]}\` are not used in any of the prompt messages.`);leta=newSet([...r].filter(s=>!o.has(s)));if(a.size>0)thrownewError(`Input variables \`${[...a]}\` are used in prompt messages but not in the prompt template.`)}}_getPromptType(){return"chat"}async_parseImagePrompts(t,r){if(typeoft.content=="string")returnt;letn=awaitPromise.all(t.content.map(asynco=>{if(o.type!=="image_url")returno;leti="";typeofo.image_url=="string"?i=o.image_url:i=o.image_url.url;lets=awaitEd.fromTemplate(i,{templateFormat:this.templateFormat}).format(r);returntypeofo.image_url!="string"&&"url"ino.image_url?o.image_url.url=s:o.image_url=s,o}));returnt.content=n,t}asyncformatMessages(t){letr=awaitthis.mergePartialAndUserVariables(t),n=[];for(letoofthis.promptMessages)if(oinstanceofLu)n.push(awaitthis._parseImagePrompts(o,r));else{leti=o.inputVariables.reduce((s,u)=>{if(!(uinr)&&!(rJt(o)&&o.optional))throwhO(newError(`Missing value for input variable \`${u.toString()}\``),"INVALID_PROMPT_INPUT");returns[u]=r[u],s},{}),a=awaito.formatMessages(i);n=n.concat(a)}returnn}asyncpartial(t){letr=this.inputVariables.filter(i=>!(iint)),n={...this.partialVariables??{},...t},o={...this,inputVariables:r,partialVariables:n};returnnewe(o)}staticfromTemplate(t,r){letn=Ed.fromTemplate(t,r),o=newCO({prompt:n});returnthis.fromMessages([o])}staticfromMessages(t,r){letn=t.reduce((a,s)=>a.concat(sinstanceofe?s.promptMessages:[tJt(s,r)]),[]),o=t.reduce((a,s)=>sinstanceofe?Object.assign(a,s.partialVariables):a,Object.create(null)),i=newSet;for(letaofn)if(!(ainstanceofLu))for(letsofa.inputVariables)sino||i.add(s);returnnewthis({...r,inputVari
`}),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,t),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))),JM(this.prefix+this.suffix,this.templateFormat,r)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(t){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(t);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(t){let r=this.inputVariables.filter(i=>!(i in t)),n={...this.partialVariables??{},...t},o={...this,inputVariables:r,partialVariables:n};return new e(o)}async format(t){let r=await this.mergePartialAndUserVariables(t),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 Bm(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(t){let{example_prompt:r}=t;if(!r)throw new Error("Missing example prompt");let n=await Ed.deserialize(r),o;if(Array.isArray(t.examples))o=t.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new e({inputVariables:t.input_variables,examplePrompt:n,examples:o,exampleSeparator:t.example_separator,prefix:t.prefix,suffix:t.suffix,templateFormat:t.template_format})}},zue=class e extends uq{_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}constructor(t){if(super(t),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:`
`,this.exampleSelector=t.exampleSelector,this.prefix=t.prefix??"",this.suffix=t.suffix??"",this.templateFormat=t.templateFormat??"f-string",this.validateTemplate=t.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))),JM(this.prefix+this.suffix,this.templateFormat,r)}}async getExamples(t){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(t);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(t){let r=await this.mergePartialAndUserVariables(t),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(t){let r=await this.mergePartialAndUserVariables(t),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 Bm(a,this.templateFormat,r)}async partial(t){let r=this.inputVariables.filter(i=>!(i in t)),n={...this.partialVariables??{},...t},o={...this,inputVariables:r,partialVariables:n};return new e(o)}}});var ay,zD=C(()=>{sf();ay=class extends nn{get lc_attributes(){return{partialVariables:void 0}}constructor(t){super(t),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}=t;if(r.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,t)}async mergePartialAndUserVariables(t){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,...t}}async invoke(t,r){let n={...this.metadata,...r?.metadata},o=[...this.tags??[],...r?.tags??[]];return this._callWithConfig(i=>this.formatPromptValue(i),t,{...r,tags:o,metadata:n,runType:"prompt"})}serialize(){throw new Error("Use .toJSON() instead")}static async deserialize(t){switch(t._type){case"prompt":{let{PromptTemplate:r}=await Promise.resolve().then(()=>(JD(),Fue));return r.deserialize(t)}case void 0:{let{PromptTemplate:r}=await Promise.resolve().then(()=>(JD(),Fue));return r.deserialize({...t,_type:"prompt"})}case"few_shot":{let{FewShotPromptTemplate:r}=await Promise.resolve().then(()=>(Hue(),GFe));return r.deserialize(t)}default:throw new Error(`Invalidprompttypeinconfig:${t._type}`)}}}});var KFe=C(()=>{zD();cq()});var YFe=C(()=>{});var ZFe=C(()=>{cq()});var XFe=C(()=>{zD();cq();Hue();KFe();JD();YFe();nq();WD();kue();ZFe()});var GM=C(()=>{XFe()});var IS=C(()=>{Pue()});var gke=b(on=>{"use strict";var fq=Symbol.for("react.element"),cJt=Symbol.for("react.portal"),dJt=Symbol.for("react.fragment"),fJt=Symbol.for("react.strict_mode"),pJt=Symbol.for("react.profiler"),hJt=Symbol.for("react.provider"),mJt=Symbol.for("react.context"),gJt=Symbol.for("react.forward_ref"),yJt=Symbol.for("react.suspense"),bJt=Symbol.for("react.memo"),_Jt=Symbol.for("react.lazy"),ake=Symbol.iterato
[`+H+"] ";for(ae in arguments[0])i(arguments[0],ae)&&(R+=ae+": "+arguments[0][ae]+", ");R=R.slice(0,-2)}else R=arguments[H];I.push(R)}E(y+`
`),O7e={warn:console.warn}});var vQt,wQt,E7e,SQt,P7e,T4n,M4n,I4n,MJ,T7e,A4n,xQt,CQt,OQt,JI,EQt,PQt,Hpe,M7e=C(()=>{zpe();vQt=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wQt=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),E7e=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let t=wQt.exec(e);if(!t)throw new TypeError("Invalid RFC-3339 date-time value");let[r,n,o,i,a,s,u,l]=t,c=Upe(Hpe(n)),d=JI(o,"month",1,12),f=JI(i,"day",1,31);return T7e(c,d,f,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l})},SQt=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),P7e=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let t=SQt.exec(e);if(!t)throw new TypeError("Invalid RFC-3339 date-time value");let[r,n,o,i,a,s,u,l,c]=t,d=Upe(Hpe(n)),f=JI(o,"month",1,12),p=JI(i,"day",1,31),h=T7e(d,f,p,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l});return c.toUpperCase()!="Z"&&h.setTime(h.getTime()-PQt(c)),h},T4n=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$/),M4n=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$/),I4n=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})$/),MJ=e=>{if(e==null)return;let t;if(typeof e=="number")t=e;else if(typeof e=="string")t=w7e(e);else if(typeof e=="object"&&e.tag===1)t=e.value;else throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(t)||t===1/0||t===-1/0)throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(t*1e3))},T7e=(e,t,r,n)=>{let o=t-1;return CQt(e,o,r),new Date(Date.UTC(e,o,r,JI(n.hours,"hour",0,23),JI(n.minutes,"minute",0,59),JI(n.seconds,"seconds",0,60),EQt(n.fractionalMilliseconds)))},A4n=50*365*24*60*60*1e3,xQt=[31,28,31,30,31,30,31,31,30,31,30,31],CQt=(e,t,r)=>{let n=xQt[t];if(t===1&&OQt(e)&&(n=29),r>n)throw new TypeError(`Invaliddayfor${vQt[t]}in${e}:${r}`)},OQt=e=>e%4===0&&(e%100!==0||e%400===0),JI=(e,t,r,n)=>{let o=x7e(Hpe(e));if(o<r||o>n)throw new TypeError(`${t}mustbebetween${r}and${n},inclusive`);return o},EQt=e=>e==null?0:S7e("0."+e)*1e3,PQt=e=>{let t=e[0],r=1;if(t=="+")r=1;else if(t=="-")r=-1;else throw new TypeError(`Offsetdirection,${t},mustbe"+"or"-"`);let n=Number(e.substring(1,3)),o=Number(e.substring(4,6));return r*(n*60+o)*60*1e3},Hpe=e=>{let t=0;for(;t<e.length-1&&e.charAt(t)==="0";)t++;return t===0?e:e.slice(t)}});var lN,ia,Vpe=C(()=>{lN=class e extends Error{constructor(t){super(t.message),Object.setPrototypeOf(this,e.prototype),this.name=t.name,this.$fault=t.$fault,this.$metadata=t.$metadata}},ia=(e,t={})=>{Object.entries(t).filter(([,n])=>n!==void 0).forEach(([n,o])=>{(e[n]==null||e[n]==="")&&(e[n]=o)});let r=e.message||e.Message||"UnknownError";return e.message=r,delete e.Message,e}});var TQt,IJ,MQt,I7e=C(()=>{Vpe();TQt=({output:e,parsedBody:t,exceptionCtor:r,errorCode:n})=>{let o=MQt(e),i=o.httpStatusCode?o.httpStatusCode+"":void 0,a=new r({name:t?.code||t?.Code||n||i||"UnknownError",$fault:"client",$metadata:o});throw ia(a,t)},IJ=e=>({output:t,parsedBody:r,errorCode:n})=>{TQt({output:t,parsedBody:r,exceptionCtor:e,errorCode:n})},MQt=e=>({httpStatusCode:e.statusCode,requestId:e.headers["x-amzn-requestid"]??e.headers["x-amzn-request-id"]??e.headers["x-amz-request-id"],extendedRequestId:e.headers["x-amz-id-2"],cfId:e.headers["x-amz-cf-id"]})});var AJ,A7e=C(()=>{AJ=e=>{switch(e){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":retu
${rg(i)}`}getCanonicalPath({path:t}){if(this.uriEscapePath){let r=[];for(let i of t.split("/"))i?.length!==0&&i!=="."&&(i===".."?r.pop():r.push(i));let n=`${t?.startsWith("/")?"/":""}${r.join("/")}${r.length>0&&t?.endsWith("/")?"/":""}`;return xh(n).replace(/%2F/g,"/")}return t}async getSignature(t,r,n,o){let i=await this.createStringToSign(t,r,o),a=new this.sha256(await n);return a.update(SE(i)),rg(await a.digest())}getSigningKey(t,r,n,o){return uZe(this.sha256,t,n,r,o||this.service)}validateResolvedCredentials(t){if(typeof t!="object"||typeof t.accessKeyId!="string"||typeof t.secretAccessKey!="string")throw new Error("Resolved credential object is not valid")}},GJ=e=>{let t=gZe(e).replace(/[\-:]/g,"");return{longDate:t,shortDate:t.slice(0,8)}},bZe=e=>Object.keys(e).sort().join(";")});var vZe=C(()=>{_Ze();fhe();hhe();mhe();bhe();_he();dhe()});var KJ,wZe=C(()=>{vE();vZe();KJ=e=>{let t;e.credentials&&(t=aYe(e.credentials,iYe,Ype)),t||(e.credentialDefaultProvider?t=fN(e.credentialDefaultProvider(Object.assign({},e,{parentClientConfig:e}))):t=async()=>{throw new Error("`credentials` is missing")});let{signingEscapePath:r=!0,systemClockOffset:n=e.systemClockOffset||0,sha256:o}=e,i;return e.signer?i=fN(e.signer):e.regionInfoProvider?i=()=>fN(e.region)().then(async a=>[await e.regionInfoProvider(a,{useFipsEndpoint:await e.useFipsEndpoint(),useDualstackEndpoint:await e.useDualstackEndpoint()})||{},a]).then(([a,s])=>{let{signingRegion:u,signingService:l}=a;e.signingRegion=e.signingRegion||u||s,e.signingName=e.signingName||l||e.serviceId;let c={...e,credentials:t,region:e.signingRegion,service:e.signingName,sha256:o,uriEscapePath:r},d=e.signerConstructor||cz;return new d(c)}):i=async a=>{a=Object.assign({},{name:"sigv4",signingName:e.signingName||e.defaultSigningName,signingRegion:await fN(e.region)(),properties:{}},a);let s=a.signingRegion,u=a.signingName;e.signingRegion=e.signingRegion||s,e.signingName=e.signingName||u||e.serviceId;let l={...e,credentials:t,region:e.signingRegion,service:e.signingName,sha256:o,uriEscapePath:r},c=e.signerConstructor||cz;return new c(l)},{...e,systemClockOffset:n,signingEscapePath:r,credentials:t,signer:i}}});var SZe=C(()=>{qYe();UYe();wZe()});var xZe=C(()=>{SZe()});var CZe=C(()=>{});var OZe=C(()=>{Rt()});var YJ,vhe=C(()=>{Rt();YJ=(e,t)=>_E(e,t).then(r=>t.utf8Encoder(r))});var Ja,EZe,PZe,TZe=C(()=>{vhe();Ja=(e,t)=>YJ(e,t).then(r=>{if(r.length)try{return JSON.parse(r)}catch(n){throw n?.name==="SyntaxError"&&Object.defineProperty(n,"$responseBodyText",{value:r}),n}return{}}),EZe=async(e,t)=>{let r=await Ja(e,t);return r.message=r.message??r.Message,r},PZe=(e,t)=>{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(e.headers,"x-amzn-errortype");if(o!==void 0)return n(e.headers[o]);if(t.code!==void 0)return n(t.code);if(t.__type!==void 0)return n(t.__type)}});var ZJ=b(ix=>{"use strict";var MZe=":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",KQt=MZe+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",IZe="["+MZe+"]["+KQt+"]*",YQt=new RegExp("^"+IZe+"$"),ZQt=function(e,t){let r=[],n=t.exec(e);for(;n;){let o=[];o.startIndex=t.lastIndex-n[0].length;let i=n.length;for(let a=0;a<i;a++)o.push(n[a]);r.push(o),n=t.exec(e)}return r},XQt=function(e){let t=YQt.exec(e);return!(t===null||typeof t>"u")};ix.isExist=function(e){return typeof e<"u"};ix.isEmptyObject=function(e){return Object.keys(e).length===0};ix.merge=function(e,t,r){if(t){let n=Object.keys(t),o=n.length;for(let i=0;i<o;i++)r==="strict"?e[n[i]]=[t[n[i]]]:e[n[i]]=t[n[i]]}};ix.getValue=function(e){return ix.isExist(e)?e:""};ix.isName=XQt;ix.getAllMatches=ZQt;ix.nameRegexp=IZe});var She=b(NZe=>{"use strict";var whe=ZJ(),QQt={allowBooleanAttributes:!1,unpairedTags:[]};NZe.validate=function(e,t){t=Object.assign({},QQt,t);let r=[],n=!1,
`&&e[i]!=="\r";i++)u+=e[i];if(u=u.trim(),u[u.length-1]==="/"&&(u=u.substring(0,u.length-1),i--),!ser(u)){let d;return u.trim().length===0?d="Invalid space after '<'.":d="Tag '"+u+"' is an invalid name.",Ga("InvalidTag",d,Rd(e,i))}let l=rer(e,i);if(l===!1)return Ga("InvalidAttr","Attributes for '"+u+"' have open quote.",Rd(e,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=jZe(c,t);if(f===!0)n=!0;else return Ga(f.err.code,f.err.msg,Rd(e,d+f.err.line))}else if(s)if(l.tagClosed){if(c.trim().length>0)return Ga("InvalidTag","Closing tag '"+u+"' can't have attributes or invalid starting.",Rd(e,a));if(r.length===0)return Ga("InvalidTag","Closing tag '"+u+"' has not been opened.",Rd(e,a));{let d=r.pop();if(u!==d.tagName){let f=Rd(e,d.tagStartPos);return Ga("InvalidTag","Expected closing tag '"+d.tagName+"' (opened in line "+f.line+", col "+f.col+") instead of closing tag '"+u+"'.",Rd(e,a))}r.length==0&&(o=!0)}}else return Ga("InvalidTag","Closing tag '"+u+"' doesn't have proper closing.",Rd(e,i));else{let d=jZe(c,t);if(d!==!0)return Ga(d.err.code,d.err.msg,Rd(e,i-c.length+d.err.line));if(o===!0)return Ga("InvalidXml","Multiple possible root nodes found.",Rd(e,i));t.unpairedTags.indexOf(u)!==-1||r.push({tagName:u,tagStartPos:a}),n=!0}for(i++;i<e.length;i++)if(e[i]==="<")if(e[i+1]==="!"){i++,i=DZe(e,i);continue}else if(e[i+1]==="?"){if(i=RZe(e,++i),i.err)return i}else break;else if(e[i]==="&"){let d=ier(e,i);if(d==-1)return Ga("InvalidChar","char '&' is not expected.",Rd(e,i));i=d}else if(o===!0&&!AZe(e[i]))return Ga("InvalidXml","Extra text at the end",Rd(e,i));e[i]==="<"&&i--}}else{if(AZe(e[i]))continue;return Ga("InvalidChar","char '"+e[i]+"' is not expected.",Rd(e,i))}if(n){if(r.length==1)return Ga("InvalidTag","Unclosed tag '"+r[0].tagName+"'.",Rd(e,r[0].tagStartPos));if(r.length>0)return Ga("InvalidXml","Invalid '"+JSON.stringify(r.map(i=>i.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return Ga("InvalidXml","Start tag expected.",1);return!0};function AZe(e){return e===" "||e===" "||e===`
`||e==="\r"}function RZe(e,t){let r=t;for(;t<e.length;t++)if(e[t]=="?"||e[t]==" "){let n=e.substr(r,t-r);if(t>5&&n==="xml")return Ga("InvalidXml","XML declaration allowed only at the start of the document.",Rd(e,t));if(e[t]=="?"&&e[t+1]==">"){t++;break}else continue}return t}function DZe(e,t){if(e.length>t+5&&e[t+1]==="-"&&e[t+2]==="-"){for(t+=3;t<e.length;t++)if(e[t]==="-"&&e[t+1]==="-"&&e[t+2]===">"){t+=2;break}}else if(e.length>t+8&&e[t+1]==="D"&&e[t+2]==="O"&&e[t+3]==="C"&&e[t+4]==="T"&&e[t+5]==="Y"&&e[t+6]==="P"&&e[t+7]==="E"){let r=1;for(t+=8;t<e.length;t++)if(e[t]==="<")r++;else if(e[t]===">"&&(r--,r===0))break}else if(e.length>t+9&&e[t+1]==="["&&e[t+2]==="C"&&e[t+3]==="D"&&e[t+4]==="A"&&e[t+5]==="T"&&e[t+6]==="A"&&e[t+7]==="["){for(t+=8;t<e.length;t++)if(e[t]==="]"&&e[t+1]==="]"&&e[t+2]===">"){t+=2;break}}return t}var eer='"',ter="'";function rer(e,t){let r="",n="",o=!1;for(;t<e.length;t++){if(e[t]===eer||e[t]===ter)n===""?n=e[t]:n!==e[t]||(n="");else if(e[t]===">"&&n===""){o=!0;break}r+=e[t]}return n!==""?!1:{value:r,index:t,tagClosed:o}}var ner=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function jZe(e,t){let r=whe.getAllMatches(e,ner),n={};for(let o=0;o<r.length;o++){if(r[o][1].length===0)return Ga("InvalidAttr","Attribute '"+r[o][2]+"' has no space in starting.",dz(r[o]));if(r[o][3]!==void 0&&r[o][4]===void 0)return Ga("InvalidAttr","Attribute '"+r[o][2]+"' is without value.",dz(r[o]));if(r[o][3]===void 0&&!t.allowBooleanAttributes)return Ga("InvalidAttr","boolean attribute '"+r[o][2]+"' is not allowed.",dz(r[o]));let i=r[o][2];if(!aer(i))return Ga("InvalidAttr","Attribute '"+i+"' is an invalid name.",dz(r[o]));if(!n.hasOwnProperty(i))n[i]=1;else return Ga("InvalidAttr","Attribute '"+i+"'isrepeated.",dz(r[o]))}return!0}function oer(e,t){let r=/\d/;for(e[t]==="x"&&(t++,r=/[\da-fA-F]/);t<e.length;t++){if(e[t]===";")return t;if(!e[t].match(r))break}return-1}function ier(e,t){if(t++,e[t]===";")return-1;if(e[t]==="#")return t++,oer(e,t);let r=0;for(;t<e.length;t++,r++)if(!(e[t].match(/\w/)&&r<20)){if(e[t]===";")break;return-1}return t}function Ga(e,t,r){return{err:{code:e,msg:t,line:r.line||r,col:r.col}}}function aer(e){return whe.isName(e)}function ser(e){return whe.isName(e)}function Rd(e,t){let r=e.substring(0,t).split(/\r?\n/);return{line:r.length,col:r[r.length-1].length+1}}function dz(e){return e.startIndex+e[1].length}});var FZe=b(xhe=>{var LZe={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(e,t){return t},attributeValueProcessor:function(e,t){return t},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(e,t,r){return e}},uer=function(e){return Object.assign({},LZe,e)};xhe.buildOptions=uer;xhe.defaultOptions=LZe});var BZe=b((tVn,kZe)=>{"usestrict";var Che=class{constructor(t){this.tagname=t,this.child=[],this[":@"]={}}add(t,r){t==="__proto__"&&(t="#__proto__"),this.child.push({[t]:r})}addChild(t){t.tagname==="__proto__"&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child})}};kZe.exports=Che});var qZe=b((rVn,$Ze)=>{var ler=ZJ();function cer(e,t){let r={};if(e[t+3]==="O"&&e[t+4]==="C"&&e[t+5]==="T"&&e[t+6]==="Y"&&e[t+7]==="P"&&e[t+8]==="E"){t=t+9;let n=1,o=!1,i=!1,a="";for(;t<e.length;t++)if(e[t]==="<"&&!i){if(o&&per(e,t))t+=7,[entityName,val,t]=der(e,t+1),val.indexOf("&")===-1&&(r[yer(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(o&&her(e,t))t+=8;else if(o&&mer(e,t))t+=8;else if(o&&ger(e,t))t+=9;else if(fer)i=!0;else throw new Error("InvalidDOCTYPE");n++,a=""}else if(e[t]===">"){if(i?e[t-1]==="-"&&e[t-2]==="-"&&(i=!1,n--):n--,n===0)brea
`);let t=new fz("!xml"),r=t,n="",o="";for(let i=0;i<e.length;i++)if(e[i]==="<")if(e[i+1]==="/"){let s=YI(e,">",i,"Closing Tag is not closed."),u=e.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(`Unpairedtagcannotbeusedasclosingtag:</${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(e[i+1]==="?"){let s=Ehe(e,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 fz(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(e.substr(i+1,3)==="!--"){let s=YI(e,"-->",i+4,"Comment is not closed.");if(this.options.commentPropName){let u=e.substring(i+4,s-2);n=this.saveTextToParentTag(n,r,o),r.add(this.options.commentPropName,[{[this.options.textNodeName]:u}])}i=s}else if(e.substr(i+1,2)==="!D"){let s=xer(e,i);this.docTypeEntities=s.entities,i=s.i}else if(e.substr(i+1,2)==="!["){let s=YI(e,"]]>",i,"CDATA is not closed.")-2,u=e.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=Ehe(e,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!==t.tagname&&(o+=o?"."+u:u),this.isItStopNode(this.options.stopNodes,o,u)){let h="";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 _=this.readStopNodeData(e,l,f+1);if(!_)throw new Error(`Unexpected end of ${l}`);i=_.i,h=_.tagContent}let m=new fz(u);u!==c&&d&&(m[":@"]=this.buildAttributesMap(c,o,u)),h&&(h=this.parseTextData(h,u,o,!0,d,!0,!0)),o=o.substr(0,o.lastIndexOf(".")),m.add(this.options.textNodeName,h),this.addChild(r,m,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 h=new fz(u);u!==c&&d&&(h[":@"]=this.buildAttributesMap(c,o,u)),this.addChild(r,h,o),o=o.substr(0,o.lastIndexOf("."))}else{let h=new fz(u);this.tagsNodeStack.push(r),u!==c&&d&&(h[":@"]=this.buildAttributesMap(c,o,u)),this.addChild(r,h,o),r=h}n="",i=f}}else n+=e[i];return t.child};function Aer(e,t,r){let n=this.options.updateTag(t.tagname,r,t[":@"]);n===!1||(typeof n=="string"&&(t.tagname=n),e.addChild(t))}var Rer=function(e){if(this.options.processEntities){for(let t in this.docTypeEntities){let r=this.docTypeEntities[t];e=e.replace(r.regx,r.val)}for(let t in this.lastEntities){let r=this.lastEntities[t];e=e.replace(r.regex,r.val)}if(this.options.htmlEntities)for(let t in this.htmlEntities){let r=this.htmlEntities[t];e=e.replace(r.regex,r.val)}e=e.replace(this.ampEntity.regex,this.ampEntity.val)}return e};function Der(e,t,r,n){return e&&(n===void 0&&(n=Object.keys(t.child).length===0),e=this.parseTextData(e,t.tagname,r,!1,t[":@"]?Object.keys(t[":@"]).length!==0:!1,n),e!==void 0&&e!==""&&t.add(this.options.textNodeName,e),e=""),e}function jer(e,t,r){let n="*
`;super(r),this.name="AggregateError",this.errors=t}};mye.exports={AggregateError:hye,kEmptyObject:Object.freeze({}),once(e){let t=!1;return function(...r){t||(t=!0,e.apply(this,r))}},createDeferredPromise:function(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}},promisify(e){return new Promise((t,r)=>{e((n,...o)=>n?r(n):t(...o))})},debuglog(){return function(){}},format(e,...t){return e.replace(/%([sdifj])/g,function(...[r,n]){let o=t.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(e){switch(typeof e){case"string":if(e.includes("'"))if(e.includes('"')){if(!e.includes("`")&&!e.includes("${"))return`\`${e}\``}else return`"${e}"`;return`'${e}'`;case"number":return isNaN(e)?"NaN":Object.is(e,-0)?String(e):e;case"bigint":return`${String(e)}n`;case"boolean":case"undefined":return String(e);case"object":return"{}"}},types:{isAsyncFunction(e){return e instanceof Mir},isArrayBufferView(e){return ArrayBuffer.isView(e)}},isBlob:Iir,deprecate(e,t){return e},addAbortListener:qz().addAbortListener||function(t,r){if(t===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",t);xat(t,"signal"),Air(r,"listener");let n;return t.aborted?queueMicrotask(()=>r()):(t.addEventListener("abort",r,{__proto__:null,once:!0,[Oir]:!0}),n=()=>{t.removeEventListener("abort",r)}),{__proto__:null,[Eir](){var o;(o=n)===null||o===void 0||o()}}},AbortSignalAny:Pir.any||function(t){if(t.length===1)return t[0];let r=new Tir,n=()=>r.abort();return t.forEach(o=>{xat(o,"signals"),o.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{t.forEach(o=>o.removeEventListener("abort",n))},{once:!0}),r.signal}};mye.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var Ld=b((lto,Eat)=>{"usestrict";var{format:Rir,inspect:JK,AggregateError:Dir}=Gc(),jir=globalThis.AggregateError||Dir,Nir=Symbol("kIsNodeError"),Lir=["string","function","number","object","Function","Object","boolean","bigint","symbol"],Fir=/^([A-Z][a-z0-9]*)+$/,kir="__node_internal_",GK={};function lA(e,t){if(!e)throw new GK.ERR_INTERNAL_ASSERTION(t)}function Cat(e){let t="",r=e.length,n=e[0]==="-"?1:0;for(;r>=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function Bir(e,t,r){if(typeof t=="function")return lA(t.length<=r.length,`Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${t.length}).`),t(...r);let n=(t.match(/%[dfijoOs]/g)||[]).length;return lA(n===r.length,`Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?t:Rir(t,...r)}function Yl(e,t,r){r||(r=Error);class n extends r{constructor(...i){super(Bir(e,t,i))}toString(){return`${this.name} [${e}]: ${this.message}`}}Object.defineProperties(n.prototype,{name:{value:r.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${e}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),n.prototype.code=e,n.prototype[Nir]=!0,GK[e]=n}function Oat(e){let t=kir+e.name;return Object.defineProperty(e,"name",{value:t}),e}function $ir(e,t){if(e&&t&&e!==t){if(Array.isArray(t.errors))return t.errors.push(e),t;let r=new jir([t,e],t.message);return r.code=t.code,r}return e||t}var gye=class extends Error{constructor(t="Theoperationwasaborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new GK.ERR_INVALID_ARG_TYPE("options","Object",r);super(t,r),this.code="ABORT_ERR",this.name="AbortError"}};Yl("ERR_ASSERTION","%s",Error);Yl("ERR_INVALID_ARG_TYPE",(e,t,r)=>{lA(typeof e=="string","'name'mustbeastring"),Array.isArray(t)||(t=[t]);let n="The";e.endsWith("argument")?n+=`${e} `:n+=`"${e}" ${e.includes(".")?"property":"argument"} `,n+="mustbe";let o=[],i=[],a=[];for(let u of t)lA(typeof u=="string","Allexpectedentrieshavetobeoftypestring"),Lir.includes(u)?o.push(u.toLowerCase()):Fir.test(u)?i.push(u):(lA(u!=="object",'The value "object" should be written as "Object"'),a.push(u));if(i.length>0){let
`);o.enqueue(s)}catch(i){o.error(i)}})},cancel(){var o;return S2(this,void 0,void 0,function*(){yield(o=r.return)===null||o===void 0?void 0:o.call(r)})}})}};ls.StreamUtils=U_e;function Ept(e,t){return C2(this,arguments,function*(){var n,o;if(!e.body)throw t?.abort(),new TL.CohereError({message:"Attempted to iterate over a response with no body"});let i=new z_e,a=new QE,s=H_e(e.body);try{for(var u=x2(nyr(s)),l;l=yield zi(u.next()),!l.done;){let c=l.value;for(let d of a.decode(c)){let f=i.decode(d);f&&(yield yield zi(f))}}}catch(c){n={error:c}}finally{try{l&&!l.done&&(o=u.return)&&(yield zi(o.call(u)))}finally{if(n)throw n.error}}for(let c of a.flush()){let d=i.decode(c);d&&(yield yield zi(d))}})}ls._iterSSEMessages=Ept;function nyr(e){return C2(this,arguments,function*(){var r,n;let o=new Uint8Array;try{for(var i=x2(e),a;a=yield zi(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=oyr(o))!==-1;)yield yield zi(o.slice(0,c)),o=o.slice(c)}}catch(s){r={error:s}}finally{try{a&&!a.done&&(n=i.return)&&(yield zi(n.call(i)))}finally{if(r)throw r.error}}o.length>0&&(yield yield zi(o))})}function oyr(e){for(let n=0;n<e.length-2;n++){if(e[n]===10&&e[n+1]===10||e[n]===13&&e[n+1]===13)return n+2;if(e[n]===13&&e[n+1]===10&&n+3<e.length&&e[n+2]===13&&e[n+3]===10)return n+4}return-1}var z_e=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(t){if(t.endsWith("\r")&&(t=t.substring(0,t.length-1)),!t){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(t),t.startsWith(":"))return null;let[r,n,o]=ayr(t,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},QE=class e{constructor(){this.buffer=[],this.trailingCR=!1}decode(t){let r=this.decodeText(t);if(this.trailingCR&&(r="\r"+r,this.trailingCR=!1),r.endsWith("\r")&&(this.trailingCR=!0,r=r.slice(0,-1)),!r)return[];let n=e.NEWLINE_CHARS.has(r[r.length-1]||""),o=r.split(e.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(t){var r;if(t==null)return"";if(typeof t=="string")return t;if(typeof Buffer<"u"){if(t instanceof Buffer)return t.toString();if(t instanceof Uint8Array)return Buffer.from(t).toString();throw new TL.CohereError({message:`Unexpected:receivednon-Uint8Array(${t.constructor.name})streamchunkinanenvironmentwithaglobal"Buffer"defined,whichthislibraryassumestobeNode.Pleasereportthiserror.`})}if(typeof TextDecoder<"u"){if(t instanceof Uint8Array||t instanceof ArrayBuffer)return(r=this.textDecoder)!==null&&r!==void 0||(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(t);throw new TL.CohereError({message:`Unexpected:receivednon-Uint8Array/ArrayBuffer(${t.constructor.name})inawebplatform.Pleasereportthiserror.`})}throw new TL.CohereError({message:"Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error."})}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let t=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,t}};ls.LineDecoder=QE;QE.NEWLINE_CHARS=new Set([`
`,"\r"]);QE.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function iyr(e){let t=new QE,r=[];for(let n of e)r.push(...t.decode(n));return r}ls._decodeChunks=iyr;function ayr(e,t){let r=e.indexOf(t);return r!==-1?[e.substring(0,r),t,e.substring(r+t.length)]:[e,"",""]}function H_e(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{next(){return S2(this,void 0,void 0,function*(){try{let r=yield t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}})},return(){return S2(this,void 0,void 0,function*(){let r=t.cancel();return t.releaseLock(),yield r,{done:!0,value:void 0}})},[Symbol.asyncIterator](){return this}}}ls.readableStreamAsyncIterable=H_e});var V_e=b(rb=>{"use strict";var syr=rb&&rb.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),uyr=rb&&rb.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),lyr=rb&&rb.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&syr(t,e,r);return uyr(t,e),t};Object.defineProperty(rb,"__esModule",{value:!0});rb.V2ChatStreamRequestCitationMode=void 0;var cyr=lyr($());rb.V2ChatStreamRequestCitationMode=cyr.serialization.enum_(["FAST","ACCURATE","OFF"])});var W_e=b(nb=>{"use strict";var dyr=nb&&nb.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),fyr=nb&&nb.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),pyr=nb&&nb.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&dyr(t,e,r);return fyr(t,e),t};Object.defineProperty(nb,"__esModule",{value:!0});nb.V2ChatRequestCitationMode=void 0;var hyr=pyr($());nb.V2ChatRequestCitationMode=hyr.serialization.enum_(["FAST","ACCURATE","OFF"])});var ML=b(ob=>{"use strict";var myr=ob&&ob.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),gyr=ob&&ob.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),yyr=ob&&ob.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&myr(t,e,r);return gyr(t,e),t};Object.defineProperty(ob,"__esModule",{value:!0});ob.TextContent=void 0;var Tpt=yyr($());ob.TextContent=Tpt.serialization.object({text:Tpt.serialization.string()})});var J_e=b(ib=>{"use strict";var byr=ib&&ib.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),_yr=ib&&ib.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),vyr=ib&&ib.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&byr(t,e,r);return _yr(t,e),t};Object.defineProperty(ib,"__esModule",{value:!0});ib.Content=void 0;var wyr=vyr($()),Syr=ML();ib.Content=wyr.serialization.union("type",{text:Syr.TextContent}).transform({
`)}}}}catch(S){a={error:S}}finally{try{m&&!m.done&&(s=h.return)&&(yield s.call(h))}finally{if(a)throw a.error}}for(let S of g.flush()){let x=(0,_o.parseAWSEvent)(S);if(x){let O=yield(0,_o.mapResponseFromBedrock)(c,u,x);v.push(JSON.stringify(O)+`
`)}}return v.end(),{ok:!0,body:v}}else{let _=yield p.body;return{ok:!0,body:yield(0,_o.mapResponseFromBedrock)(c,u,_)}}}catch(_){throw _}});_o.fetchOverride=wjr});var Mx=b(vZ=>{"use strict";Object.defineProperty(vZ,"__esModule",{value:!0});vZ.CohereEnvironment=void 0;vZ.CohereEnvironment={Production:"https://api.cohere.com"}});var cP=b((Zmt,wZ)=>{(function(e,t,r){typeof wZ<"u"&&wZ.exports?wZ.exports=r():typeof define=="function"&&define.amd?define(r):t[e]=r()})("urljoin",Zmt,function(){function e(t){var r=[];if(t.length===0)return"";if(typeof t[0]!="string")throw new TypeError("Url must be a string. Received "+t[0]);if(t[0].match(/^[^/:]+:\/*$/)&&t.length>1){var n=t.shift();t[0]=n+t[0]}t[0].match(/^file:\/\/\//)?t[0]=t[0].replace(/^([^/:]+):\/*/,"$1:///"):t[0]=t[0].replace(/^([^/:]+):\/*/,"$1://");for(var o=0;o<t.length;o++){var i=t[o];if(typeof i!="string")throw new TypeError("Url must be a string. Received "+i);i!==""&&(o>0&&(i=i.replace(/^[\/]+/,"")),o<t.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 t;return typeof arguments[0]=="object"?t=arguments[0]:t=[].slice.call(arguments),e(t)}})});var tSe=b(xf=>{"use strict";var Sjr=xf&&xf.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),xjr=xf&&xf.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),K2=xf&&xf.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&Sjr(t,e,r);return xjr(t,e),t},SZ=xf&&xf.__awaiter||function(e,t,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(e,t||[])).next())})},Cjr=xf&&xf.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(xf,"__esModule",{value:!0});xf.V2=void 0;var Xmt=K2(Mx()),wf=K2($()),Ra=K2(QS()),Sf=K2(Tx()),Qmt=Cjr(cP()),Ix=K2(Wa()),eSe=class{constructor(t={}){this._options=t}chatStream(t,r){var n,o;return SZ(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:wf.fetcher)({url:(0,Qmt.default)((o=yield wf.Supplier.get(this._options.environment))!==null&&o!==void 0?o:Xmt.CohereEnvironment.Production,"v2/chat"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield wf.Supplier.get(this._options.clientName))!=null?yield wf.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":wf.RUNTIME.type,"X-Fern-Runtime-Version":wf.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},Sf.V2ChatStreamRequest.jsonOrThrow(t,{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 wf.Stream({stream:i.body,parse:a=>SZ(this,void 0,void 0,function*(){return Sf.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 Ra.BadRequestError(i.error.body);case 401:throw new Ra.
`}});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new he.BadRequestError(i.error.body);case 401:throw new he.UnauthorizedError(i.error.body);case 403:throw new he.ForbiddenError(i.error.body);case 404:throw new he.NotFoundError(i.error.body);case 422:throw new he.UnprocessableEntityError(ze.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new he.TooManyRequestsError(ze.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new he.ClientClosedRequestError(ze.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 500:throw new he.InternalServerError(i.error.body);case 501:throw new he.NotImplementedError(ze.NotImplementedErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 503:throw new he.ServiceUnavailableError(i.error.body);case 504:throw new he.GatewayTimeoutError(ze.GatewayTimeoutErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));default:throw new nr.CohereError({statusCode:i.error.statusCode,body:i.error.body})}switch(i.error.reason){case"non-json":throw new nr.CohereError({statusCode:i.error.statusCode,body:i.error.rawBody});case"timeout":throw new nr.CohereTimeoutError;case"unknown":throw new nr.CohereError({message:i.error.errorMessage})}})}chat(t,r){var n,o;return Mf(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:et.fetcher)({url:(0,dg.default)((o=yield et.Supplier.get(this._options.environment))!==null&&o!==void 0?o:cg.CohereEnvironment.Production,"v1/chat"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield et.Supplier.get(this._options.clientName))!=null?yield et.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":et.RUNTIME.type,"X-Fern-Runtime-Version":et.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},ze.ChatRequest.jsonOrThrow(t,{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 ze.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 he.BadRequestError(i.error.body);case 401:throw new he.UnauthorizedError(i.error.body);case 403:throw new he.ForbiddenError(i.error.body);case 404:throw new he.NotFoundError(i.error.body);case 422:throw new he.UnprocessableEntityError(ze.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new he.TooManyRequestsError(ze.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new he.ClientClosedRequestError(ze.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{
`}});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new he.BadRequestError(i.error.body);case 401:throw new he.UnauthorizedError(i.error.body);case 403:throw new he.ForbiddenError(i.error.body);case 404:throw new he.NotFoundError(i.error.body);case 422:throw new he.UnprocessableEntityError(ze.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new he.TooManyRequestsError(ze.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new he.ClientClosedRequestError(ze.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 500:throw new he.InternalServerError(i.error.body);case 501:throw new he.NotImplementedError(ze.NotImplementedErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 503:throw new he.ServiceUnavailableError(i.error.body);case 504:throw new he.GatewayTimeoutError(ze.GatewayTimeoutErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));default:throw new nr.CohereError({statusCode:i.error.statusCode,body:i.error.body})}switch(i.error.reason){case"non-json":throw new nr.CohereError({statusCode:i.error.statusCode,body:i.error.rawBody});case"timeout":throw new nr.CohereTimeoutError;case"unknown":throw new nr.CohereError({message:i.error.errorMessage})}})}generate(t,r){var n,o;return Mf(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:et.fetcher)({url:(0,dg.default)((o=yield et.Supplier.get(this._options.environment))!==null&&o!==void 0?o:cg.CohereEnvironment.Production,"v1/generate"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield et.Supplier.get(this._options.clientName))!=null?yield et.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":et.RUNTIME.type,"X-Fern-Runtime-Version":et.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},ze.GenerateRequest.jsonOrThrow(t,{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 ze.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 he.BadRequestError(i.error.body);case 401:throw new he.UnauthorizedError(i.error.body);case 403:throw new he.ForbiddenError(i.error.body);case 404:throw new he.NotFoundError(i.error.body);case 422:throw new he.UnprocessableEntityError(ze.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new he.TooManyRequestsError(ze.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new he.ClientClosedRequestError(ze.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=ggt.default.toByteArray(n);this.rankMap.set(i.join(","),o),this.textMap.set(o,i)}this.specialTokens={...e.special_tokens,...t},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[o,i])=>(n[i]=this.textEncoder.encode(o),n),{})}encode(e,t=[],r="all"){let n=new RegExp(this.patStr,"ug"),o=ySe.specialTokenRegex(Object.keys(this.specialTokens)),i=[],a=new Set(t==="all"?Object.keys(this.specialTokens):t),s=new Set(r==="all"?Object.keys(this.specialTokens).filter(l=>!a.has(l)):r);if(s.size>0){let l=ySe.specialTokenRegex([...s]),c=e.match(l);if(c!=null)throw new Error(`Thetextcontainsaspecialtokenthatisnotallowed:${c[0]}`)}let u=0;for(;;){let l=null,c=u;for(;o.lastIndex=c,l=o.exec(e),!(l==null||a.has(l[0]));)c=l.index+1;let d=l?.index??e.length;for(let p of e.substring(u,d).matchAll(n)){let h=this.textEncoder.encode(p[0]),m=this.rankMap.get(h.join(","));if(m!=null){i.push(m);continue}i.push(...bNr(h,this.rankMap))}if(l==null)break;let f=this.specialTokens[l[0]];i.push(f),u=l.index+l[0].length}return i}decode(e){let t=[],r=0;for(let i=0;i<e.length;++i){let a=e[i],s=this.textMap.get(a)??this.inverseSpecialTokens[a];s!=null&&(t.push(s),r+=s.length)}let n=new Uint8Array(r),o=0;for(let i of t)n.set(i,o),o+=i.length;return this.textDecoder.decode(n)}},RZ=ySe;gNr(RZ,"specialTokenRegex",e=>new RegExp(e.map(t=>_Nr(t)).join("|"),"g"))});var bgt=C(()=>{ygt()});async function _gt(e){return e in DZ||(DZ[e]=vNr.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(t=>t.json()).then(t=>new RZ(t)).catch(t=>{throw delete DZ[e],t})),await DZ[e]}async function vgt(e){return _gt(bSe(e))}var DZ,vNr,_Se=C(()=>{bgt();kD();DZ={},vNr=new Qf({})});function gw(e){return typeof e!="object"||!e?!1:!!("type"in e&&e.type==="function"&&"function"in e&&typeof e.function=="object"&&e.function&&"name"in e.function&&"parameters"in e.function)}var wNr,SNr,QL,eF,a4=C(()=>{mgt();rq();gO();kD();_Se();sf();wNr=e=>e.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":e.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":e.startsWith("gpt-4-32k")?"gpt-4-32k":e.startsWith("gpt-4-")?"gpt-4":e.startsWith("gpt-4o")?"gpt-4o":e;SNr=()=>!1,QL=class extends nn{get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(t){super(t),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=t.verbose??SNr(),this.callbacks=t.callbacks,this.tags=t.tags??[],this.metadata=t.metadata??{}}},eF=class extends QL{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}constructor({callbacks:t,callbackManager:r,...n}){let{cache:o,...i}=n;super({callbacks:t??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=AZ.global():this.cache=void 0,this.caller=new Qf(n??{})}async getNumTokens(t){if(typeof t!="string")return 0;let r=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await vgt("modelName"in this?wNr(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(t).length}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}return r}static _convertInputToPromptValue(t){return typeof t=="string"?new qD(t):Array.isArray(t)?new UD(t.map(Nm)):t}_identifyingParams(){return{}}_getSerializedCacheKeyParameters
]`;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(`Couldnotconvertregexpatternat${t.currentPath.join("/")}toaflag-independentform!Fallingbacktotheflag-ignorantsource`),e.source}return o}});var Pre=b(Ere=>{"use strict";Object.defineProperty(Ere,"__esModule",{value:!0});Ere.parseRecordDef=void 0;var T3=me(),NMt=Pu(),$Yr=Ore(),qYr=yre();function UYr(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===T3.ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:(0,NMt.parseDef)(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:(0,NMt.parseDef)(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??{}};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===T3.ZodFirstPartyTypeKind.ZodString&&e.keyType._def.checks?.length){let{type:n,...o}=(0,$Yr.parseStringDef)(e.keyType._def,t);return{...r,propertyNames:o}}else{if(e.keyType?._def.typeName===T3.ZodFirstPartyTypeKind.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===T3.ZodFirstPartyTypeKind.ZodBranded&&e.keyType._def.type._def.typeName===T3.ZodFirstPartyTypeKind.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...o}=(0,qYr.parseBrandedDef)(e.keyType._def,t);return{...r,propertyNames:o}}}return r}Ere.parseRecordDef=UYr});var VEe=b(Tre=>{"use strict";Object.defineProperty(Tre,"__esModule",{value:!0});Tre.parseMapDef=void 0;var LMt=Pu(),zYr=Pre();function HYr(e,t){if(t.mapStrategy==="record")return(0,zYr.parseRecordDef)(e,t);let r=(0,LMt.parseDef)(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},n=(0,LMt.parseDef)(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}Tre.parseMapDef=HYr});var WEe=b(Mre=>{"use strict";Object.defineProperty(Mre,"__esModule",{value:!0});Mre.parseNativeEnumDef=void 0;function VYr(e){let t=e.values,n=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[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}}Mre.parseNativeEnumDef=VYr});var JEe=b(Ire=>{"use strict";Object.defineProperty(Ire,"__esModule",{value:!0});Ire.parseNeverDef=void 0;function WYr(){return{not:{}}}Ire.parseNeverDef=WYr});var GEe=b(Are=>{"use strict";Object.defineProperty(Are,"__esModule",{value:!0});Are.parseNullDef=void 0;function JYr(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}Are.parseNullDef=JYr});var Rre=b(rT=>{"use strict";Object.defineProperty(rT,"__esModule",{value:!0});rT.parseUnionDef=rT.primitiveMappings=void 0;var GYr=Pu();rT.primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function KYr(e,t){if(t.target==="openApi3")return FMt(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in rT.primitiveMappings&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=rT.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._
`);var ki={},nJt=0;function KM(e,t){let r=`atom${++nJt}`,n={toString(){return(ki.env?ki.env.MODE:void 0)!=="production"&&this.debugLabel?r+":"+this.debugLabel:r}};return typeof e=="function"?n.read=e:(n.init=e,n.read=oJt,n.write=iJt),t&&(n.write=t),n}function oJt(e){return e(this)}function iJt(e,t,r){return t(this,typeof r=="function"?r(e(this)):r)}var QFe=(e,t)=>e.unstable_is?e.unstable_is(t):t===e,Wue=e=>"init"in e,Jue=e=>!!e.write,JV=new WeakMap,Kue=e=>{var t;return Yue(e)&&!((t=JV.get(e))!=null&&t[1])},aJt=(e,t)=>{let r=JV.get(e);if(r)r[1]=!0,r[0].forEach(n=>n(t));else if((ki.env?ki.env.MODE:void 0)!=="production")throw new Error("[Bug] cancelable promise not found")},sJt=e=>{if(JV.has(e))return;let t=[new Set,!1];JV.set(e,t);let r=()=>{t[1]=!0};e.then(r,r),e.onCancel=n=>{t[0].add(n)}},Yue=e=>typeof e?.then=="function",eke=e=>"v"in e||"e"in e,WV=e=>{if("e"in e)throw e.e;if((ki.env?ki.env.MODE:void 0)!=="production"&&!("v"in e))throw new Error("[Bug] atom state is not initialized");return e.v},nke=(e,t,r)=>{r.p.has(e)||(r.p.add(e),t.then(()=>{r.p.delete(e)},()=>{r.p.delete(e)}))},tke=(e,t,r,n,o)=>{var i;if((ki.env?ki.env.MODE:void 0)!=="production"&&n===t)throw new Error("[Bug] atom cannot depend on itself");r.d.set(n,o.n),Kue(r.v)&&nke(t,r.v,o),(i=o.m)==null||i.t.add(t),e&&uJt(e,n,t)},YD=()=>[new Map,new Map,new Set],Gue=(e,t,r)=>{e[0].has(t)||e[0].set(t,new Set),e[1].set(t,r)},uJt=(e,t,r)=>{let n=e[0].get(t);n&&n.add(r)},lJt=(e,t)=>e[0].get(t),rke=(e,t)=>{e[2].add(t)},OO=e=>{let t,r=!1,n=o=>{try{o()}catch(i){r||(t=i,r=!0)}};for(;e[1].size||e[2].size;){e[0].clear();let o=new Set(e[1].values());e[1].clear();let i=new Set(e[2]);e[2].clear(),o.forEach(a=>{var s;return(s=a.m)==null?void 0:s.l.forEach(n)}),i.forEach(n)}if(r)throw t},oke=(...[e,t,r,n])=>{let o;(ki.env?ki.env.MODE:void 0)!=="production"&&(o=new Set);let i=(S,x,O)=>{let T="v"in x,E=x.v,M=Kue(x.v)?x.v:null;if(Yue(O)){sJt(O);for(let A of x.d.keys())nke(S,O,e(A));x.v=O,delete x.e}else x.v=O,delete x.e;(!T||!Object.is(E,x.v))&&(++x.n,M&&aJt(M,O))},a=(S,x,O)=>{var T;let E=e(x);if(eke(E)&&(E.m&&!O?.has(x)||Array.from(E.d).every(([k,L])=>a(S,k,O).n===L)))return E;E.d.clear();let M=!0,A=k=>{if(QFe(x,k)){let q=e(k);if(!eke(q))if(Wue(k))i(k,q,k.init);else throw new Error("no atom init");return WV(q)}let L=a(S,k,O);try{return WV(L)}finally{if(M)tke(S,x,E,k,L);else{let q=YD();tke(q,x,E,k,L),p(q,x,E),OO(q)}}},j,N,F={get signal(){return j||(j=new AbortController),j.signal},get setSelf(){return(ki.env?ki.env.MODE:void 0)!=="production"&&!Jue(x)&&console.warn("setSelf function cannot be used with read-only atom"),!N&&Jue(x)&&(N=(...k)=>{if((ki.env?ki.env.MODE:void 0)!=="production"&&M&&console.warn("setSelf function cannot be called in sync"),!M)return f(x,...k)}),N}};try{let k=t(x,A,F);if(i(x,E,k),Yue(k)){(T=k.onCancel)==null||T.call(k,()=>j?.abort());let L=()=>{if(E.m){let q=YD();p(q,x,E),OO(q)}};k.then(L,L)}return E}catch(k){return delete E.v,E.e=k,++E.n,E}finally{M=!1}},s=S=>WV(a(void 0,S)),u=(S,x,O)=>{var T,E;let M=new Map;for(let A of((T=O.m)==null?void 0:T.t)||[])M.set(A,e(A));for(let A of O.p)M.set(A,e(A));return(E=lJt(S,x))==null||E.forEach(A=>{M.set(A,e(A))}),M};function l(S,x,O){let T=[],E=new Set,M=new Set,A=[[x,O]];for(;A.length>0;){let[j,N]=A[A.length-1];if(M.has(j)){A.pop();continue}if(E.has(j)){T.push([j,N,N.n]),M.add(j),A.pop();continue}E.add(j);for(let[F,k]of u(S,j,N))j!==F&&!E.has(F)&&A.push([F,k])}return[T,M]}let c=(S,x,O)=>{let[T,E]=l(S,x,O),M=new Set([x]);for(let A=T.length-1;A>=0;--A){let[j,N,F]=T[A],k=!1;for(let L of N.d.keys())if(L!==j&&M.has(L)){k=!0;break}k&&(a(S,j,E),p(S,j,N),F!==N.n&&(Gue(S,j,N),M.add(j))),E.delete(j)}},d=(S,x,...O)=>{let T=!0,E=A=>WV(a(S,A)),M=(A,...j)=>{let N=e(A);try{if(QFe(x,A)){if(!Wue(A))throw new Error("atom not writable");let F=N.n,k=j[0];i(A,N,k),p(S,A,N),F!==N.n&&(Gue(S,A,N),c(S,A,N));return}else return d(S,A,...j)}finally{T||OO(S)}};try{return r(x,E,M,...O)}finally{T=!1}},f=(S,...x)=>{let O=YD();try{return d(O,S,...x)}finally{OO(O)}},p=(S,x,O)=>{if(O.m&&!Kue(O.v)){for(let T of O.d.keys())O.m.d.has(T)||(h(S,T,e(T)).t.
<text>${cf}</text>`,showInContextMenu:!1}];var nI="https://api.brevilabs.com/v1",cl="copilot-chat-view",Uo="user",cy="ai",ale=`You are Obsidian Copilot, a helpful assistant that integrates AI to Obsidian note-taking.
1.SetaworkingembeddingmodelinQAsettings.Ifit's not a local model, don'tforgettosettheAPIkey.
2.Click'Refresh Index for Vault'andwaitforindexingtocomplete.Ifyouencountertheratelimitingerror,pleaseturnyourrequestperseconddowninQAsetting.`,nBe=6e3,Ile=.4,oBe=.4,Ale=15,Rle=448e3,jS={DEFAULT:"",READING_FILES:"Reading files",SEARCHING_WEB:"Searching the web",READING_FILE_TREE:"Reading file tree"},AO={SETTINGS:"settings",EXPIRED_MODAL:"expired_modal",CHAT_MODE_SELECT:"chat_mode_select",MODE_SELECT_TOOLTIP:"mode_select_tooltip"};var rI=(f=>(f.OPENAI="openai",f.AZURE_OPENAI="azure openai",f.ANTHROPIC="anthropic",f.COHEREAI="cohereai",f.GOOGLE="google",f.OPENROUTERAI="openrouterai",f.GROQ="groq",f.OLLAMA="ollama",f.LM_STUDIO="lm-studio",f.OPENAI_FORMAT="3rd party (openai-format)",f.COPILOT_PLUS="copilot-plus",f.MISTRAL="mistralai",f))(rI||{});var RO={reasoning:"This model supports general reasoning tasks.",vision:"This model supports image inputs.",websearch:"This model can access the internet."},PO=[{name:"copilot-plus-flash",provider:"copilot-plus",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"gpt-4o",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"gpt-4o-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"o1-mini",provider:"openai",enabled:!0,isBuiltIn:!0,capabilities:["reasoning"]},{name:"o3-mini",provider:"openai",enabled:!0,isBuiltIn:!0,capabilities:["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:"command-r",provider:"cohereai",enabled:!0,isBuiltIn:!0},{name:"command-r-plus",provider:"cohereai",enabled:!0,isBuiltIn:!0},{name:"gemini-2.0-pro-exp",provider:"google",enabled:!0,isBuiltIn:!0,capabilities:["vision"]},{name:"gemini-2.0-flash",provider:"google",enabled:!0,isBuiltIn:!0,capabilities:["vision"]},{name:"azure-openai",provider:"azure openai",enabled:!0,isBuiltIn:!0}],TO=(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))(TO||{});var pq=[{name:"copilot-plus-small",provider:"copilot-plus",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0},{name:"copilot-plus-large",provider:"copilot-plus-jina",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,believerExclusive:!0,dimensions:1024},{name:"copilot-plus-multilingual",provider:"copilot-plus-jina",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,dimensions:512},{name:"text-embedding-3-small",provider:"openai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0},{name:"text-embedding-3-large",provider:"openai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"embed-multilingual-light-v3.0",provider:"cohereai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"text-embedding-004",provider:"google",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"azure-openai",provider:"azure openai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0}],wle="nomic-embed-text",i5={openai:{label:"OpenAI",host:"https://api.openai.com",keyManagementURL:"https://platform.openai.com/api-keys",testModel:"gpt-4o"},"azure openai":{label:"Azure OpenAI",host:"",keyManagementURL:"",testModel:"azure-openai"},anthropic:{label:"Anthropic",host:"https://api.anthropic.com/",keyManagementURL:"https://console.anthropic.com/settings/keys",testModel:"claude-3-5-sonnet-latest"},cohereai:{label:"Cohere",host:"https://api.cohere.com",keyManagementURL:"https://dashboard.cohere.ai/api-keys",testModel:"command-r"},google:{label:"Gemini",host:"https://generativelanguage.googleapis.com",keyManagementURL:"https://makersuite.google.com/app/apikey",testModel:"gemini-2.0-flash"},openrouterai:{label:"OpenRouter",host:"https://openrouter.ai/api/v1/",keyManagementURL:"https://openrouter.ai/keys",testModel:"openai/chatgpt-4o-latest"},groq:{label:"Groq",host:"https://api.groq.com/openai",keyManagementURL:"https://console.groq.com/keys",testModel:"llama3-
`+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&i.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function Lgt(e){var t,r,n,o;let i=[];if(!((r=(t=e.candidates)===null||t===void 0?void 0:t[0].content)===null||r===void 0)&&r.parts)for(let a of(o=(n=e.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}var WNr=[s4.RECITATION,s4.SAFETY,s4.LANGUAGE];function $Z(e){return!!e.finishReason&&WNr.includes(e.finishReason)}function pP(e){var t,r,n;let o="";if((!e.candidates||e.candidates.length===0)&&e.promptFeedback)o+="Responsewasblocked",!((t=e.promptFeedback)===null||t===void 0)&&t.blockReason&&(o+=` due to ${e.promptFeedback.blockReason}`),!((r=e.promptFeedback)===null||r===void 0)&&r.blockReasonMessage&&(o+=`: ${e.promptFeedback.blockReasonMessage}`);else if(!((n=e.candidates)===null||n===void 0)&&n[0]){let i=e.candidates[0];$Z(i)&&(o+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(o+=`: ${i.finishMessage}`))}return o}function u4(e){return this instanceof u4?(this.v=e,this):new u4(e)}function JNr(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIteratorisnotdefined.");var n=r.apply(e,t||[]),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(h,m){i.push([f,p,h,m])>1||s(f,p)})})}function s(f,p){try{u(n[f](p))}catch(h){d(i[0][3],h)}}function u(f){f.value instanceof u4?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])}}var Fgt=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function GNr(e){let t=e.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),r=ZNr(t),[n,o]=r.tee();return{stream:YNr(n),response:KNr(o)}}async function KNr(e){let t=[],r=e.getReader();for(;;){let{done:n,value:o}=await r.read();if(n)return OSe(XNr(t));t.push(o)}}function YNr(e){return JNr(this,arguments,function*(){let r=e.getReader();for(;;){let{value:n,done:o}=yield u4(r.read());if(o)break;yield yield u4(OSe(n))}})}function ZNr(e){let t=e.getReader();return new ReadableStream({start(n){let o="";return i();function i(){return t.read().then(({value:a,done:s})=>{if(s){if(o.trim()){n.error(new ed("Failedtoparsestream"));return}n.close();return}o+=a;let u=o.match(Fgt),l;for(;u;){try{l=JSON.parse(u[1])}catch{n.error(new ed(`Error parsing JSON response: "${u[1]}"`));return}n.enqueue(l),o=o.substring(u[0].length),u=o.match(Fgt)}return i()})}}})}function XNr(e){let t=e[e.length-1],r={promptFeedback:t?.promptFeedback};for(let n of e){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 qgt(e,t,r,n){let o=await c4(t,YA.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(r),n);return GNr(o)}async function Ugt(e,t,r,n){let i=await(await c4(t,YA.GENERATE_CONTENT,e,!1,JSON.stringify(r),n)).json();return{response:OSe(i)}}function zgt(e){if(e!=null){if(typeof e=="string")return{role:"system",parts:[{text:e}]};if(e.text)return{role:"system",parts:[e]};if(e.parts)return e.role?e:{role:"system",parts:e.parts}}}function l4(e){let t=[];if(typeof e=="string")t=[{
`)===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{t.append(i,a)}catch(s){console.warn("Response "+s.message)}}}),t}Xgt.call(QA.prototype);function bw(e,t){if(!(this instanceof bw))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(t||(t={}),this.type="default",this.status=t.status===void 0?200:t.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=t.statusText===void 0?"":""+t.statusText,this.headers=new Wu(t.headers),this.url=t.url||"",this._initBody(e)}Xgt.call(bw.prototype);bw.prototype.clone=function(){return new bw(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new Wu(this.headers),url:this.url})};bw.error=function(){var e=new bw(null,{status:200,statusText:""});return e.ok=!1,e.status=0,e.type="error",e};var SLr=[301,302,303,307,308];bw.redirect=function(e,t){if(SLr.indexOf(t)===-1)throw new RangeError("Invalid status code");return new bw(null,{status:t,headers:{location:e}})};var XA=rc.DOMException;try{new XA}catch{XA=function(t,r){this.message=t,this.name=r;var n=Error(t);this.stack=n.stack},XA.prototype=Object.create(Error.prototype),XA.prototype.constructor=XA}function Qgt(e,t){return new Promise(function(r,n){var o=new QA(e,t);if(o.signal&&o.signal.aborted)return n(new XA("Aborted","AbortError"));var i=new XMLHttpRequest;function a(){i.abort()}i.onload=function(){var l={statusText:i.statusText,headers:wLr(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 bw(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 XA("Aborted","AbortError"))},0)};function s(l){try{return l===""&&rc.location.href?rc.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&&(kd.blob?i.responseType="blob":kd.arrayBuffer&&(i.responseType="arraybuffer")),t&&typeof t.headers=="object"&&!(t.headers instanceof Wu||rc.Headers&&t.headers instanceof rc.Headers)){var u=[];Object.getOwnPropertyNames(t.headers).forEach(function(l){u.push(nF(l)),i.setRequestHeader(l,MSe(t.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)})}Qgt.polyfill=!0;rc.fetch||(rc.fetch=Qgt,rc.Headers=Wu,rc.Request=QA,rc.Response=bw);var xLr="0.5.9",CLr=Object.defineProperty,OLr=(e,t,r)=>t in e?CLr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,ASe=(e,t,r)=>(OLr(e,typeof t!="symbol"?t+"":t,r),r),DSe=class e extends Error{constructor(t,r){super(t),this.error=t,this.status_code=r,this.name="ResponseError",Error.captureStackTrace&&Error.captureStackTrace(this,e)}},jSe=class{constructor(t,r,n){ASe(this,"abortController"),ASe(this,"itr"),ASe(this,"doneCallback"),this.abortController=t,this.itr=r,this.doneCallback=n}abort(){this.abortController.abort()}async*[Symbol.asyncIterator](){for await(let t of this.itr){if("error"in t)throw new Error(t.error);if(yield t,t.done||t.status==="success"){this.doneCallback();return}}throw new Error("Did not receive done or success response in stream.")}},NSe=async e=>{if(e.ok)return;let t=`Error${e.status}:${e.statusText}`,r=null;if(e.headers.get("content-type")?.includes("application/json"))try{r=await
`);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)}},MLr=e=>{if(!e)return"http://127.0.0.1:11434";let t=e.includes("://");e.startsWith(":")&&(e=`http://127.0.0.1${e}`,t=!0),t||(e=`http://${e}`);let r=new URL(e),n=r.port;n||(t?n=r.protocol==="https:"?"443":"80":n="11434");let o=`${r.protocol}//${r.hostname}:${n}${r.pathname}`;return o.endsWith("/")&&(o=o.slice(0,-1)),o},ILr=Object.defineProperty,ALr=(e,t,r)=>t in e?ILr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,RSe=(e,t,r)=>(ALr(e,typeof t!="symbol"?t+"":t,r),r),eR=class{constructor(t){RSe(this,"config"),RSe(this,"fetch"),RSe(this,"ongoingStreamedRequests",[]),this.config={host:""},t?.proxy||(this.config.host=MLr(t?.host??"http://127.0.0.1:11434")),this.fetch=fetch,t?.fetch!=null&&(this.fetch=t.fetch)}abort(){for(let t of this.ongoingStreamedRequests)t.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(t,r){r.stream=r.stream??!1;let n=`${this.config.host}/api/${t}`;if(r.stream){let i=new AbortController,a=await oF(this.fetch,n,r,{signal:i.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");let s=TLr(a.body),u=new jSe(i,s,()=>{let l=this.ongoingStreamedRequests.indexOf(u);l>-1&&this.ongoingStreamedRequests.splice(l,1)});return this.ongoingStreamedRequests.push(u),u}return await(await oF(this.fetch,n,r,{headers:this.config.headers})).json()}async encodeImage(t){if(typeof t!="string"){let r=new Uint8Array(t),n="",o=r.byteLength;for(let i=0;i<o;i++)n+=String.fromCharCode(r[i]);return btoa(n)}return t}async generate(t){return t.images&&(t.images=await Promise.all(t.images.map(this.encodeImage.bind(this)))),this.processStreamableRequest("generate",t)}async chat(t){if(t.messages)for(let r of t.messages)r.images&&(r.images=await Promise.all(r.images.map(this.encodeImage.bind(this))));return this.processStreamableRequest("chat",t)}async create(t){return this.processStreamableRequest("create",{name:t.model,stream:t.stream,modelfile:t.modelfile,quantize:t.quantize})}async pull(t){return this.processStreamableRequest("pull",{name:t.model,stream:t.stream,insecure:t.insecure})}async push(t){return this.processStreamableRequest("push",{name:t.model,stream:t.stream,insecure:t.insecure})}async delete(t){return await PLr(this.fetch,`${this.config.host}/api/delete`,{name:t.model}),{status:"success"}}async copy(t){return await oF(this.fetch,`${this.config.host}/api/copy`,{...t}),{status:"success"}}async list(){return await(await eyt(this.fetch,`${this.config.host}/api/tags`)).json()}async show(t){return await(await oF(this.fetch,`${this.config.host}/api/show`,{...t})).json()}async embed(t){return await(await oF(this.fetch,`${this.config.host}/api/embed`,{...t})).json()}async embeddings(t){return await(await oF(this.fetch,`${this.config.host}/api/embeddings`,{...t})).json()}async ps(){return await(await eyt(this.fetch,`${this.config.host}/api/ps`)).json()}},RLr=new eR;kh();iy();var nc=[];for(WZ=0;WZ<256;++WZ)nc.push((WZ+256).toString(16).slice(1));var WZ;function tyt(e,t=0){return(nc[e[t+0]]+nc[e[t+1]]+nc[e[t+2]]+nc[e[t+3]]+"-"+nc[e[t+4]]+nc[e[t+5]]+"-"+nc[e[t+6]]+nc[e[t+7]]+"-"+nc[e[t+8]]+nc[e[t+9]]+"-"+nc[e[t+10]]+nc[e[t+11]]+nc[e[t+12]]+nc[e[t+13]]+nc[e[t+14]]+nc[e[t+15]]).toLowerCase()}var JZ,DLr=new Uint8Array(16);function FSe(){if(!JZ&&(JZ=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!JZ))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return JZ(DLr)}var jLr=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),kSe={randomUUID:jLr};function NLr(e,t,r){if(kSe.randomUUID&&!t&&!e)return kSe.randomUUID();e=e||{};var n=e.random||(e.rng||FSe)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){r=r||0;for(var o=0;o<16;++o)t[r+o]=n[o];return t}return tyt(n)}var BSe=NLr;function $Se(e,t){return new Jr({content:e.content??"",tool_call_chunks:e.tool_calls?.map(r=>({name:r.function.name,args:JSON.stringify(r.function.arguments),type:"tool_call_chunk",index:0,id:BSe()})),response_
`,"\r"]);nR.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function ZSe(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var ww=class e{constructor(t,r){this.iterator=t,this.controller=r}static fromSSEResponse(t,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 QLr(t,r))if(!i){if(a.data.startsWith("[DONE]")){i=!0;continue}if(a.event===null){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 fs(void 0,s.error,void 0,void 0);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 fs(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 e(o,r)}static fromReadableStream(t,r){let n=!1;async function*o(){let a=new nR,s=ZSe(t);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 e(i,r)}[Symbol.asyncIterator](){return this.iterator()}tee(){let t=[],r=[],n=this.iterator(),o=i=>({next:()=>{if(i.length===0){let a=n.next();t.push(a),r.push(a)}return i.shift()}});return[new e(()=>o(t),this.controller),new e(()=>o(r),this.controller)]}toReadableStream(){let t=this,r,n=new TextEncoder;return new JSe({async start(){r=t[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*QLr(e,t){if(!e.body)throw t.abort(),new qt("Attempted to iterate over a response with no body");let r=new XSe,n=new nR,o=ZSe(e.body);for await(let i of eFr(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*eFr(e){let t=new Uint8Array;for await(let r of e){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?new TextEncoder().encode(r):r,o=new Uint8Array(t.length+n.length);o.set(t),o.set(n,t.length),t=o;let i;for(;(i=tFr(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}function tFr(e){for(let n=0;n<e.length-2;n++){if(e[n]===10&&e[n+1]===10||e[n]===13&&e[n+1]===13)return n+2;if(e[n]===13&&e[n+1]===10&&n+3<e.length&&e[n+2]===13&&e[n+3]===10)return n+4}return-1}var XSe=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(t){if(t.endsWith("\r")&&(t=t.substring(0,t.length-1)),!t){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(t),t.startsWith(":"))return null;let[r,n,o]=rFr(t,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}};function rFr(e,t){let r=e.indexOf(t);return r!==-1?[e.substring(0,r),t,e.substring(r+t.length)]:[e,"",""]}var pyt=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function",hyt=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&f4(e),f4=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",nFr=e=>hyt(e)||pyt(e)||YSe(e);async function txe(e,t,r){if(e=await e,hyt(e))return e;if(pyt(e)){let o=await e.blob();t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=f4(o)?[await o.arrayBuffer()]:[o];return new XZ(i,t,r)}let n=await oFr(e);if(t||(t=aFr(e)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new XZ(n,t,r)}async function oFr(e){let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(f4(e))t.push(await e.arrayBuffer());else if(sFr(e))for await(let r of e)t.push(r);else throw new Error(`Unexpecteddatatype:${typeofe};constructor:${e?.constructor?.name};props:${iFr(e)}`);return t}function iFr(e){return`[${Object.getOwnPropertyNames(e).map(r=>`"${r}"`).join(", ")}]`}function aFr(e){return QSe(e.name)||QSe(e.filename)||QSe(e.path)?.split(/[\\/]/).pop()}var QSe=e=>{if(typeof e=="string")return e;if(typeof Buffer<"u"&&e instanceof Buffer)return String(e)},sFr=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function",rxe=e=>e&&typeof e=="object"&&e.body&&e[Symbol.toStringTag]==="MultipartBody";var Bh=async e=>{let t=await myt(e.body);return GSe(t,e)},myt=async e=>{let t=new WSe;return await Promise.all(Object.entries(e||{}).map(([r,n])=>exe(t,r,n))),t};var exe=async(e,t,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Receivednullfor"${t}";topassnullinFormData,youmustusethestring'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")e.append(t,String(r));else if(nFr(r)){let n=await txe(r);e.append(t,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>exe(e,t+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>exe(e,`${t}[${n}]`,o)));else throw new TypeError(`Invalidvaluegiventoform,expectedastring,number,boolean,object,Array,FileorBlobbutgot${r}instead`)}};var lFr=function(e,t,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 t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r},cFr=function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},rX;async function wyt(e){let{response:t}=e;if(e.options.stream)return mF("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):ww.fromSSEResponse(t,e.controller);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let r=t.headers.get("content-type");if(r?.includes("application/json")||r?.includes("application/vnd.api+json")){let i=await t.json();return mF("response",t.status,t.url,t.headers,i),Syt(i,t)}let o=await t.text();return mF("response",t.status,t.url,t.headers,o),o}function Syt(e,t){return!e||typeof e!="object"||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}var oX=class e extends Promise{constructor(t,r=wyt){super(n=>{n(null)}
\r`.includes(e[n]);)n++};return a()},bxe=e=>TFr(e,bl.ALL^bl.NUM);var CF=function(e,t,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 t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r},Vo=function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},Gu,Fx,OF,yP,_xe,pX,vxe,wxe,Sxe,hX,xxe,jyt,EF=class e extends xF{constructor(t){super(),Gu.add(this),Fx.set(this,void 0),OF.set(this,void 0),yP.set(this,void 0),CF(this,Fx,t,"f"),CF(this,OF,[],"f")}get currentChatCompletionSnapshot(){return Vo(this,yP,"f")}static fromReadableStream(t){let r=new e(null);return r._run(()=>r._fromReadableStream(t)),r}static createChatCompletion(t,r,n){let o=new e(r);return o._run(()=>o._runChatCompletion(t,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createChatCompletion(t,r,n){super._createChatCompletion;let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),Vo(this,Gu,"m",_xe).call(this);let i=await t.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let a of i)Vo(this,Gu,"m",vxe).call(this,a);if(i.controller.signal?.aborted)throw new Xa;return this._addChatCompletion(Vo(this,Gu,"m",hX).call(this))}async _fromReadableStream(t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),Vo(this,Gu,"m",_xe).call(this),this._connected();let o=ww.fromReadableStream(t,this.controller),i;for await(let a of o)i&&i!==a.id&&this._addChatCompletion(Vo(this,Gu,"m",hX).call(this)),Vo(this,Gu,"m",vxe).call(this,a),i=a.id;if(o.controller.signal?.aborted)throw new Xa;return this._addChatCompletion(Vo(this,Gu,"m",hX).call(this))}[(Fx=new WeakMap,OF=new WeakMap,yP=new WeakMap,Gu=new WeakSet,_xe=function(){this.ended||CF(this,yP,void 0,"f")},pX=function(r){let n=Vo(this,OF,"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},Vo(this,OF,"f")[r.index]=n,n)},vxe=function(r){if(this.ended)return;let n=Vo(this,Gu,"m",jyt).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=Vo(this,Gu,"m",pX).call(this,i);i.finish_reason&&(Vo(this,Gu,"m",Sxe).call(this,i),a.current_tool_call_index!=null&&Vo(this,Gu,"m",wxe).call(this,i,a.current_tool_call_index));for(let s of o.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(Vo(this,Gu,"m",Sxe).call(this,i),a.current_tool_call_index!=null&&Vo(this,Gu,"m",wxe).call(this,i,a.current_tool_call_index)),a.current_tool_call_index=s.index;for(let s of o.delta.tool_calls??[]){let u=i.message.tool_calls?.[s.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:s.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,
${mX(e)}`);if(T==null)throw new qt(`missingchoices[${d}].tool_calls[${x}].type
${mX(e)}`);if(j==null)throw new qt(`missingchoices[${d}].tool_calls[${x}].function.name
${mX(e)}`);if(A==null)throw new qt(`missingchoices[${d}].tool_calls[${x}].function.arguments
${mX(e)}`);return{...M,id:E,type:T,function:{...N,name:j,arguments:A}}})}}:{...p,message:{...g,content:h,role:v,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}),created:o,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};return Myt(u,t)}function mX(e){return JSON.stringify(e)}var S4=class e extends EF{static fromReadableStream(t){let r=new e(null);return r._run(()=>r._fromReadableStream(t)),r}static runFunctions(t,r,n){let o=new e(null),i={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return o._run(()=>o._runFunctions(t,r,i)),o}static runTools(t,r,n){let o=new e(r),i={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(t,r,i)),o}};var x4=class extends ut{parse(t,r){return Ayt(t.tools),this._client.chat.completions.create(t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap(n=>v4(n,t))}runFunctions(t,r){return t.stream?S4.runFunctions(this._client,t,r):w4.runFunctions(this._client,t,r)}runTools(t,r){return t.stream?S4.runTools(this._client,t,r):w4.runTools(this._client,t,r)}stream(t,r){return EF.createChatCompletion(this._client,t,r)}};var PF=class extends ut{constructor(){super(...arguments),this.completions=new x4(this._client)}};(function(e){e.Completions=x4})(PF||(PF={}));var TF=class extends ut{create(t,r){return this._client.post("/realtime/sessions",{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}};var uR=class extends ut{constructor(){super(...arguments),this.sessions=new TF(this._client)}};uR.Sessions=TF;var St=function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},xp=function(e,t,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 t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r},oc,Cxe,xw,gX,bg,cR,MF,lR,_X,Cp,yX,bX,E4,C4,O4,Nyt,Lyt,Fyt,kyt,Byt,$yt,qyt,Cw=class e extends SF{constructor(){super(...arguments),oc.add(this),Cxe.set(this,[]),xw.set(this,{}),gX.set(this,{}),bg.set(this,void 0),cR.set(this,void 0),MF.set(this,void 0),lR.set(this,void 0),_X.set(this,void 0),Cp.set(this,void 0),yX.set(this,void 0),bX.set(this,void 0),E4.set(this,void 0)}[(Cxe=new WeakMap,xw=new WeakMap,gX=new WeakMap,bg=new WeakMap,cR=new WeakMap,MF=new WeakMap,lR=new WeakMap,_X=new WeakMap,Cp=new WeakMap,yX=new WeakMap,bX=new WeakMap,E4=new WeakMap,oc=new WeakSet,Symbol.asyncIterator)](){let t=[],r=[],n=!1;return this.on("event",o=>{let i=r.shift();i?i.resolve(o):t.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let i of r)i.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let i of r)i.reject(o);r.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((i,a)=>r.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(t){let r=new e;return r._run(()=>r._fromReadableStream(t)),r}async _fromReadableStream(t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();let o=ww.fromReadableStream(t,this.controller);for await(let i of o)St(this,oc,"m",C4).call(this,i);if(o.controller.signal?.aborted)throw new Xa;return this._addRun(St(this,oc,"m",O4).call(this))}toReadableStream(){return new ww(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(t,r,n,o,i){let a=new e;return a._run(()=>a._runToolAssistantStream(t,r,n,o,{...i,headers:{...i?.headers,"X-Stainless-
-`),fkr={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language"%s"isnotsupported.
Supportedlanguagesare:
-${dkr}`,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"wasdeclaredasa%s-dimensionalvector,butgota%s-dimensionalvectorinstead.
Inputvectorsmustbeofthesizedeclaredintheschema,ascalculatingsimilaritybetweenvectorsofdifferentsizescanleadtounexpectedresults.`,WRONG_SEARCH_PROPERTY_TYPE:'Property "%s" is not searchable. Only "string" properties are searchable.',FACET_NOT_SUPPORTED:`Facetdoens't support the type "%s".`,INVALID_DISTANCE_SUFFIX:'Invaliddistancesuffix"%s".Validsuffixesare:cm,m,km,mi,yd,ft.',INVALID_SEARCH_MODE:'Invalidsearchmode"%s".Validmodesare:"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"isarequiredparameterwhenperforminghybridsearch.Pleaseprovideasearchterm.',INVALID_VECTOR_INPUT:'Invalid"vector"property.Expectedanobjectwith"value"and"property"properties,butgot"%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'installedinyourOramainstance.
`,appendChunkOverlapHeader:!0})).forEach(d=>{d.pageContent.trim()&&i.push({content:d.pageContent,fileInfo:l})})}return i}getDocHash(t){return(0,o0t.MD5)(t).toString()}async getFilesToIndex(t){let{inclusions:r,exclusions:n}=MR(),o=this.app.vault.getMarkdownFiles();if(t)return o.filter(c=>TP(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(!TP(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 br([`Filestoindex:${u.size}`,`Previouslyindexed:${i.size}`,`Emptyfilesskipped:${l.size}`,`Filesmissingembeddings:${s.size}`].join(`
`)),Array.from(u)}initializeIndexingState(t){this.state={isIndexingPaused:!1,isIndexingCancelled:!1,indexedCount:0,totalFilesToIndex:t,processedFiles:new Set,currentIndexingNotice:null,indexNoticeMessage:null}}createIndexingNotice(){let t=document.createDocumentFragment(),r=t.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()}),t.appendChild(this.state.indexNoticeMessage),t.appendChild(n),this.state.currentIndexingNotice=new Rw.Notice(t,0),this.state.currentIndexingNotice}async handlePause(){if(this.state.isIndexingPaused){for(;this.state.isIndexingPaused&&!this.state.isIndexingCancelled;)await new Promise(t=>setTimeout(t,100));if(!this.state.isIndexingCancelled){let t=await this.getFilesToIndex();if(t.length===0){console.log("No files to index after filter change, stopping indexing"),this.cancelIndexing(),new Rw.Notice("No files to index with current filters");return}this.state.totalFilesToIndex=t.length,console.log("Total files to index:",this.state.totalFilesToIndex),console.log("Files to index:",t),this.updateIndexingNoticeMessage()}}}pauseIndexing(){this.state.isIndexingPaused=!0}resumeIndexing(){this.state.isIndexingPaused=!1}updateIndexingNoticeMessage(){if(this.state.indexNoticeMessage){let t=this.state.isIndexingPaused?" (Paused)":"",r=["Copilot is indexing your vault...",`${this.state.indexedCount}/${this.state.totalFilesToIndex}filesprocessed${t}`],n=pe(),o=PP(n.qaInclusions);o.length>0&&r.push(`Inclusions:${o.join(", ")}`);let a=[...OQ(this.app),...PP(n.qaExclusions)];a.length>0&&r.push(`Exclusions:${a.join(", ")}`),this.state.indexNoticeMessage.textContent=r.join(`
`)}}isStringLengthError(t){if(!t)return!1;if(t instanceof RangeError&&t.message.toLowerCase().includes("string length"))return!0;let n=(t.message||t.toString()).toLowerCase();return n.includes("string length")||n.includes("rangeerror")}handleError(t,r){let n=r?.filePath;if(n?(r.batch?console.error("Batch processing error:",{error:t,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:t?.constructor?.name,errorMessage:t?.message}):console.error(`Errorindexingfile${n}:`,t),r.errors?.push(n)):console.error("Fatal error during indexing:",t),this.state.currentIndexingNotice&&this.state.currentIndexingNotice.hide(),this.isStringLengthError(t)){new Rw.Notice("Vault is too large for 1 partition, please increase the number of partitions in your Copilot QA settings!",1e4);return}if(this.isRateLimitError(t))return;let o=n?`Errorindexingfile${n}.Checkconsolefordetails.`:"Fatal error during indexing. Check console for details.";new Rw.Notice(o)}isRateLimitError(t){return t?.message?.includes?.("rate limit")||!1}finalizeIndexing(t){if(this.state.currentIndexingNotice&&this.state.currentIndexingNotice.hide(),this.state.isIndexingCancelled){new Rw.Notice("Indexing cancelled");return}t.length>0?new Rw.Notice(`Indexingcompletedwith${t.length}errors.Checkconsolefordetails.`):new Rw.Notice("Indexing completed successfully!")}async reindexFile(t){try{let r=await this.embeddingsManager.getEmbeddingsAPI();if(!r)return;if(await this.dbOps.removeDocs(t.path),await this.dbOps.checkAndHandleEmbeddingModelChange(r)){await this.indexVaultToVectorStore(!0);return}let o=await this.prepareAllChunks([t]);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(),pe().debug&&console.log(`Reindexedfile:${t.path}`)}catch(r){this.handleError(r,{filePath:t.path})}}async cancelIndexing(){console.log("Indexing cancelled by user"),this.state.isIndexingCancelled=!0,await new Promise(t=>setTimeout(t,100)),this.state.currentIndexingNotice&&this.state.currentIndexingNotice.hide()}};var ma=class e{constructor(){this.embeddingsManager=ps.getInstance(),this.dbOps=new Ux(app),this.indexOps=new MQ(app,this.dbOps,this.embeddingsManager),this.eventHandler=new EQ(app,this.indexOps,this.dbOps),this.initializationPromise=this.initialize(),this.setupSettingsSubscription()}static getInstance(){return e.instance||(e.instance=new e),e.instance}setupSettingsSubscription(){this.lastKnownSettings={...pe()};let t=async()=>{let r=pe(),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())}};sl(()=>{this.initializationPromise=t()})}async initialize(){try{let t=3;for(;t>0;)try{await this.dbOps.initializeDB(await this.embeddingsManager.getEmbeddingsAPI());break}catch(r){if(r instanceof dr&&r.message.includes("Vault adapter not available")&&(t--,t>0)){await new Promise(n=>setTimeout(n,100));continue}new $4.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(t){console.error("Failed to initialize vector store:",t)}}async waitForInitialization(){await this.initializationPromise}async indexVaultToVectorStore(t){return await this.waitForInitialization(),$4.Platform.isMobile&&pe().disableIndexOnMobile?(new $4.Notice("Indexing is disabled on mobile devices"),0):this.indexOps.indexVaultToVectorStore(t)}async clearIndex(){await this.waitForInitialization(),await this.dbOps.clearIndex(await this.embeddingsManager.getEmbeddingsAPI())}async garbageCollectVectorStore(){return aw
`);o.enqueue(s)}catch(i){o.error(i)}},async cancel(){await r.return?.()}})}};async function*s$r(e,t){if(!e.body)throw t.abort(),new zr("Attempted to iterate over a response with no body");let r=new vCe,n=new QF,o=m0t(e.body);for await(let i of u$r(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*u$r(e){let t=new Uint8Array;for await(let r of e){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?new TextEncoder().encode(r):r,o=new Uint8Array(t.length+n.length);o.set(t),o.set(n,t.length),t=o;let i;for(;(i=l$r(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}function l$r(e){for(let n=0;n<e.length-2;n++){if(e[n]===10&&e[n+1]===10||e[n]===13&&e[n+1]===13)return n+2;if(e[n]===13&&e[n+1]===10&&n+3<e.length&&e[n+2]===13&&e[n+3]===10)return n+4}return-1}var vCe=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(t){if(t.endsWith("\r")&&(t=t.substring(0,t.length-1)),!t){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(t),t.startsWith(":"))return null;let[r,n,o]=c$r(t,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},QF=class e{constructor(){this.buffer=[],this.trailingCR=!1}decode(t){let r=this.decodeText(t);if(this.trailingCR&&(r="\r"+r,this.trailingCR=!1),r.endsWith("\r")&&(this.trailingCR=!0,r=r.slice(0,-1)),!r)return[];let n=e.NEWLINE_CHARS.has(r[r.length-1]||""),o=r.split(e.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(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof Buffer<"u"){if(t instanceof Buffer)return t.toString();if(t instanceof Uint8Array)return Buffer.from(t).toString();throw new zr(`Unexpected:receivednon-Uint8Array(${t.constructor.name})streamchunkinanenvironmentwithaglobal"Buffer"defined,whichthislibraryassumestobeNode.Pleasereportthiserror.`)}if(typeof TextDecoder<"u"){if(t instanceof Uint8Array||t instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(t);throw new zr(`Unexpected:receivednon-Uint8Array/ArrayBuffer(${t.constructor.name})inawebplatform.Pleasereportthiserror.`)}throw new zr("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let t=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,t}};QF.NEWLINE_CHARS=new Set([`
`,"\r"]);QF.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function c$r(e,t){let r=e.indexOf(t);return r!==-1?[e.substring(0,r),t,e.substring(r+t.length)]:[e,"",""]}function m0t(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var d$r=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function",f$r=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&q4(e),q4=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function";async function g0t(e,t,r){if(e=await e,f$r(e))return e;if(d$r(e)){let o=await e.blob();t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=q4(o)?[await o.arrayBuffer()]:[o];return new RQ(i,t,r)}let n=await p$r(e);if(t||(t=m$r(e)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new RQ(n,t,r)}async function p$r(e){let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(q4(e))t.push(await e.arrayBuffer());else if(g$r(e))for await(let r of e)t.push(r);else throw new Error(`Unexpecteddatatype:${typeofe};constructor:${e?.constructor?.name};props:${h$r(e)}`);return t}function h$r(e){return`[${Object.getOwnPropertyNames(e).map(r=>`"${r}"`).join(", ")}]`}function m$r(e){return SCe(e.name)||SCe(e.filename)||SCe(e.path)?.split(/[\\/]/).pop()}var SCe=e=>{if(typeof e=="string")return e;if(typeof Buffer<"u"&&e instanceof Buffer)return String(e)},g$r=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function",xCe=e=>e&&typeof e=="object"&&e.body&&e[Symbol.toStringTag]==="MultipartBody";var b$r=function(e,t,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 t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r},_$r=function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},NQ;async function S0t(e){let{response:t}=e;if(e.options.stream)return ek("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):Dw.fromSSEResponse(t,e.controller);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let r=t.headers.get("content-type");if(r?.includes("application/json")||r?.includes("application/vnd.api+json")){let i=await t.json();return ek("response",t.status,t.url,t.headers,i),i}let o=await t.text();return ek("response",t.status,t.url,t.headers,o),o}var LQ=class e extends Promise{constructor(t,r=S0t){super(n=>{n(null)}),this.responsePromise=t,this.parseResponse=r}_thenUnwrap(t){return new e(this.responsePromise,async r=>t(await this.parseResponse(r)))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){let[t,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:r}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(t,r){return this.parse().then(t,r)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}},FQ=class{constructor({baseURL:t,maxRetries:r=2,timeout:n=6e5,httpAgent:o,fetch:i}){this.baseURL=t,this.maxRetries=CCe("maxRetries",r),this.timeout=CCe("timeout",n),this.httpAgent=o,this.fetch=i??yCe}authHeaders(t){return{}}defaultHeaders(t){return{Accept:"application/json","Content-Type":"application/json","User
Pleasemigratetoanewermodel.Visithttps://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages",{body:t,timeout:this._client._options.timeout??6e5,...r,stream:t.stream??!1})}stream(t,r){return QQ.createMessage(this,t,r)}},I0t={"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"};DP||(DP={});var A0t,ei=class extends FQ{constructor({baseURL:t=BQ("ANTHROPIC_BASE_URL"),apiKey:r=BQ("ANTHROPIC_API_KEY")??null,authToken:n=BQ("ANTHROPIC_AUTH_TOKEN")??null,...o}={}){let i={apiKey:r,authToken:n,...o,baseURL:t||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&x0t())throw new zr(`It looks like you're running in a browser-like environment.
`);super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new AP(this),this.messages=new DP(this),this.beta=new IP(this),this._options=i,this.apiKey=r,this.authToken=n}defaultQuery(){return this._options.defaultQuery}defaultHeaders(t){return{...super.defaultHeaders(t),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01",...this._options.defaultHeaders}}validateHeaders(t,r){if(!(this.apiKey&&t["x-api-key"])&&r["x-api-key"]!==null&&!(this.authToken&&t.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(t){let r=this.apiKeyAuth(t),n=this.bearerAuth(t);return r!=null&&!$Q(r)?r:n!=null&&!$Q(n)?n:{}}apiKeyAuth(t){return this.apiKey==null?{}:{"X-Api-Key":this.apiKey}}bearerAuth(t){return this.authToken==null?{}:{Authorization:`Bearer${this.authToken}`}}};A0t=ei;ei.Anthropic=A0t;ei.HUMAN_PROMPT=`
`));return{type:"base64",media_type:r[1]??"",data:r[2]??""}}function L$r(e){let t=[];for(let r of e)if(r._getType()==="tool")if(typeof r.content=="string"){let n=t[t.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}):t.push(new Ua({content:[{type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}]}))}else t.push(new Ua({content:r.content}));else{let n=t[t.length-1];if(n?._getType()==="human"&&r._getType()==="human"){let o;typeof n.content=="string"?o=[{type:"text",text:n.content}]:o=n.content,typeof r.content=="string"?o.push({type:"text",text:r.content}):o=o.concat(r.content),n.content=o}else t.push(r)}return t}function N0t(e){if(e.id===void 0)throw new Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:e.id,name:e.name,input:e.args}}function L0t(e){let t=["tool_use","tool_result","input_json_delta"],r=["text","text_delta"];return typeof e=="string"?e:e.map(o=>{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=j0t(o.image_url):a=j0t(o.image_url.url),{type:"image",source:a,...i?{cache_control:i}:{}}}else{if(r.find(a=>a===o.type)&&"text"in o)return{type:"text",text:o.text,...i?{cache_control:i}:{}};if(t.find(a=>a===o.type)){let a={...o};if("index"in a&&delete a.index,a.type==="input_json_delta"&&(a.type="tool_use"),"input"in a)try{a.input=JSON.parse(a.input)}catch{}return{...a,...i?{cache_control:i}:{}}}else throw new Error("Unsupported message content format")}})}function eee(e){let t=L$r(e),r;return t.length>0&&t[0]._getType()==="system"&&(r=e[0].content),{messages:(r!==void 0?t.slice(1):t).map(i=>{let a;if(i._getType()==="human")a="user";else if(i._getType()==="ai")a="assistant";else if(i._getType()==="tool")a="user";else throw i._getType()==="system"?new Error("System messages are only permitted as the first passed message."):new Error(`Messagetype"${i._getType()}"isnotsupported.`);if(Fu(i)&&i.tool_calls?.length){if(typeof i.content=="string")return i.content===""?{role:a,content:i.tool_calls.map(N0t)}:{role:a,content:[{type:"text",text:i.content},...i.tool_calls.map(N0t)]};{let{content:s}=i;return!i.tool_calls.every(l=>s.find(c=>(c.type==="tool_use"||c.type==="input_json_delta")&&c.id===l.id))&&console.warn('The "tool_calls" field on a message is only respected if content is a string.'),{role:a,content:L0t(i.content)}}}else return{role:a,content:L0t(i.content)}}),system:r}}function F0t(e,t){if(e.type==="message_start"){let{content:r,usage:n,...o}=e.message,i={};for(let[s,u]of Object.entries(o))u!=null&&(i[s]=u);let a={input_tokens:n.input_tokens,output_tokens:n.output_tokens,total_tokens:n.input_tokens+n.output_tokens};return{chunk:new Jr({content:t.coerceContentToString?"":[],additional_kwargs:i,usage_metadata:t.streamUsage?a:void 0,id:e.message.id})}}else if(e.type==="message_delta"){let r={input_tokens:0,output_tokens:e.usage.output_tokens,total_tokens:e.usage.output_tokens};return{chunk:new Jr({content:t.coerceContentToString?"":[],additional_kwargs:{...e.delta},usage_metadata:t.streamUsage?r:void 0})}}else{if(e.type==="content_block_start"&&e.content_block.type==="tool_use")return{chunk:new Jr({content:t.coerceContentToString?"":[{index:e.index,...e.content_block,input:""}],additional_kwargs:{}})};if(e.type==="content_block_delta"&&e.delta.type==="text_delta"){let r=e.delta?.text;if(r!==void 0)return{chunk:new Jr({content:t.coerceContentToString?r:[{index:e.index,...e.delta}],additional_kwargs:{}})}}else{if(e.type==="content_block_delta"&&e.delta.type==="input_json_delta")return{chunk:new Jr({content:t.coerceContentToString?"":[{index:e.index,input:e.delta.partial_json,type:e.delta.type}],additional_kwargs:{}})};if(e.type==="content_block_start"&&e.content_block.type==="text"){let r=e.content_block?.text;if(r!==void 0)return{chunk:new Jr({content:t.coerceContentToString?r:[{index:e.index,...e.content_block}],additional_kwargs:{}})}}}}return null}func
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(t),t.startsWith(":"))return null;let[r,n,o]=V$r(t,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},vk=class e{constructor(){this.buffer=[],this.trailingCR=!1}decode(t){let r=this.decodeText(t);if(this.trailingCR&&(r="\r"+r,this.trailingCR=!1),r.endsWith("\r")&&(this.trailingCR=!0,r=r.slice(0,-1)),!r)return[];let n=e.NEWLINE_CHARS.has(r[r.length-1]||""),o=r.split(e.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(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof Buffer<"u"){if(t instanceof Buffer)return t.toString();if(t instanceof Uint8Array)return Buffer.from(t).toString();throw new wl(`Unexpected:receivednon-Uint8Array(${t.constructor.name})streamchunkinanenvironmentwithaglobal"Buffer"defined,whichthislibraryassumestobeNode.Pleasereportthiserror.`)}if(typeof TextDecoder<"u"){if(t instanceof Uint8Array||t instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(t);throw new wl(`Unexpected:receivednon-Uint8Array/ArrayBuffer(${t.constructor.name})inawebplatform.Pleasereportthiserror.`)}throw new wl("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let t=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,t}};vk.NEWLINE_CHARS=new Set([`
`,"\r","\v","\f","","","","\x85","\u2028","\u2029"]);vk.NEWLINE_REGEXP=/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g;function V$r(e,t){let r=e.indexOf(t);return r!==-1?[e.substring(0,r),t,e.substring(r+t.length)]:[e,"",""]}function U0t(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var z0t=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function",H0t=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&see(e),see=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",W$r=e=>H0t(e)||z0t(e)||HCe(e);async function KCe(e,t,r){if(e=await e,r??(r=H0t(e)?{lastModified:e.lastModified,type:e.type}:{}),z0t(e)){let o=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file"),new ree([o],t,r)}let n=await J$r(e);if(t||(t=K$r(e)??"unknown_file"),!r.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new ree(n,t,r)}async function J$r(e){let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(see(e))t.push(await e.arrayBuffer());else if(Y$r(e))for await(let r of e)t.push(r);else throw new Error(`Unexpecteddatatype:${typeofe};constructor:${e?.constructor?.name};props:${G$r(e)}`);return t}function G$r(e){return`[${Object.getOwnPropertyNames(e).map(r=>`"${r}"`).join(", ")}]`}function K$r(e){return JCe(e.name)||JCe(e.filename)||JCe(e.path)?.split(/[\\/]/).pop()}var JCe=e=>{if(typeof e=="string")return e;if(typeof Buffer<"u"&&e instanceof Buffer)return String(e)},Y$r=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function",YCe=e=>e&&typeof e=="object"&&e.body&&e[Symbol.toStringTag]==="MultipartBody";var Z4=async e=>{let t=await V0t(e.body);return UCe(t,e)},V0t=async e=>{let t=new $Ce;return await Promise.all(Object.entries(e||{}).map(([r,n])=>GCe(t,r,n))),t};var GCe=async(e,t,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Receivednullfor"${t}";topassnullinFormData,youmustusethestring'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")e.append(t,String(r));else if(W$r(r)){let n=await KCe(r);e.append(t,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>GCe(e,t+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>GCe(e,`${t}[${n}]`,o)));else throw new TypeError(`Invalidvaluegiventoform,expectedastring,number,boolean,object,Array,FileorBlobbutgot${r}instead`)}};var X$r=function(e,t,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 t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r},Q$r=function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},uee;async function Z0t(e){let{response:t}=e;if(e.options.stream)return wk("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):aee.fromSSEResponse(t,e.controller);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let r=t.headers.get("content-type");if(r?.includes("application/json")||r?.includes("application/vnd.api+json")){let i=await t.json();return wk("response",t.status,t.url,t.headers,i),i}let o=await t.text();return wk("response",t.status,t.url,t.headers,o),o}var lee=class e extends Promise{constructor(t
Received:${JSON.stringify(o,null,2)}`)};if(typeof o=="string")return o;if(Array.isArray(o)){let s=t(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(`Messagecontentmustbeastringoranarray.
Received:${JSON.stringify(o,null,2)}`)},n=o=>{if(Fu(o)&&o.tool_calls?.length)return o.tool_calls.map(i=>({...i,id:$Pe(i.id??"")})).map(BF)};return e.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:t(o.getType()),content:a,name:o.name,toolCallId:$Pe(o.tool_call_id)}:Fu(o)?i===void 0?{role:t(o.getType()),content:a}:{role:t(o.getType()),toolCalls:i}:{role:t(o.getType()),content:a}})}function Ern(e,t){let{message:r}=e;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=qPe(r.content);switch(r.role){case"assistant":{let i=[],a=[];for(let s of n)try{let u=wR(s,{returnId:!0});i.push({...u,id:u.id??hee().replace(/-/g,"")})}catch(u){a.push($F(s,u.message))}return new Po({content:o,tool_calls:i,invalid_tool_calls:a,additional_kwargs:{},usage_metadata:t?{input_tokens:t.promptTokens,output_tokens:t.completionTokens,total_tokens:t.totalTokens}:void 0})}default:return new Ua({content:o})}}function Prn(e,t){if(!e.content&&!e.toolCalls)return t?new Jr({content:"",usage_metadata:t?{input_tokens:t.promptTokens,output_tokens:t.completionTokens,total_tokens:t.totalTokens}:void 0}):null;let r=e.toolCalls?.length?e.toolCalls?.map((s,u)=>({...s,index:u,id:s.id??hee().replace(/-/g,""),type:"function"})):void 0,n="assistant";e.role&&(n=e.role);let o=qPe(e.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 jm({content:o}):n==="assistant"?new Jr({content:o,tool_call_chunks:a,additional_kwargs:i,usage_metadata:t?{input_tokens:t.promptTokens,output_tokens:t.completionTokens,total_tokens:t.totalTokens}:void 0}):n==="tool"?new mO({content:o,additional_kwargs:i,tool_call_id:r?.[0].id??""}):n==="function"?new wS({content:o,additional_kwargs:i}):new Dm({content:o,role:n})}function lAt(e){return e.map(t=>{if("function"in t)return t;let r=t.description??`Tool:${t.name}`;return{type:"function",function:{name:t.name,description:r,parameters:Li(t.schema)}}})}var vne=class extends Qc{static lc_name(){return"ChatMistralAI"}constructor(t){super(t??{}),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
withoutCORSError:`+bi(n)+`
withCORSError:`+bi(o);throw new Error(i)}}}findModelByName(t){return pe().activeModels.find(n=>n.name===t)}};async function Sne(e,t){let r=`Giventhefollowingconversationandafollowupquestion,
ExplicitChunks:`,s),console.log("Orama Chunks: ",l),console.log("Combined Chunks: ",c),console.log("Max Orama Score: ",f),h?console.log("Reranked Chunks: ",d):console.log("No reranking applied.")),d}async rewriteQuery(r){try{let n=await this.queryRewritePrompt.format({question:r}),i=await Ud.getInstance().getChatModel().bind({temperature:0}).invoke(n);return i&&"content"in i?aj(i.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 Ux.getDocsByPath(i,o.path);if(a){let s=a.map(u=>new zx({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&&(pe().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);br("==== Daily note date range: ====",d[0],d[d.length-1]);let f=ly(d.join(", "),app.vault),h=(await this.getExplicitChunks(f)).map(S=>({...S,metadata:{...S.metadata,includeInContext:!0}}));br("==== Modified time range: ====",l,c),s.where={mtime:{between:[l,c]}};let _=(await ic(a,s)).hits.map(S=>new zx({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=[...h,..._];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)}pe().debug&&console.log(`====OramaSearchParams:====
`,s);let u=await ic(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 zx({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 ps.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}}))}};bd();var zPe=Ep(async({timeRange:e,query:t,salientTerms:r})=>{if(await ma.getInstance().isIndexEmpty())throw new dr(s5);let o=e!==void 0,i=pe().maxSourceChunks<Ale?Ale:pe().maxSourceChunks;pe().debug&&console.log("returnAll:",o);let u=(await new oT({minSimilarityScore:o?0:.1,maxK:o?1e3:i,salientTerms:r,timeRange:e?{startTime:e.startTime.epoch,endTime:e.endTime.epoch}:void 0,textWeight:oBe,returnAll:o,useRerankerThreshold:.5}).getRelevantDocuments(t)).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:Er.object({timeRange:Er.object({startTime:Er.any(),endTime:Er.any()}).optional(),query:Er.string().describe("The search query"),salientTerms:Er.array(Er.string()).describe("List of salient terms extracted from the query")})}),hAt=Ep(async()=>{try{let e=await ma.getInstance().indexVaultToVectorStore();return`Pleasereportwhethertheindexingwassuccessful.
Ifsuccessistrue,justsayitissuccessful.If0filesisindexed,saytherearenonewfilestoindex.`+JSON.stringify({success:!0,message:e===0?"No new files to index.":`Indexed${e}filesinthevault.`})}catch(e){return console.error("Error indexing vault:",e),JSON.stringify({success:!1,message:"An error occurred while indexing the vault."})}},{name:"indexVault",description:"Index the vault to the Copilot index"}),HPe=Ep(async({query:e,chatHistory:t})=>{try{let r=await Sne(e,t),n=await _l.getInstance().webSearch(r),o=n.response.citations||[],i=o.length>0?`
`,n=JSON.stringify(t);if(n.length>15e5){let o=JTe(e,!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:Er.void()});bd();var GTe=Ep(async({url:e})=>{try{let t=await _l.getInstance().youtube4llm(e);return t.response.transcript?JSON.stringify({success:!0,transcript:t.response.transcript,elapsed_time_ms:t.elapsed_time_ms}):JSON.stringify({success:!1,message:"Transcript not available. Only English videos with the auto transcript option turned on are supported at the moment"})}catch(t){return console.error(`ErrortranscribingYouTubevideo${e}:`,t),JSON.stringify({success:!1,message:"An error occurred while transcribing the YouTube video."})}},{name:"youtubeTranscription",description:"Get the transcript of a YouTube video",schema:Er.object({url:Er.string().describe("The YouTube video URL"),brevilabsClient:Er.any().describe("The BrevilabsClient instance")})});var _B=class{},C1t=(e,t)=>{if(t!==void 0)return e[t];let r=Object.keys(e);if(r.length===1)return e[r[0]]},Zne=(e,t)=>{let r=C1t(e,t);if(!r){let n=Object.keys(e);throw new Error(`inputvalueshave${n.length}keys,youmustspecifyaninputkeyorpassonly1keyasinput`)}return r},KTe=(e,t)=>{let r=C1t(e,t);if(!r&&r!==""){let n=Object.keys(e);throw new Error(`outputvalueshave${n.length}keys,youmustspecifyanoutputkeyorpassonly1keyasoutput`)}return r};NM();UM();var YTe=class extends tf{addUserMessage(t){return this.addMessage(new Ua(t))}addAIChatMessage(t){return this.addMessage(new Po(t))}addAIMessage(t){return this.addMessage(new Po(t))}async addMessages(t){for(let r of t)await this.addMessage(r)}clear(){throw new Error("Not implemented.")}},vB=class extends YTe{constructor(t){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=t??[]}async getMessages(){return this.messages}async addMessage(t){this.messages.push(t)}async clear(){this.messages=[]}};var Ww=class extends _B{constructor(t){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=t?.chatHistory??new vB,this.returnMessages=t?.returnMessages??this.returnMessages,this.inputKey=t?.inputKey??this.inputKey,this.outputKey=t?.outputKey??this.outputKey}async saveContext(t,r){await this.chatHistory.addUserMessage(Zne(t,this.inputKey)),await this.chatHistory.addAIChatMessage(KTe(r,this.outputKey))}async clear(){await this.chatHistory.clear()}};ZTe();GM();var W8=class extends Ww{constructor(t){super({returnMessages:t?.returnMessages??!1,chatHistory:t?.chatHistory,inputKey:t?.inputKey,outputKey:t?.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=t?.humanPrefix??this.humanPrefix,this.aiPrefix=t?.aiPrefix??this.aiPrefix,this.memoryKey=t?.memoryKey??this.memoryKey,this.k=t?.k??this.k}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(t){let r=await this.chatHistory.getMessages();return this.returnMessages?{[this.memoryKey]:r.slice(-this.k*2)}:{[this.memoryKey]:of(r.slice(-this.k*2),this.humanPrefix,this.aiPrefix)}}};NM();ZTe();var O1=class e{constructor(){this.initMemory(),sl(()=>this.initMemory())}static getInstance(){return e.instance||(e.instance=new e),e.instance}initMemory(){let t=pe(
`,t)),t}async handleError(t,r,n,o){let i=bi(t);r&&console.error("Error during LLM invocation:",i);let a=t?.response?.data?.error||i,s=a?.code||i,u="";if(t?.message?.includes("Invalid license key")?u="Invalid Copilot Plus license key. Please check your license key in settings.":s==="model_not_found"?u="You do not have access to this model or the model does not exist, please check with your API provider.":u=`${s}`,console.error(a),n&&o){o("");let l=u.search("Troubleshooting URL");u=l!==-1?u.slice(0,l):u,i.search(/401|invalid|not valid/gi)!==-1&&(u=`Somethingwentwrong.PleasecheckifyouhavesetyourAPIkey.
Path:Settings>copilotplugin>BasicTab>SetKeys.
Orcheckmodelconfig
ErrorDetails:`+u),n({message:u,isErrorMessage:!0,sender:cy,isVisible:!0,timestamp:ll(new Date)})}else new M1t.Notice(u),console.error(a)}},Xne=class extends G8{async run(t,r,n,o,i){let{debug:a=!1}=i,s="";try{let l=await $C.getChain().stream({input:t.message});for await(let c of l){if(r.signal.aborted)break;s+=c.content,n(s)}}catch(u){await this.handleError(u,a,o,n)}return this.handleResponse(s,t,r,o,n,a)}},Qne=class extends G8{async run(t,r,n,o,i){let{debug:a=!1}=i,s="";try{if(await this.chainManager.vectorStoreManager.isIndexEmpty())return this.handleResponse(s5,t,r,o,n,a);let c=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),d=ij(c),f=await $C.getRetrievalChain().stream({question:t.message,chat_history:d});for await(let p of f){if(r.signal.aborted)break;s+=p.content,n(s)}s=this.addSourcestoResponse(s)}catch(u){await this.handleError(u,a,o,n)}return this.handleResponse(s,t,r,o,n,a)}addSourcestoResponse(t){let r=Yke($C.retrievedDocuments);if(r.length>0){let n=r.map(o=>`-[[${o}]]`).join(`
`;this.qaPrompt=ah.fromMessages([KD.fromTemplate(t)])}escapeTemplateString(t){return t.replace(/\{/g,"{{").replace(/\}/g,"}}")}getChatPrompt(){return this.chatPrompt}async getQAPrompt({question:t,context:r,systemMessage:n}){return await this.qaPrompt.format({question:t,context:r,system_message:n})}};var Np=class Np{constructor(t,r){this.app=t,this.vectorStoreManager=r,this.memoryManager=O1.getInstance(),this.chatModelManager=Ud.getInstance(),this.promptManager=K8.getInstance(),this.initialize(),pBe(async()=>await this.createChainWithNewModel()),hBe(()=>this.setChain(qm(),{refreshIndex:pe().indexVaultToVectorStore==="ON MODE SWITCH"&&(qm()==="vault_qa"||qm()==="copilot_plus")})),sl(async()=>await this.createChainWithNewModel())}async initialize(){await this.createChainWithNewModel()}static getChain(){return Np.chain}static getRetrievalChain(){return Np.retrievalChain}validateChainType(t){if(t==null)throw new Error("No chain type set")}validateChatModel(){if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){let t="Chat model is not initialized properly, check your API key in Copilot setting and make sure you have API access.";throw new I1t.Notice(t),new Error(t)}}validateChainInitialization(){(!Np.chain||!Jke(Np.chain))&&(console.error("Chain is not initialized properly, re-initializing chain: ",qm()),this.setChain(qm()))}static storeRetrieverDocuments(t){Np.retrievedDocuments=t}async createChainWithNewModel(){let t=m5();try{let r=n5(t,pe().activeModels);r||(console.error("Resetting default model. No model configuration found for: ",t),r=PO[0],t=r.name+"|"+r.provider),await this.chatModelManager.setChatModel(r),this.setChain(qm()),br(`Settingmodelto${t}`)}catch(r){Ur(`createChainWithNewModelfailed:${r}`),br(`modelKey:${t}`)}}async setChain(t,r={}){if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){console.error("setChain failed: No chat model set.");return}this.validateChainType(t);let n=this.chatModelManager.getChatModel(),o=this.memoryManager.getMemory(),i=this.promptManager.getChatPrompt();switch(t){case"llm_chain":{Np.chain=a5.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),cj("llm_chain");break}case"vault_qa":{await this.initializeQAChain(r);let a=new oT({minSimilarityScore:.01,maxK:pe().maxSourceChunks,salientTerms:[]});Np.retrievalChain=a5.createConversationalRetrievalChain({llm:n,retriever:a,systemMessage:ZM()},Np.storeRetrieverDocuments.bind(Np),pe().debug),cj("vault_qa"),pe().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),Np.chain=a5.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),cj("copilot_plus");break}default:this.validateChainType(t);break}}getChainRunner(){let t=qm();switch(t){case"llm_chain":return new Xne(this);case"vault_qa":return new Qne(this);case"copilot_plus":return new eoe(this);default:throw new Error(`Unsupportedchaintype:${t}`)}}async initializeQAChain(t){t.refreshIndex&&await this.vectorStoreManager.indexVaultToVectorStore()}async runChain(t,r,n,o,i={}){let{debug:a=!1,ignoreSystemMessage:s=!1}=i;a&&console.log(`====Step0:Initialusermessage====
`),r=[],n="",o="",i="";for(let a of t)a.startsWith("**user**:")||a.startsWith("**ai**:")?(n&&o&&r.push({sender:n===Uo?Uo:cy,message:o.trim(),isVisible:!0,timestamp:i?Cle(i):null}),n=a.startsWith("**user**:")?Uo:cy,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===Uo?Uo:cy,message:o.trim(),isVisible:!0,timestamp:i?Cle(i):null}),r}async function Y8(e,t){await t.clearChatMemory();for(let r=0;r<e.length-1;r++){let n=e[r];if(n.sender===Uo){let o=e[r+1];o?.sender===cy&&await t.getMemory().saveContext({input:n.message},{output:o.message})}}}var wB=require("obsidian"),pr=B(Y()),R1t=B(gh());var toe=B(Y());var ti=toe.forwardRef(({className:e,type:t,...r},n)=>toe.createElement("input",{type:t,className:_e("!h-9 !min-w-[50px] !border border-border border-solid !rounded-md !bg-transparent !px-3 !py-1 md:!text-base !text-sm !transition-colors","focus-visible:!shadow-sm focus-visible:!outline-none focus-visible:!ring-1 focus-visible:!ring-ring","placeholder:text-xs","flex w-full shadow-sm placeholder:text-muted disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...r}));ti.displayName="Input";var pm=B(Y());var P1=pm.forwardRef(({className:e,value:t,...r},n)=>{let o=pm.useRef(null),i=pm.useCallback(()=>{let s=o.current;if(s){s.style.height="auto";let u=Math.min(s.scrollHeight,300);s.style.height=`${u}px`}},[]);pm.useLayoutEffect(()=>{i()},[t,i]),pm.useEffect(()=>(i(),window.addEventListener("resize",i),()=>window.removeEventListener("resize",i)),[i]);let a=s=>{o.current=s,typeof n=="function"?n(s):n&&(n.current=s)};return pm.createElement("textarea",{className:_e("border-solid resize-y min-w-fit overflow-auto","flex min-h-[60px] max-h-[300px] w-full rounded-md border border-primary-alt bg-transparent px-3 py-2 text-base shadow-sm placeholder:text-muted focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),value:t,ref:a,onChange:s=>{i(),r.onChange?.(s)},onInput:i,onCompositionEnd:i,onPaste:()=>{setTimeout(i,0)},...r})});P1.displayName="Textarea";function Iin({initialTitle:e="",initialPrompt:t="",disabledTitle:r=!1,onSave:n,onCancel:o}){let[i,a]=(0,pr.useState)(e),[s,u]=(0,pr.useState)(t),[l,c]=(0,pr.useState)({title:!1,prompt:!1}),[d,f]=(0,pr.useState)(!1),h=i&&/[<>:"/\\|?*\x00-\x1F]/g.test(i),m=async()=>{if(h){new wB.Notice("Title contains invalid characters. Please remove them before saving.");return}if(i&&s)try{f(!0),await n(i,s)}catch(S){new wB.Notice(bi(S))}finally{f(!1)}else c({title:!0,prompt:!0}),new wB.Notice("Please fill in both fields: Title and Prompt.")},_=l.title&&!i,g=l.prompt&&!s,v=i.trim()!==""&&s.trim()!==""&&!h;return pr.default.createElement("div",{className:"flex flex-col gap-4 p-4"},pr.default.createElement("div",{className:"text-xl font-bold text-normal mb-2"},"User Custom Prompt"),pr.default.createElement("div",{className:"flex flex-col"},pr.default.createElement("div",{className:"flex items-center gap-1"},pr.default.createElement("div",{className:"text-base font-medium text-normal"},"Title"),pr.default.createElement("span",{className:"text-error"},"*")),pr.default.createElement("div",{className:"flex flex-col gap-1"},pr.default.createElement("div",{className:"text-sm text-muted"},"The title of the prompt, must be unique."),pr.default.createElement("div",{className:"text-xs text-warning"},"Note: Title will be used as filename. Avoid using: ",'< > : " / \\ | ? *')),pr.default.createElement(ti,{type:"text",value:i,onChange:S=>{a(S.target.value),l.title||c(x=>({...x,title:!0}))},onBlur:()=>c(S=>({...S,title:!0})),disabled:r,className:"w-full mt-1",required:!0}),_&&pr.default.createElement("div",{className:"text-error text-xs mt-1"},"Title is required"),h&&pr.default.createElement("div",{className:"text-error text-xs mt-1"},"Title contains invalid characters")),pr.default.createElement("div",{className:"flex flex-col gap-1"},pr.default.createElement("div",{className:"space-y-2"},pr.default.createElement("div",{className:"flex items-center gap-1"},pr.default.createElement("div",{className:"text-base font-medium text-normal"},"Prompt"),pr.default.createElement("span",{className:"text-error"},"*")),pr.default.createElement("div",{className:"text-sm text-muted -mt-1"},"Use the following syntax in your prompt:")),pr.default.createElement("div",{className:"text
`),l="OramaDB-Debug-Search.md",c=this.app.vault.getAbstractFileByPath(l);c instanceof wT.TFile?await this.app.vault.modify(c,u):await this.app.vault.create(l,u);let d=this.app.vault.getAbstractFileByPath(l);d instanceof wT.TFile&&(await this.app.workspace.getLeaf().openFile(d),this.close())}catch(i){console.error("Error in debug search:",i),new wT.Notice("Error executing search. Check console for details.")}})}onClose(){let{contentEl:t}=this;t.empty()}};function SB(e){return e.replace(/\s+/g,"-").toLowerCase()}function j1t(e,t){if(!e)throw new Error("Command name is required");if(e.length>Mle)throw new Error(`Commandnamemustbelessthan${Mle}characters`);if(!/^[a-zA-Z0-9\s]+$/.test(e))throw new Error("Command name must only contain alphanumeric characters and spaces");if(T1().some(n=>n.name.toLowerCase()===e.toLowerCase()&&n.name.toLowerCase()!==t?.toLowerCase()))throw new Error("A command with this name already exists")}function N1t(e){return T1().find(r=>SB(r.name)===e)}function T1(){return pe().inlineEditCommands??uj}function L1t(){return qo().inlineEditCommands??uj}function F1t(e,t){let r=e.indexOf(cf);return r===-1?e+`
-[[Note2]]`,rows:"10",style:"width: 100%; min-height: 200px; margin: 10px 0; padding: 10px; font-family: monospace;"}}),t.createEl("div",{cls:"search-button-container"}).createEl("button",{text:"Show Index Data",cls:"mod-cta"}).addEventListener("click",async()=>{let o=this.searchInput.value,i=ly(o,this.app.vault).map(a=>a.path);if(i.length===0){new X8.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 X8.Notice("Error searching database. Check console for details.")}})}onClose(){let{contentEl:t}=this;t.empty()}};var Q8=require("obsidian"),uoe=class extends Q8.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 Q8.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 `Listallindexedfiles`.").setClass("remove-files-setting").addTextArea(o=>o.setPlaceholder(`-[[path/to/file1.md]]
`));let Ze={message:Bo,originalMessage:Ie,sender:Uo,isVisible:!1,timestamp:ct,content:Je,context:{notes:sr,urls:f==="copilot_plus"?[...ge||[],...Xi.imageUrls]:ge||[]}};l(Ze),m&&(n(m),M(-1)),await OAe(Ze,t,l,h,v,{debug:a.debug,updateLoadingMessage:T}),x(!1),T(jS.DEFAULT)},J=ee=>{let ge=i.userMessageHistory;return ee==="up"&&E<ge.length-1?(M(E+1),ge[ge.length-1-E-1]):ee==="down"&&E>-1?(M(E-1),E===0?"":ge[ge.length-1-E+1]):m},te=(0,jn.useCallback)(async(ee=!1)=>{if(!D){console.error("App instance is not available.");return}let ge=u.filter(Je=>Je.isVisible);if(ge.length===0){new Qw.Notice("No messages to save.");return}let Ue=ge[0].timestamp?.epoch||Date.now(),ct=ge.map(Je=>`**${Je.sender}**:${Je.message}