varIer=Object.create;varl2=Object.defineProperty;varMer=Object.getOwnPropertyDescriptor;varRer=Object.getOwnPropertyNames;varjer=Object.getPrototypeOf,Ner=Object.prototype.hasOwnProperty;varpUe=t=>{throwTypeError(t)};varDer=(t,e,r)=>eint?l2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;varw=(t,e)=>()=>(t&&(e=t(t=0)),e);varv=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Cf=(t,e)=>{for(varrine)l2(t,r,{get:e[r],enumerable:!0})},mUe=(t,e,r,n)=>{if(e&&typeofe=="object"||typeofe=="function")for(letoofRer(e))!Ner.call(t,o)&&o!==r&&l2(t,o,{get:()=>e[o],enumerable:!(n=Mer(e,o))||n.enumerable});returnt};varF=(t,e,r)=>(r=t!=null?Ier(jer(t)):{},mUe(e||!t||!t.__esModule?l2(r,"default",{value:t,enumerable:!0}):r,t)),zl=t=>mUe(l2({},"__esModule",{value:!0}),t);varCc=(t,e,r)=>Der(t,typeofe!="symbol"?e+"":e,r),Ler=(t,e,r)=>e.has(t)||pUe("Cannot "+r);varhUe=(t,e,r)=>e.has(t)?pUe("Cannot add the same private member more than once"):einstanceofWeakSet?e.add(t):e.set(t,r);vargUe=(t,e,r)=>(Ler(t,e,"access private method"),r);functionnpe(){if(!bK&&(bK=typeofcrypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!bK))thrownewError("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");returnbK(Fer)}varbK,Fer,yUe=w(()=>{Fer=newUint8Array(16)});functionbUe(t,e=0){returnOc[t[e+0]]+Oc[t[e+1]]+Oc[t[e+2]]+Oc[t[e+3]]+"-"+Oc[t[e+4]]+Oc[t[e+5]]+"-"+Oc[t[e+6]]+Oc[t[e+7]]+"-"+Oc[t[e+8]]+Oc[t[e+9]]+"-"+Oc[t[e+10]]+Oc[t[e+11]]+Oc[t[e+12]]+Oc[t[e+13]]+Oc[t[e+14]]+Oc[t[e+15]]}varOc,_Ue=w(()=>{Oc=[];for(lett=0;t<256;++t)Oc.push((t+256).toString(16).slice(1))});varker,ope,vUe=w(()=>{ker=typeofcrypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ope={randomUUID:ker}});function$er(t,e,r){if(ope.randomUUID&&!e&&!t)returnope.randomUUID();t=t||{};letn=t.random||(t.rng||npe)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){r=r||0;for(leto=0;o<16;++o)e[r+o]=n[o];returne}returnbUe(n)}varbC,wUe=w(()=>{vUe();yUe();_Ue();bC=$er});varc2=w(()=>{wUe()});functionqer(t){OUe=t}function_K(){returnOUe}functionut(t,e){letr=_K(),n=vK({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===LL?void0:LL].filter(o=>!!o)});t.common.issues.push(n)}functionwK(t,e,r,n){if(r==="a"&&!n)thrownewTypeError("Private accessor was defined without a getter");if(typeofe=="function"?t!==e||!n:!e.has(t))thrownewTypeError("Cannot read private member from an object whose class did not declare it");returnr==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}functionPUe(t,e,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(typeofe=="function"?t!==e||!o:!e.has(t))thrownewTypeError("Cannot write private member to an object whose class did not declare it");returnn==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r}functionHr(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))thrownewError(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);returne?{errorMap:e,description:o}:{errorMap:(a,s)=>{varu,l;let{message:c}=t;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}}functionTUe(t){lete="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";returnt.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),e}functionitr(t){returnnewRegExp(`^${TUe(t)}$`)}functionAUe(t){lete=`${EUe}T${TUe(t)}`,r=[];returnr.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,newRegExp(`^${e}$`)}functionatr(t,e){return!!((e==="v4"||!e)&&Xer.test(t)||(e==="v6"||!e)&&etr.test(t))}functionstr(t,e){if(!Ger.test(t))return!1;try{let[r]=t.split("."),n=r.replace(/-/g,"+").replace(/_/g,"/").pa
`),r}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch{console.warn("[WARNING]: LangSmith failed to fetch info on supported operations. Falling back to batch operations and default limits.")}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let e=await this._getBatchSizeLimitBytes();await this.drainAutoBatchQueue(e)}async createRun(e){if(!this._filterForSampling([e]).length)return;let r={...this.headers,"Content-Type":"application/json"},n=e.project_name;delete e.project_name;let o=await this.prepareRunCreateOrUpdateInputs({session_name:n,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&o.trace_id!==void 0&&o.dotted_order!==void 0){this.processRunOperation({action:"create",item:o}).catch(console.error);return}let i=o4e(o),a=await this.caller.call(Vt(this.debug),`${this.apiUrl}/runs`,{method:"POST",headers:r,body:hp(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(a,"create run",!0)}async batchIngestRuns({runCreates:e,runUpdates:r}){if(e===void 0&&r===void 0)return;let n=await Promise.all(e?.map(s=>this.prepareRunCreateOrUpdateInputs(s))??[]),o=await Promise.all(r?.map(s=>this.prepareRunCreateOrUpdateInputs(s))??[]);if(n.length>0&&o.length>0){let s=n.reduce((l,c)=>(c.id&&(l[c.id]=c),l),{}),u=[];for(let l of o)l.id!==void 0&&s[l.id]?s[l.id]={...s[l.id],...l}:u.push(l);n=Object.values(s),o=u}let i={post:n,patch:o};if(!i.post.length&&!i.patch.length)return;let a={post:[],patch:[]};for(let s of["post","patch"]){let u=s,l=i[u].reverse(),c=l.pop();for(;c!==void 0;)a[u].push(c),c=l.pop()}(a.post.length>0||a.patch.length>0)&&await this._postBatchIngestRuns(hp(a))}async _postBatchIngestRuns(e){let r={...this.headers,"Content-Type":"application/json",Accept:"application/json"},n=await this.batchIngestCaller.call(Vt(this.debug),`${this.apiUrl}/runs/batch`,{method:"POST",headers:r,body:e,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(n,"batch create run",!0)}async multipartIngestRuns({runCreates:e,runUpdates:r}){if(e===void 0&&r===void 0)return;let n={},o=[];for(let c of e??[]){let d=await this.prepareRunCreateOrUpdateInputs(c);d.id!==void 0&&d.attachments!==void 0&&(n[d.id]=d.attachments),delete d.attachments,o.push(d)}let i=[];for(let c of r??[])i.push(await this.prepareRunCreateOrUpdateInputs(c));if(o.find(c=>c.trace_id===void 0||c.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(i.find(c=>c.trace_id===void 0||c.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(o.length>0&&i.length>0){let c=o.reduce((f,p)=>(p.id&&(f[p.id]=p),f),{}),d=[];for(let f of i)f.id!==void 0&&c[f.id]?c[f.id]={...c[f.id],...f}:d.push(f);o=Object.values(c),i=d}if(o.length===0&&i.length===0)return;let u=[],l=[];for(let[c,d]of[["post",o],["patch",i]])for(let f of d){let{inputs:p,outputs:m,events:h,attachments:b,...g}=f,y={inputs:p,outputs:m,events:h},S=hp(g);l.push({name:`${c}.${g.id}`,payload:new Blob([S],{type:`application/json;length=${S.length}`})});for(let[x,O]of Object.entries(y)){if(O===void 0)continue;let P=hp(O);l.push({name:`${c}.${g.id}.${x}`,payload:new Blob([P],{type:`application/json;length=${P.length}`})})}if(g.id!==void 0){let x=n[g.id];if(x){delete n[g.id];for(let[O,P]of Object.entries(x)){let E,A;if(Array.isArray(P)?[E,A]=P:(E=P.mimeType,A=P.data),O.includes(".")){console.warn(`Skippingattachment'${O}'forrun${g.id}:Invalidattachmentname.Attachmentnamesmustnotcontainperiods('.').Pleaserenametheattachmentandtryagain.`);continue}l.push({name:`attachment.${g.id}.${O}`,payload:new Blob([A],{type:`${E};length=${A.byteLength}`})})}
Context: ${r}`)}}asyncupdateRun(e,r){Kr(e),r.inputs&&(r.inputs=awaitthis.processInputs(r.inputs)),r.outputs&&(r.outputs=awaitthis.processOutputs(r.outputs));letn={...r,id:e};if(!this._filterForSampling([n],!0).length)return;if(this.autoBatchTracing&&n.trace_id!==void0&&n.dotted_order!==void0){if(r.end_time!==void0&&n.parent_run_id===void0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){awaitthis.processRunOperation({action:"update",item:n}).catch(console.error);return}elsethis.processRunOperation({action:"update",item:n}).catch(console.error);return}leto={...this.headers,"Content-Type":"application/json"},i=awaitthis.caller.call(Vt(this.debug),`${this.apiUrl}/runs/${e}`,{method:"PATCH",headers:o,body:hp(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});awaitsn(i,"update run",!0)}asyncreadRun(e,{loadChildRuns:r}={loadChildRuns:!1}){Kr(e);letn=awaitthis._get(`/runs/${e}`);returnr&&n.child_run_ids&&(n=awaitthis._loadChildRuns(n)),n}asyncgetRunUrl({runId:e,run:r,projectOpts:n}){if(r!==void0){leto;r.session_id?o=r.session_id:n?.projectName?o=(awaitthis.readProject({projectName:n?.projectName})).id:n?.projectId?o=n?.projectId:o=(awaitthis.readProject({projectName:pp("PROJECT")||"default"})).id;leti=awaitthis._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${o}/r/${r.id}?poll=true`}elseif(e!==void0){leto=awaitthis.readRun(e);if(!o.app_path)thrownewError(`Run ${e} has no app_path`);return`${this.getHostUrl()}${o.app_path}`}elsethrownewError("Must provide either runId or run")}async_loadChildRuns(e){letr=awaityir(this.listRuns({id:e.child_run_ids})),n={},o={};r.sort((i,a)=>(i?.dotted_order??"").localeCompare(a?.dotted_order??""));for(letiofr){if(i.parent_run_id===null||i.parent_run_id===void0)thrownewError(`Child run ${i.id} has no parent`);i.parent_run_idinn||(n[i.parent_run_id]=[]),n[i.parent_run_id].push(i),o[i.id]=i}e.child_runs=n[e.id]||[];for(letiinn)i!==e.id&&(o[i].child_runs=n[i]);returne}async*listRuns(e){let{projectId:r,projectName:n,parentRunId:o,traceId:i,referenceExampleId:a,startTime:s,executionOrder:u,isRoot:l,runType:c,error:d,id:f,query:p,filter:m,traceFilter:h,treeFilter:b,limit:g,select:y}=e,S=[];if(r&&(S=Array.isArray(r)?r:[r]),n){letE=Array.isArray(n)?n:[n],A=awaitPromise.all(E.map(I=>this.readProject({projectName:I}).then(R=>R.id)));S.push(...A)}letx=["app_path","child_run_ids","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],O={session:S.length?S:null,run_type:c,reference_example:a,query:p,filter:m,trace_filter:h,tree_filter:b,execution_order:u,parent_run:o,start_time:s?s.toISOString():null,error:d,id:f,limit:g,trace:i,select:y||x,is_root:l},P=0;forawait(letEofthis._getCursorPaginatedList("/runs/query",O))if(g){if(P>=g)break;if(E.length+P>g){yield*E.slice(0,g-P);break}P+=E.length,yield*E}elseyield*E}asyncgetRunStats({id:e,trace:r,parentRun:n,runType:o,projectNames:i,projectIds:a,referenceExampleIds:s,startTime:u,endTime:l,error:c,query:d,filter:f,traceFilter:p,treeFilter:m,isRoot:h,dataSourceType:b}){letg=a||[];i&&(g=[...a||[],...awaitPromise.all(i.map(P=>this.readProject({projectName:P}).then(E=>E.id)))]);letS=Object.fromEntries(Object.entries({id:e,trace:r,parent_run:n,run_type:o,session:g,reference_example:s,start_time:u,end_time:l,error:c,query:d,filter:f,trace_filter:p,tree_filter:m,is_root:h,data_source_type:b}).filter(([P,E])=>E!==void0));returnawait(awaitthis.caller.call(Vt(this.debug),`${this.apiUrl}/runs/stats`,{method:"POST",headers:this.headers,body:JSON.stringify(S),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json()}asyncshareRun(e,{shareId:r}={}){letn={run_id:e,share_token:r||as()};Kr(e);leti=await(awaitthis.caller.call(Vt(this.debug),`${this.apiUrl}/runs/${e}/share`,{method:"PUT"
`)}`):new Error(`Failedtolistsharedexamples:${i.status}${i.statusText}`);return a.map(s=>({...s,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:r=null,metadata:n=null,upsert:o=!1,projectExtra:i=null,referenceDatasetId:a=null}){let s=o?"?upsert=true":"",u=`${this.apiUrl}/sessions${s}`,l=i||{};n&&(l.metadata=n);let c={name:e,extra:l,description:r};a!==null&&(c.reference_dataset_id=a);let d=await this.caller.call(Vt(this.debug),u,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(c),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await sn(d,"create project"),await d.json()}async updateProject(e,{name:r=null,description:n=null,metadata:o=null,projectExtra:i=null,endTime:a=null}){let s=`${this.apiUrl}/sessions/${e}`,u=i;o&&(u={...u||{},metadata:o});let l={name:r,extra:u,description:n,end_time:a?new Date(a).toISOString():null},c=await this.caller.call(Vt(this.debug),s,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await sn(c,"update project"),await c.json()}async hasProject({projectId:e,projectName:r}){let n="/sessions",o=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)Kr(e),n+=`/${e}`;else if(r!==void 0)o.append("name",r);else throw new Error("Must provide projectName or projectId");let i=await this.caller.call(Vt(this.debug),`${this.apiUrl}${n}?${o}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});try{let a=await i.json();return i.ok?Array.isArray(a)?a.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:r,includeStats:n}){let o="/sessions",i=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)Kr(e),o+=`/${e}`;else if(r!==void 0)i.append("name",r);else throw new Error("Must provide projectName or projectId");n!==void 0&&i.append("include_stats",n.toString());let a=await this._get(o,i),s;if(Array.isArray(a)){if(a.length===0)throw new Error(`Project[id=${e},name=${r}]notfound`);s=a[0]}else s=a;return s}async getProjectUrl({projectId:e,projectName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either projectName or projectId");let n=await this.readProject({projectId:e,projectName:r}),o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");let n=await this.readDataset({datasetId:e,datasetName:r}),o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let e=new URLSearchParams({limit:"1"});for await(let r of this._getPaginated("/sessions",e))return this._tenantId=r[0].tenant_id,r[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:r,nameContains:n,referenceDatasetId:o,referenceDatasetName:i,referenceFree:a,metadata:s}={}){let u=new URLSearchParams;if(e!==void 0)for(let l of e)u.append("id",l);if(r!==void 0&&u.append("name",r),n!==void 0&&u.append("name_contains",n),o!==void 0)u.append("reference_dataset",o);else if(i!==void 0){let l=await this.readDataset({datasetName:i});u.append("reference_dataset",l.id)}a!==void 0&&u.append("reference_free",a.toString()),s!==void 0&&u.append("metadata",JSON.stringify(s));for await(let l of this._getPaginated("/sessions",u))yield*l}async deleteProject({projectId:e,projectName:r}){let n;if(e===void 0&&r===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?n=(await this.readProject({projectName:r})).id:n=e,Kr(n);let o=await this.caller.call(Vt(this.debug),`${this.apiUrl}/sessions/${n}
`).map(s=>JSON.parse(s))}async*listDatasets({limit:e=100,offset:r=0,datasetIds:n,datasetName:o,datasetNameContains:i,metadata:a}={}){let s="/datasets",u=new URLSearchParams({limit:e.toString(),offset:r.toString()});if(n!==void 0)for(let l of n)u.append("id",l);o!==void 0&&u.append("name",o),i!==void 0&&u.append("name_contains",i),a!==void 0&&u.append("metadata",JSON.stringify(a));for await(let l of this._getPaginated(s,u))yield*l}async updateDataset(e){let{datasetId:r,datasetName:n,...o}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let i=r??(await this.readDataset({datasetName:n})).id;Kr(i);let a=await this.caller.call(Vt(this.debug),`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await sn(a,"update dataset"),await a.json()}async updateDatasetTag(e){let{datasetId:r,datasetName:n,asOf:o,tag:i}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let a=r??(await this.readDataset({datasetName:n})).id;Kr(a);let s=await this.caller.call(Vt(this.debug),`${this.apiUrl}/datasets/${a}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({as_of:typeof o=="string"?o:o.toISOString(),tag:i}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(s,"update dataset tags")}async deleteDataset({datasetId:e,datasetName:r}){let n="/datasets",o=e;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(o=(await this.readDataset({datasetName:r})).id),o!==void 0)Kr(o),n+=`/${o}`;else throw new Error("Must provide datasetName or datasetId");let i=await this.caller.call(Vt(this.debug),this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(i,`delete${n}`),await i.json()}async indexDataset({datasetId:e,datasetName:r,tag:n}){let o=e;if(!o&&!r)throw new Error("Must provide either datasetName or datasetId");if(o&&r)throw new Error("Must provide either datasetName or datasetId, not both");o||(o=(await this.readDataset({datasetName:r})).id),Kr(o);let i={tag:n},a=await this.caller.call(Vt(this.debug),`${this.apiUrl}/datasets/${o}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(a,"index dataset"),await a.json()}async similarExamples(e,r,n,{filter:o}={}){let i={limit:n,inputs:e};o!==void 0&&(i.filter=o),Kr(r);let a=await this.caller.call(Vt(this.debug),`${this.apiUrl}/datasets/${r}/search`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await sn(a,"fetch similar examples"),(await a.json()).examples}async createExample(e,r,n){if(a4e(e)&&(r!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let o=r?n?.datasetId:e.dataset_id,i=r?n?.datasetName:e.dataset_name;if(o===void 0&&i===void 0)throw new Error("Must provide either datasetName or datasetId");if(o!==void 0&&i!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");o===void 0&&(o=(await this.readDataset({datasetName:i})).id);let a=(r?n?.createdAt:e.created_at)||new Date,s;a4e(e)?s=e:s={inputs:e,outputs:r,created_at:a?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};let u=await this._uploadExamplesMultipart(o,[s]);return await this.readExample(u.example_ids?.[0]??as())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let y=e,S=y[0].dataset_id,x=y[0].dataset_name;if(S===void 0&&x===void 0)throw new Error("Must provide either datasetName or datasetId");if(S!==void 0&&x!==void 0)throw new
${o}`);throwi.statusCode=r.status,i}if(n.commits.length!==0)returnn.commits[0].commit_hash}async_likeOrUnlikePrompt(e,r){let[n,o,i]=CC(e),a=awaitthis.caller.call(Vt(this.debug),`${this.apiUrl}/likes/${n}/${o}`,{method:"POST",body:JSON.stringify({like:r}),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});returnawaitsn(a,`${r?"like":"unlike"} prompt`),awaita.json()}async_getPromptUrl(e){let[r,n,o]=CC(e);if(awaitthis._currentTenantIsOwner(r)){leti=awaitthis._getSettings();returno!=="latest"?`${this.getHostUrl()}/prompts/${n}/${o.substring(0,8)}?organizationId=${i.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${i.id}`}elsereturno!=="latest"?`${this.getHostUrl()}/hub/${r}/${n}/${o.substring(0,8)}`:`${this.getHostUrl()}/hub/${r}/${n}`}asyncpromptExists(e){return!!awaitthis.getPrompt(e)}asynclikePrompt(e){returnthis._likeOrUnlikePrompt(e,!0)}asyncunlikePrompt(e){returnthis._likeOrUnlikePrompt(e,!1)}async*listCommits(e){forawait(letrofthis._getPaginated(`/commits/${e}/`,newURLSearchParams,n=>n.commits))yield*r}async*listPrompts(e){letr=newURLSearchParams;r.append("sort_field",e?.sortField??"updated_at"),r.append("sort_direction","desc"),r.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void0&&r.append("is_public",e.isPublic.toString()),e?.query&&r.append("query",e.query);forawait(letnofthis._getPaginated("/repos",r,o=>o.repos))yield*n}asyncgetPrompt(e){let[r,n,o]=CC(e),i=awaitthis.caller.call(Vt(this.debug),`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(i.status===404)returnnull;awaitsn(i,"get prompt");leta=awaiti.json();returna.repo?a.repo:null}asynccreatePrompt(e,r){letn=awaitthis._getSettings();if(r?.isPublic&&!n.tenant_handle)thrownewError(`Cannot create a public prompt without first
https://smith.langchain.com/prompts`);let[o,i,a]=CC(e);if(!awaitthis._currentTenantIsOwner(o))throwawaitthis._ownerConflictError("create a prompt",o);lets={repo_handle:i,...r?.description&&{description:r.description},...r?.readme&&{readme:r.readme},...r?.tags&&{tags:r.tags},is_public:!!r?.isPublic},u=awaitthis.caller.call(Vt(this.debug),`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});awaitsn(u,"create prompt");let{repo:l}=awaitu.json();returnl}asynccreateCommit(e,r,n){if(!awaitthis.promptExists(e))thrownewError("Prompt does not exist, you must create it first.");let[o,i,a]=CC(e),s=n?.parentCommitHash==="latest"||!n?.parentCommitHash?awaitthis._getLatestCommitHash(`${o}/${i}`):n?.parentCommitHash,u={manifest:JSON.parse(JSON.stringify(r)),parent_commit:s},l=awaitthis.caller.call(Vt(this.debug),`${this.apiUrl}/commits/${o}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(u),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});awaitsn(l,"create commit");letc=awaitl.json();returnthis._getPromptUrl(`${o}/${i}${c.commit_hash?`:${c.commit_hash}`:""}`)}asyncupdateExamplesMultipart(e,r=[]){returnthis._updateExamplesMultipart(e,r)}async_updateExamplesMultipart(e,r=[]){if(!awaitthis._getMultiPartSupport())thrownewError("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");letn=newFormData;for(letsofr){letu=s.id,l={...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split}},c=hp(l),d=newBlob([c],{type:"application/json"});if(n.append(u,d),s.inputs){letf=hp(s.inputs),p=newBlob([f],{type:"application/json"});n.append(`${u}.inputs`,p)}if(s.outputs){letf=hp(s.outputs),p=newBlob([f],{type:"application/json"});n.append(`${u}.outputs`,p)}if(s.attachments)for(let[f,p]ofObject.entries(s.attachments)){letm,h;Array.isArray(p)?[m,h]=p:(m=p.mimeType,h=p.data);letb=newBlob([h],{type:`${m}; length=${h.byteLength}`});n.append(`${u}.attachment.${f}`,b)}if(s.attachments_operations){letf=hp(s.attachments_operations),p=newBlob([f],{type:"application/json"});n.append(`${u}.attachments_operations`,p)}}leto=e??r[0]?.dataset_id;returnawait(awaitthis.caller.call(Vt(this.debug),`${this.apiUrl}/v1/platform/datasets/${o}/examples`,{method:"PATCH",headers:this.headers,body:n})).json()}asyncuploadExamplesMultipart(e,r=[]){returnthis._uploadExamplesMultipart(e,r)}async_uploadExamplesMultipart(e,r=[]){if(!awaitthis._getMultiPartSupport())thrownewError("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");letn=newFormData;for(letaofr){lets=(a.id??as()).toString(),u={created_at:a.created_at,...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split},...a.source_run_id&&{source_run_id:a.source_run_id},...a.use_source_run_io&&{use_source_run_io:a.use_source_run_io},...a.use_source_run_attachments&&{use_source_run_attachments:a.use_source_run_attachments}},l=hp(u),c=newBlob([l],{type:"application/json"});if(n.append(s,c),a.inputs){letd=hp(a.inputs),f=newBlob([d],{type:"application/json"});n.append(`${s}.inputs`,f)}if(a.outputs){letd=hp(a.outputs),f=newBlob([d],{type:"application/json"});n.append(`${s}.outputs`,f)}if(a.attachments)for(let[d,f]ofObject.entries(a.attachments)){letp,m;Array.isArray(f)?[p,m]=f:(p=f.mimeType,m=f.data);leth=newBlob([m],{type:`${p}; length=${m.byteLength}`});n.append(`${s}.attachment.${d}`,h)}}leto=awaitthis.caller.call(Vt(this.debug),`${this.apiUrl}/v1/platform/datasets/${e}/examples`,{method:"POST",headers:this.headers,body:n});returnawaitsn(o,"upload examples"),awaito.json()}asyncupdatePrompt(e,r){if(!awaitthis.promptExists(e))thrownewError("Prompt does not exist, you must create it first.");let[n,o]=CC(e);if(!awaitthis._currentTenantIsOwner(n))throwawaitthis._ownerConflictError("
`)}var Nir,hR,E2=w(()=>{Nir=Object.prototype.hasOwnProperty;hR=class extends Error{constructor(e,r,n,o,i){super(g4e(e,{name:r,index:n,operation:o,tree:i})),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:o}),Object.defineProperty(this,"tree",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.setPrototypeOf(this,new.target.prototype),this.message=g4e(e,{name:r,index:n,operation:o,tree:i})}}});var Zpe={};Cf(Zpe,{JsonPatchError:()=>ss,_areEquals:()=>T2,applyOperation:()=>gR,applyPatch:()=>AE,applyReducer:()=>Fir,deepClone:()=>Dir,getValueByPointer:()=>lG,validate:()=>y4e,validator:()=>cG});function lG(t,e){if(e=="")return t;var r={op:"_get",path:e};return gR(t,r),r.value}function gR(t,e,r=!1,n=!0,o=!0,i=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):cG(e,0)),e.path===""){let a={newDocument:t};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=t,a;if(e.op==="move"||e.op==="copy")return a.newDocument=lG(t,e.from),e.op==="move"&&(a.removed=t),a;if(e.op==="test"){if(a.test=T2(t,e.value),a.test===!1)throw new ss("Testoperationfailed","TEST_OPERATION_FAILED",i,e,t);return a.newDocument=t,a}else{if(e.op==="remove")return a.removed=t,a.newDocument=null,a;if(e.op==="_get")return e.value=t,a;if(r)throw new ss("Operation`op`propertyisnotoneofoperationsdefinedinRFC-6902","OPERATION_OP_INVALID",i,e,t);return a}}else{n||(t=Md(t));let s=(e.path||"").split("/"),u=t,l=1,c=s.length,d,f,p;for(typeof r=="function"?p=r:p=cG;;){if(f=s[l],f&&f.indexOf("~")!=-1&&(f=P2(f)),o&&(f=="__proto__"||f=="prototype"&&l>0&&s[l-1]=="constructor"))throw new TypeError("JSON-Patch:modifying`__proto__`or`constructor/prototype`propisbannedforsecurityreasons,ifthiswasonpurpose,pleaseset`banPrototypeModifications`flagfalseandpassittothisfunction.Moreinfoinfast-json-patchREADME");if(r&&d===void 0&&(u[f]===void 0?d=s.slice(0,l).join("/"):l==c-1&&(d=e.path),d!==void 0&&p(e,0,t,d)),l++,Array.isArray(u)){if(f==="-")f=u.length;else{if(r&&!uG(f))throw new ss("Expectedanunsignedbase-10integervalue,makingthenewreferencedvaluethearrayelementwiththezero-basedindex","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,t);uG(f)&&(f=~~f)}if(l>=c){if(r&&e.op==="add"&&f>u.length)throw new ss("ThespecifiedindexMUSTNOTbegreaterthanthenumberofelementsinthearray","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);let m=Lir[e.op].call(e,u,f,t);if(m.test===!1)throw new ss("Testoperationfailed","TEST_OPERATION_FAILED",i,e,t);return m}}else if(l>=c){let m=VL[e.op].call(e,u,f,t);if(m.test===!1)throw new ss("Testoperationfailed","TEST_OPERATION_FAILED",i,e,t);return m}if(u=u[f],r&&l<c&&(!u||typeof u!="object"))throw new ss("Cannotperformoperationatthedesiredpath","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function AE(t,e,r,n=!0,o=!0){if(r&&!Array.isArray(e))throw new ss("Patchsequencemustbeanarray","SEQUENCE_NOT_AN_ARRAY");n||(t=Md(t));let i=new Array(e.length);for(let a=0,s=e.length;a<s;a++)i[a]=gR(t,e[a],r,!0,o,a),t=i[a].newDocument;return i.newDocument=t,i}function Fir(t,e,r){let n=gR(t,e);if(n.test===!1)throw new ss("Testoperationfailed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function cG(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new ss("Operationisnotanobject","OPERATION_NOT_AN_OBJECT",e,t,r);if(VL[t.op]){if(typeof t.path!="string")throw new ss("Operation`path`propertyisnotastring","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new ss('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new ss("Operation`from`propertyisnotpresent(applicablein`move`and`copy`operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)t
`)&&(n=n.substring(1));let o=n.indexOf("```"),i=n;return o!==-1&&(i=n.substring(0,o)),e(i.trim())}function KL(t){if(typeof t>"u")return null;try{return JSON.parse(t)}catch{}let e="",r=[],n=!1,o=!1;for(let i of t){if(n)i==='"'&&!o?n=!1:i===`
`&&!o?i="\\n":i==="\\"?o=!o:o=!1;else if(i==='"')n=!0,o=!1;else if(i==="{")r.push("}");else if(i==="[")r.push("]");else if(i==="}"||i==="]")if(r&&r[r.length-1]===i)r.pop();else return null;e+=i}n&&(e+='"');for(let i=r.length-1;i>=0;i-=1)e+=r[i];try{return JSON.parse(e)}catch{return null}}var ume=w(()=>{});function jE(t){return typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"&&"source_type"in t&&(t.source_type==="url"||t.source_type==="base64"||t.source_type==="text"||t.source_type==="id")}function z4e(t){return jE(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}function H4e(t){return jE(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}function V4e(t){if(jE(t)){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url}};if(t.source_type==="base64"){if(!t.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${t.mime_type};base64,${t.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function lme({dataUrl:t,asTypedArray:e=!1}){let r=t.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),n;if(r){n=r[1].toLowerCase();let o=e?Uint8Array.from(atob(r[2]),i=>i.charCodeAt(0)):r[2];return{mime_type:n,data:o}}}function W4e(t,e){if(t.type==="text"){if(!e.fromStandardTextBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardTextBlock\` method.`);return e.fromStandardTextBlock(t)}if(t.type==="image"){if(!e.fromStandardImageBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardImageBlock\` method.`);return e.fromStandardImageBlock(t)}if(t.type==="audio"){if(!e.fromStandardAudioBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardAudioBlock\` method.`);return e.fromStandardAudioBlock(t)}if(t.type==="file"){if(!e.fromStandardFileBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardFileBlock\` method.`);return e.fromStandardFileBlock(t)}throw new Error(`Unable to convert content block type '${t.type}' to provider-specific format: not recognized.`)}var cme=w(()=>{});function Oh(t,e){return typeof t=="string"?t===""?e:typeof e=="string"?t+e:Array.isArray(e)&&e.some(r=>jE(r))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e]:Array.isArray(e)?R2(t,e)??[...t,...e]:e===""?t:Array.isArray(t)&&t.some(r=>jE(r))?[...t,{type:"file",source_type:"text",text:e}]:[...t,{type:"text",text:e}]}function K4e(t,e){return t==="error"||e==="error"?"error":"success"}function Qir(t,e){function r(n,o){if(typeof n!="object"||n===null||n===void 0)return n;if(o>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(a=>r(a,o+1));let i={};for(let a of Object.keys(n))i[a]=r(n[a],o+1);return i}return JSON.stringify(r(t,0),null,2)}function xs(t,e){let r={...t};for(let[n,o]of Object.entries(e))if(r[n]==null)r[n]=o;else{if(o==null)continue;if(typeof r[n]!=typeof o||Array.isArray(r[n])!==Array.isArray(o))throw new Error(`field[${n}] already exists in the message chunk, but with a different type.`);if(typeof r[n]=="string"){if(n==="type")continue;r[n]+=o}else if(typeof r[n]=="object"&&!Array.isArray(r[n]))r[n]=xs(r[n],o);else if(Array.isArray(r[n]))r[n]=R2(r[n],o);else{if(r[n]===o)continue;console.warn(`field[${n}] already exists in this message chunk and value has unsupported type.`)}}return r}function R2(t,e){if(!(t===void 0&&e===void 0)){if(t===void 0||e===void 0)return t||e;{let r=[...t];for(let n of e)if(typeof n=="object"&&"index"in n&&typeof n.index=="number"){let o=r.findIndex(i=>i.index===n.index);o!==-1?r[o]=xs(r[o],n):r.push(n)}else{if(typeof n=="object"&&"text"in n&&n.text==="")continue;r.push(n)}return r}}}function G4e(t,e){if(!t&&!e)throw new Error("Cannot merge two undefined objects.");if(!t||!e)return t||e;if(typeof t!=typeof e)throw new Error(`Cannot merge objects of different types.
Right ${typeof e}`);if(typeof t=="string"&&typeof e=="string")return t+e;if(Array.isArray(t)&&Array.isArray(e))return R2(t,e);if(typeof t=="object"&&typeof e=="object")return xs(t,e);if(t===e)return t;throw new Error(`Can not merge objects of different types.
]`;continue}o+=n[u],n[u]==="\\"?i=!0:a&&n[u]==="]"?a=!1:!a&&n[u]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var qme,my,par,MG=w(()=>{FE();my={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(qme===void0&&(qme=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),qme),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};par=newSet("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});functionRG(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===de.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:fr(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};letr={type:"object",additionalProperties:fr(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")returnr;if(t.keyType?._def.typeName===de.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=IG(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===de.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===de.ZodBranded&&t.keyType._def.type._def.typeName===de.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=TG(t.keyType._def,e);return{...r,propertyNames:o}}}returnr}varjG=w(()=>{Td();qs();MG();AG()});functionD3e(t,e){if(e.mapStrategy==="record")returnRG(t,e);letr=fr(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=fr(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}varzme=w(()=>{qs();jG()});functionL3e(t){lete=t.values,n=Object.keys(t.values).filter(i=>typeofe[e[i]]!="number").map(i=>e[i]),o=Array.from(newSet(n.map(i=>typeofi)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}varHme=w(()=>{});functionF3e(){return{not:{}}}varVme
`}}let c={};for(let p of e){let m=p.source.split(":"),h=p.target.split(":"),b=m.filter((g,y)=>g===h[y]).join(":");c[b]||(c[b]=[]),c[b].push(p)}let d=new Set;function f(p,m){let h=p.length===1&&p[0].source===p[0].target;if(m&&!h){let b=m.split(":").pop();if(d.has(b))throw new Error(`Foundduplicatesubgraph'${b}'--thislikelymeansthatyou're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(b),l+=` subgraph ${b}
`)}f(c[""]??[],"");for(let p in c)!p.includes(":")&&p!==""&&f(c[p],p);return a&&(l+=Sar(i??{})),l}async function Q3e(t,e){let{backgroundColor:r="white"}=e??{},n=btoa(t);r!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));let o=`https://mermaid.ink/img/${n}?bgColor=${r}`,i=await fetch(o);if(!i.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${i.status}`,`Status text: ${i.statusText}`].join(`
`));return await i.blob()}var war,eHe=w(()=>{war=["*","_","`"]});function xar(t,e){if(t!==void 0&&!EE(t))return t;if(q2(e))try{let r=e.getName();return r=r.startsWith("Runnable")?r.slice(8):r,r}catch{return e.getName()}else return e.name??"UnknownSchema"}function Car(t){return q2(t.data)?{type:"runnable",data:{id:t.data.lc_id,name:t.data.getName()}}:{type:"schema",data:{...So(t.data.schema),title:t.data.name}}}function tHe(t,e=[]){let r=new Set(t.edges.filter(o=>!e.includes(o.source)).map(o=>o.target)),n=[];for(let o of Object.values(t.nodes))!e.includes(o.id)&&!r.has(o.id)&&n.push(o);return n.length===1?n[0]:void 0}function rHe(t,e=[]){let r=new Set(t.edges.filter(o=>!e.includes(o.target)).map(o=>o.source)),n=[];for(let o of Object.values(t.nodes))!e.includes(o.id)&&!r.has(o.id)&&n.push(o);return n.length===1?n[0]:void 0}var z2,nHe=w(()=>{Ec();TE();Pme();eHe();z2=class t{constructor(e){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){let e={};return Object.values(this.nodes).forEach((r,n)=>{e[r.id]=EE(r.id)?n:r.id}),{nodes:Object.values(this.nodes).map(r=>({id:e[r.id],...Car(r)})),edges:this.edges.map(r=>{let n={source:e[r.source],target:e[r.target]};return typeof r.data<"u"&&(n.data=r.data),typeof r.conditional<"u"&&(n.conditional=r.conditional),n})}}addNode(e,r,n){if(r!==void 0&&this.nodes[r]!==void 0)throw new Error(`Node with id ${r} already exists`);let o=r??as(),i={id:o,data:e,name:xar(r,e),metadata:n};return this.nodes[o]=i,i}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(r=>r.source!==e.id&&r.target!==e.id)}addEdge(e,r,n,o){if(this.nodes[e.id]===void 0)throw new Error(`Source node ${e.id} not in graph`);if(this.nodes[r.id]===void 0)throw new Error(`Target node ${r.id} not in graph`);let i={source:e.id,target:r.id,data:n,conditional:o};return this.edges.push(i),i}firstNode(){return tHe(this)}lastNode(){return rHe(this)}extend(e,r=""){let n=r;Object.values(e.nodes).map(l=>l.id).every(EE)&&(n="");let i=l=>n?`${n}:${l}`:l;Object.entries(e.nodes).forEach(([l,c])=>{this.nodes[i(l)]={...c,id:i(l)}});let a=e.edges.map(l=>({...l,source:i(l.source),target:i(l.target)}));this.edges=[...this.edges,...a];let s=e.firstNode(),u=e.lastNode();return[s?{id:i(s.id),data:s.data}:void 0,u?{id:i(u.id),data:u.data}:void 0]}trimFirstNode(){let e=this.firstNode();e&&tHe(this,[e.id])&&this.removeNode(e)}trimLastNode(){let e=this.lastNode();e&&rHe(this,[e.id])&&this.removeNode(e)}reid(){let e=Object.fromEntries(Object.values(this.nodes).map(o=>[o.id,o.name])),r=new Map;Object.values(e).forEach(o=>{r.set(o,(r.get(o)||0)+1)});let n=o=>{let i=e[o];return EE(o)&&r.get(i)===1?i:o};return new t({nodes:Object.fromEntries(Object.entries(this.nodes).map(([o,i])=>[n(o),{...i,id:n(o)}])),edges:this.edges.map(o=>({...o,source:n(o.source),target:n(o.target)}))})}drawMermaid(e){let{withStyles:r,curveStyle:n,nodeColors:o={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:i}=e??{},a=this.reid(),s=a.firstNode(),u=a.lastNode();return X3e(a.nodes,a.edges,{firstNode:s?.id,lastNode:u?.id,withStyles:r,curveStyle:n,nodeColors:o,wrapLabelNWords:i})}async drawMermaidPng(e){let r=this.drawMermaid(e);return Q3e(r,{backgroundColor:e?.backgroundColor})}}});function oHe(t){let e=new TextEncoder,r=new ReadableStream({async start(n){for await(let o of t)n.enqueue(e.encode(`event: data
`)),n.close()}});return Nd.fromReadableStream(r)}var iHe=w(()=>{Wb()});function ahe(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}function DG(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function*she(t,e){for(;;){let{value:r,done:n}=jd.runWithConfig(bm(t),e.next.bind(e),!0);if(n)break;yield r}}async function*LG(t,e){let r=e[Symbol.asyncIterator]();for(;;){let{value:n,done:o}=await jd.runWithConfig(bm(t),r.next.bind(e),!0);if(o)break;yield n}}var aHe,sHe=w(()=>{ZL();Hb();aHe=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function"});function xl(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function Oar(t){if(oG(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn'thappen.")}function IC(t){if(typeof t=="function")return new Nf({func:t});if(Cn.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){let e={};for(let[r,n]of Object.entries(t))e[r]=IC(n);return new kE({steps:e})}else throw new Error(`Expected a Runnable, function or object.
Instead got an unsupported type.`)}function Par(t,e){let r=e.name??t.getName(),n=e.description??e.schema?.description;return e.schema.constructor===Wr.ZodString?new H2({name:r,description:n,schema:Wr.object({input:Wr.string()}).transform(o=>o.input),bound:t}):new H2({name:r,description:n,schema:e.schema,bound:t})}var uhe,Cn,MC,FG,kG,bi,kE,lhe,Nf,$G,eF,BG,H2,Df=w(()=>{Td();uhe=F(EK(),1);TE();Ype();h3e();y3e();yR();Wb();Cme();Hb();QL();_3e();Pme();ZL();nHe();iHe();sHe();mG();Cn=class extends gp{constructor(){super(...arguments),Object.defineProperty(this,"lc_runnable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}getName(e){let r=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${r}${e}`:r}bind(e){return new MC({bound:this,kwargs:e,config:{}})}map(){return new FG({bound:this})}withRetry(e){return new kG({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new MC({bound:this,config:e,kwargs:{}})}withFallbacks(e){let r=Array.isArray(e)?e:e.fallbacks;return new $G({runnable:this,fallbacks:r})}_getOptionsList(e,r=0){if(Array.isArray(e)&&e.length!==r)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${r} inputs`);if(Array.isArray(e))return e.map(un);if(r>1&&!Array.isArray(e)&&e.runId){console.warn("ProvidedrunIdwillbeusedonlyforthefirstelementofthebatch.");let n=Object.fromEntries(Object.entries(e).filter(([o])=>o!=="runId"));return Array.from({length:r},(o,i)=>un(i===0?e:n))}return Array.from({length:r},()=>un(e))}async batch(e,r,n){let o=this._getOptionsList(r??{},e.length),i=o[0]?.maxConcurrency??n?.maxConcurrency,a=new _m({maxConcurrency:i,onFailedAttempt:u=>{throw u}}),s=e.map((u,l)=>a.call(async()=>{try{return await this.invoke(u,o[l])}catch(c){if(n?.returnExceptions)return c;throw c}}));return Promise.all(s)}async*_streamIterator(e,r){yield this.invoke(e,r)}async stream(e,r){let n=un(r),o=new AC({generator:this._streamIterator(e,n),config:n});return await o.setup,Nd.fromAsyncGenerator(o)}_separateRunnableConfigFromCallOptions(e){let r;e===void 0?r=un(e):r=un({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});let n={...e};return delete n.callbacks,delete n.tags,delete n.metadata,delete n.runName,delete n.configurable,delete n.recursionLimit,delete n.maxConcurrency,delete n.runId,delete n.timeout,delete n.signal,[r,n]}async _callWithConfig(e,r,n){let o=un(n),a=await(await _p(o))?.handleChainStart(this.toJSON(),xl(r,"input"),o.runId,o?.runType,void 0,void 0,o?.runName??this.getName());delete o.runId;let s;try{let u=e.call(this,r,o,a);s=await Vb(u,n?.signal)}catch(u){throw await a?.handleChainError(u),u}return await a?.handleChainEnd(xl(s,"output")),s}async _batchWithConfig(e,r,n,o){let i=this._getOptionsList(n??{},r.length),a=await Promise.all(i.map(_p)),s=await Promise.all(a.map(async(l,c)=>{let d=await l?.handleChainStart(this.toJSON(),xl(r[c],"input"),i[c].runId,i[c].runType,void 0,void 0,i[c].runName??this.getName());return delete i[c].runId,d})),u;try{let l=e.call(this,r,i,s,o);u=await Vb(l,i?.[0]?.signal)}catch(l){throw await Promise.all(s.map(c=>c?.handleChainError(l))),l}return await Promise.all(s.map(l=>l?.handleChainEnd(xl(u,"output")))),u}async*_transformStreamWithConfig(e,r,n){let o,i=!0,a,s=!0,u=un(n),l=await _p(u);async function*c(){for await(let f of e){if(i)if(o===void 0)o=f;else try{o=Hl(o,f)}catch{o=void 0,i=!1}yield f}}let d;try{let f=await d3e(r.bind(this),c(),async()=>l?.handleChainStart(this.toJSON(),{input:""},u.runId,u.runType,void 0,void 0,u.runName??this.getName()),n?.signal,u);delete u.runId,d=f.setup;let p=d?.handlers.find(g3e),m=f.output;p!==void 0&&d!==void 0&&(m=p.tapOutputIterable(d.runId,m));let h=d?.handlers.find(m3e);h!==void 0&&d!==void 0&&(m=h.tapOutputIterable(d.runId,m));for await(
- `)}`,new Error(ce)}let oe=`${s}/$ref`,se=oa(t,Pe,r,n,o,i,a,oe,u);if(se.valid||te.push({instanceLocation:a,keyword:"$ref",keywordLocation:oe,error:"Asubschemahaderrors."},...se.errors),r==="4"||r==="7")return{valid:te.length===0,errors:te}}if(Array.isArray(m)){let Re=m.length,Pe=!1;for(let oe=0;oe<Re;oe++)if(c===m[oe]||m[oe]==="integer"&&c==="number"&&t%1===0&&t===t){Pe=!0;break}Pe||te.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m.join('", "')}".`})}else m==="integer"?(c!=="number"||t%1||t!==t)&&te.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m}".`}):m!==void 0&&c!==m&&te.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m}".`});if(h!==void 0&&(c==="object"||c==="array"?RC(t,h)||te.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):t!==h&&te.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),b!==void 0&&(c==="object"||c==="array"?b.some(Re=>RC(t,Re))||te.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`}):b.some(Re=>t===Re)||te.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`})),y!==void 0){let Re=`${s}/not`;oa(t,y,r,n,o,i,a,Re).valid&&te.push({instanceLocation:a,keyword:"not",keywordLocation:Re,error:'Instance matched "not" schema.'})}let et=[];if(S!==void 0){let Re=`${s}/anyOf`,Pe=te.length,oe=!1;for(let se=0;se<S.length;se++){let ce=S[se],Ce=Object.create(u),Je=oa(t,ce,r,n,o,p===!0?i:null,a,`${Re}/${se}`,Ce);te.push(...Je.errors),oe=oe||Je.valid,Je.valid&&et.push(Ce)}oe?te.length=Pe:te.splice(Pe,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:Re,error:"Instancedoesnotmatchanysubschemas."})}if(x!==void 0){let Re=`${s}/allOf`,Pe=te.length,oe=!0;for(let se=0;se<x.length;se++){let ce=x[se],Ce=Object.create(u),Je=oa(t,ce,r,n,o,p===!0?i:null,a,`${Re}/${se}`,Ce);te.push(...Je.errors),oe=oe&&Je.valid,Je.valid&&et.push(Ce)}oe?te.length=Pe:te.splice(Pe,0,{instanceLocation:a,keyword:"allOf",keywordLocation:Re,error:"Instancedoesnotmatcheverysubschema."})}if(O!==void 0){let Re=`${s}/oneOf`,Pe=te.length,oe=O.filter((se,ce)=>{let Ce=Object.create(u),Je=oa(t,se,r,n,o,p===!0?i:null,a,`${Re}/${ce}`,Ce);return te.push(...Je.errors),Je.valid&&et.push(Ce),Je.valid}).length;oe===1?te.length=Pe:te.splice(Pe,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:Re,error:`Instance does not match exactly one subschema (${oe} matches).`})}if((c==="object"||c==="array")&&Object.assign(u,...et),P!==void 0){let Re=`${s}/if`;if(oa(t,P,r,n,o,i,a,Re,u).valid){if(E!==void 0){let oe=oa(t,E,r,n,o,i,a,`${s}/then`,u);oe.valid||te.push({instanceLocation:a,keyword:"if",keywordLocation:Re,error:'Instance does not match "then" schema.'},...oe.errors)}}else if(A!==void 0){let oe=oa(t,A,r,n,o,i,a,`${s}/else`,u);oe.valid||te.push({instanceLocation:a,keyword:"if",keywordLocation:Re,error:'Instance does not match "else" schema.'},...oe.errors)}}if(c==="object"){if(g!==void 0)for(let se of g)se in t||te.push({instanceLocation:a,keyword:"required",keywordLocation:`${s}/required`,error:`Instance does not have required property "${se}".`});let Re=Object.keys(t);if(k!==void 0&&Re.length<k&&te.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${k} properties.`}),z!==void 0&&Re.length>z&&te.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${z} properties.`}),V!==void 0){let se=`${s}/propertyNames`;for(let ce in t){let Ce=`${a}/${wm(ce)}`,Je=oa(ce,V,r,n,o,i,Ce,se);Je.valid||te.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:se,error:`Property name "${ce}" does not
"JSONSchema" is a declarative language that allows you to annotate and validate JSON documents.
For example, the example "JSONSchema" instance {{"properties": {{"foo": {{"description": "alistoftestwords", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "alistoftestwords". The items within "foo" must be strings.
Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSONSchema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
`&&(c(),u="",l=0,r=!1);if(!h.scan(d))break;if(a=!0,g=h.scan(bsr)||"name",h.scan(hsr),g==="="?(y=h.scanUntil(PHe),h.scan(PHe),h.scanUntil(f)):g==="{"?(y=h.scanUntil(p),h.scan(ysr),h.scanUntil(f),g="&"):y=h.scanUntil(f),!h.scan(f))thrownewError("Unclosed tag at "+h.pos);if(g==">"?x=[g,y,b,h.pos,u,l,r]:x=[g,y,b,h.pos],l++,o.push(x),g==="#"||g==="^")n.push(x);elseif(g==="/"){if(O=n.pop(),!O)thrownewError('Unopened section "'+y+'" at '+b);if(O[1]!==y)thrownewError('Unclosed section "'+O[1]+'" at '+b)}elseg==="name"||g==="{"||g==="&"?s=!0:g==="="&&m(y)}if(c(),O=n.pop(),O)thrownewError('Unclosed section "'+O[1]+'" at '+h.pos);returnwsr(vsr(o))}functionvsr(t){for(vare=[],r,n,o=0,i=t.length;o<i;++o)r=t[o],r&&(r[0]==="text"&&n&&n[0]==="text"?(n[1]+=r[1],n[3]=r[3]):(e.push(r),n=r));returne}functionwsr(t){for(vare=[],r=e,n=[],o,i,a=0,s=t.length;a<s;++a)switch(o=t[a],o[0]){case"#":case"^":r.push(o),n.push(o),r=o[4]=[];break;case"/":i=n.pop(),i[5]=o[2],r=n.length>0?n[n.length-1][4]:e;break;default:r.push(o)}returne}functionY2(t){this.string=t,this.tail=t,this.pos=0}functioniF(t,e){this.view=t,this.cache={".":this.view},this.parent=e}functionLf(){this.templateCache={_cache:{},set:function(e,r){this._cache[e]=r},get:function(e){returnthis._cache[e]},clear:function(){this._cache={}}}}varasr,aF,lsr,dsr,psr,hsr,gsr,PHe,ysr,bsr,Ah,J2,WG,EHe=w(()=>{asr=Object.prototype.toString,aF=Array.isArray||function(e){returnasr.call(e)==="[object Array]"};lsr=RegExp.prototype.test;dsr=/\S/;psr={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};hsr=/\s*/,gsr=/\s+/,PHe=/\s*=/,ysr=/\s*\}/,bsr=/#|\^|\/|>|\{|&|=|!/;Y2.prototype.eos=function(){returnthis.tail===""};Y2.prototype.scan=function(e){varr=this.tail.match(e);if(!r||r.index!==0)return"";varn=r[0];returnthis.tail=this.tail.substring(n.length),this.pos+=n.length,n};Y2.prototype.scanUntil=function(e){varr=this.tail.search(e),n;switch(r){case-1:n=this.tail,this.tail="";break;case0:n="";break;default:n=this.tail.substring(0,r),this.tail=this.tail.substring(r)}returnthis.pos+=n.length,n};iF.prototype.push=function(e){returnnewiF(e,this)};iF.prototype.lookup=function(e){varr=this.cache,n;if(r.hasOwnProperty(e))n=r[e];else{for(varo=this,i,a,s,u=!1;o;){if(e.indexOf(".")>0)for(i=o.view,a=e.split("."),s=0;i!=null&&s<a.length;)s===a.length-1&&(u=OHe(i,a[s])||usr(i,a[s])),i=i[a[s++]];elsei=o.view[e],u=OHe(o.view,e);if(u){n=i;break}o=o.parent}r[e]=n}returnvhe(n)&&(n=n.call(this.view)),n};Lf.prototype.clearCache=function(){typeofthis.templateCache<"u"&&this.templateCache.clear()};Lf.prototype.parse=function(e,r){varn=this.templateCache,o=e+":"+(r||Ah.tags).join(":"),i=typeofn<"u",a=i?n.get(o):void0;returna==null&&(a=_sr(e,r),i&&n.set(o,a)),a};Lf.prototype.render=function(e,r,n,o){vari=this.getConfigTags(o),a=this.parse(e,i),s=rinstanceofiF?r:newiF(r,void0);returnthis.renderTokens(a,s,n,e,o)};Lf.prototype.renderTokens=function(e,r,n,o,i){for(vara="",s,u,l,c=0,d=e.length;c<d;++c)l=void0,s=e[c],u=s[0],u==="#"?l=this.renderSection(s,r,n,o,i):u==="^"?l=this.renderInverted(s,r,n,o,i):u===">"?l=this.renderPartial(s,r,n,i):u==="&"?l=this.unescapedValue(s,r):u==="name"?l=this.escapedValue(s,r,i):u==="text"&&(l=this.rawValue(s)),l!==void0&&(a+=l);returna};Lf.prototype.renderSection=function(e,r,n,o,i){vara=this,s="",u=r.lookup(e[1]);functionl(f){returna.render(f,r,n,i)}if(u){if(aF(u))for(varc=0,d=u.length;c<d;++c)s+=this.renderTokens(e[4],r.push(u[c]),n,o,i);elseif(typeofu=="object"||typeofu=="string"||typeofu=="number")s+=this.renderTokens(e[4],r.push(u),n,o,i);elseif(vhe(u)){if(typeofo!="string")thrownewError("Cannot use higher-order sections without the original template");u=u.call(r.view,o.slice(e[3],e[5]),l),u!=null&&(s+=u)}elses+=this.renderTokens(e[4],r,n,o,i);returns}};Lf.prototype.renderInverted=function(e,r,n,o,i){vara=r.lookup(e[1]);if(!a||aF(a)&&a.length===0)returnthis.renderTokens(e[4],r,n,o,i)};Lf.prototype.indentPartial=function(e,r,n){for(varo=r.replace(/[^ \t]/g,""),i=e.split(`
`)};Lf.prototype.renderPartial=function(e,r,n,o){if(n){vari=this.getConfigTags(o),a=vhe(n)?n(e[1]):n[e[1]];if(a!=null){vars=e[6],u=e[5],l=e[4],c=a;u==0&&l&&(c=this.indentPartial(a,l,s));vard=this.parse(c,i);returnthis.renderTokens(d,r,n,c,o)}}};Lf.prototype.unescapedValue=function(e,r){varn=r.lookup(e[1]);if(n!=null)returnn};Lf.prototype.escapedValue=function(e,r,n){varo=this.getConfigEscape(n)||Ah.escape,i=r.lookup(e[1]);if(i!=null)returntypeofi=="number"&&o===Ah.escape?String(i):o(i)};Lf.prototype.rawValue=function(e){returne[1]};Lf.prototype.getConfigTags=function(e){returnaF(e)?e:e&&typeofe=="object"?e.tags:void0};Lf.prototype.getConfigEscape=function(e){if(e&&typeofe=="object"&&!aF(e))returne.escape};Ah={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void0,escape:void0,parse:void0,render:void0,Scanner:void0,Context:void0,Writer:void0,settemplateCache(t){J2.templateCache=t},gettemplateCache(){returnJ2.templateCache}},J2=newLf;Ah.clearCache=function(){returnJ2.clearCache()};Ah.parse=function(e,r){returnJ2.parse(e,r)};Ah.render=function(e,r,n,o){if(typeofe!="string")thrownewTypeError('Invalid template! Template should be a "string" but "'+ssr(e)+'" was given as the first argument for mustache#render(template, view, partials)');returnJ2.render(e,r,n,o)};Ah.escape=msr;Ah.Scanner=Y2;Ah.Context=iF;Ah.Writer=Lf;WG=Ah});functionTHe(){WG.escape=t=>t}varZ2,Ssr,KG,xsr,Csr,whe,Osr,Sp,X2,IR,MR=w(()=>{EHe();M2();Z2=t=>{lete=t.split(""),r=[],n=(i,a)=>{for(lets=a;s<e.length;s+=1)if(i.includes(e[s]))returns;return-1},o=0;for(;o<e.length;)if(e[o]==="{"&&o+1<e.length&&e[o+1]==="{")r.push({type:"literal",text:"{"}),o+=2;elseif(e[o]==="}"&&o+1<e.length&&e[o+1]==="}")r.push({type:"literal",text:"}"}),o+=2;elseif(e[o]==="{"){leti=n("}",o);if(i<0)thrownewError("Unclosed '{' in template.");r.push({type:"variable",name:e.slice(o+1,i).join("")}),o=i+1}else{if(e[o]==="}")thrownewError("Single '}' in template.");{leti=n("{}",o),a=(i<0?e.slice(o):e.slice(o,i)).join("");r.push({type:"literal",text:a}),o=i<0?e.length:i}}returnr},Ssr=t=>t.map(e=>e[0]==="name"?{type:"variable",name:e[1].includes(".")?e[1].split(".")[0]:e[1]}:["#","&","^",">"].includes(e[0])?{type:"variable",name:e[1]}:{type:"literal",text:e[1]}),KG=t=>{THe();lete=WG.parse(t);returnSsr(e)},xsr=(t,e)=>Z2(t).reduce((r,n)=>{if(n.type==="variable"){if(n.nameine){leto=typeofe[n.name]=="string"?e[n.name]:JSON.stringify(e[n.name]);returnr+o}thrownewError(`(f-string) Missing value for input ${n.name}`)}returnr+n.text},""),Csr=(t,e)=>(THe(),WG.render(t,e)),whe={"f-string":xsr,mustache:Csr},Osr={"f-string":Z2,mustache:KG},Sp=(t,e,r)=>{try{returnwhe[e](t,r)}catch(n){throwME(n,"INVALID_PROMPT_INPUT")}},X2=(t,e)=>Osr[e](t),IR=(t,e,r)=>{if(!(einwhe)){letn=Object.keys(whe);thrownewError(`Invalid template format. Got \`${e}\`;
should be one of ${n}`)}try{letn=r.reduce((o,i)=>(o[i]="foo",o),{});Array.isArray(t)?t.forEach(o=>{if(o.type==="text")Sp(o.text,e,n);elseif(o.type==="image_url")if(typeofo.image_url=="string")Sp(o.image_url,e,n);else{leti=o.image_url.url;Sp(i,e,n)}elsethrownewError(`Invalid message template received. ${JSON.stringify(o,null,2)}`)}):Sp(t,e,n)}catch(n){thrownewError(`Invalid prompt schema: ${n.message}`)}}});varShe={};Cf(She,{PromptTemplate:()=>Dd});varDd,sF=w(()=>{G2();MR();Dd=classtextendsNC{staticlc_name(){return"PromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void0}),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:void0}),e.templateFormat==="mustache"&&e.validateTemplate===void0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){if(this.templateFormat==="mustache")thrownewError("Mustache templates cannot be validated.");letr=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),IR(this.template,this.templateFormat,r)}}_getPromptType(){return"prompt"}asyncformat(e){letr=awaitthis.mergePartialAndUserVariables(e);returnSp(this.template,this.templateFormat,r)}staticfromExamples(e,r,n,o=`
`,i=""){leta=[i,...e,r].join(o);returnnewt({inputVariables:n,template:a})}staticfromTemplate(e,r){let{templateFormat:n="f-string",...o}=r??{},i=newSet;returnX2(e,n).forEach(a=>{a.type==="variable"&&i.add(a.name)}),newt({inputVariables:[...i],templateFormat:n,template:e,...o})}asyncpartial(e){letr=this.inputVariables.filter(i=>!(iine)),n={...this.partialVariables??{},...e},o={...this,inputVariables:r,partialVariables:n};returnnewt(o)}serialize(){if(this.outputParser!==void0)thrownewError("Cannot serialize a prompt template with an output parser");return{_type:this._getPromptType(),input_variables:this.inputVariables,template:this.template,template_format:this.templateFormat}}staticasyncdeserialize(e){if(!e.template)thrownewError("Prompt template must have a template");returnnewt({inputVariables:e.input_variables,template:e.template,templateFormat:e.template_format})}}});varuF,xhe=w(()=>{K2();oF();MR();uF=classtextendsKb{staticlc_name(){return"ImagePromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","image"]}),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void0}),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:void0}),this.template=e.template,this.templateFormat=e.templateFormat??this.templateFormat,this.validateTemplate=e.validateTemplate??this.validateTemplate,this.additionalContentFields=e.additionalContentFields,this.validateTemplate){letr=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),IR([{type:"image_url",image_url:this.template}],this.templateFormat,r)}}_getPromptType(){return"prompt"}asyncpartial(e){letr=this.inputVariables.filter(i=>!(iine)),n={...this.partialVariables??{},...e},o={...this,inputVariables:r,partialVariables:n};returnnewt(o)}asyncformat(e){letr={};for(let[a,s]ofObject.entries(this.template))typeofs=="string"?r[a]=Sp(s,this.templateFormat,e):r[a]=s;letn=e.url||r.url,o=e.detail||r.detail;if(!n)thrownewError("Must provide either an image URL.");if(typeofn!="string")thrownewError("url must be a string.");leti={url:n};returno&&(i.detail=o),i}asyncformatPromptValue(e){letr=awaitthis.format(e);returnnewVG(r)}}});functionChe(t,e){letr=[];for(letnofObject.values(t))if(typeofn=="string")X2(n,e).forEach(o=>{o.type==="variable"&&r.push(o.name)});elseif(Array.isArray(n))for(letoofn)typeofo=="string"?X2(o,e).forEach(i=>{i.type==="variable"&&r.push(i.name)}):typeofo=="object"&&r.push(...Che(o,e));elsetypeofn=="object"&&n!==null&&r.push(...Che(n,e));returnArray.from(newSet(r))}functionOhe(t,e,r){letn={};for(let[o,i]ofObject.entries(t))if(typeofi=="string")n[o]=Sp(i,r,e);elseif(Array.isArray(i)){leta=[];for(letsofi)typeofs=="string"?a.push(Sp(s,r,e)):typeofs=="object"&&a.push(Ohe(s,e,r));n[o]=a}elsetypeofi=="object"&&i!==null?n[o]=Ohe(i,e,r):n[o]=i;returnn}varQ2,Phe=w(()=>{Df();MR();Q2=classextendsCn{staticlc_name(){return"DictPromptTemplate"}constructor(e){letr=e.templateFormat??"f-string",n=Che(e.template,r);super({inputVariables:n,...e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","dict"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:void0}),this.template=e.template,this.templateFormat=r,this.inputVariables=n}asyncformat(e){returnOhe(this.template,e,this.template
From:${i}`);s=[l[0]]}else s=[];i={url:i},a=new uF({template:i,inputVariables:s,templateFormat:r?.templateFormat,additionalContentFields:o})}else if(typeof i=="object"){if("url"in i){let u;r?.templateFormat==="mustache"?u=KG(i.url):u=Z2(i.url),s=u.flatMap(l=>l.type==="variable"?[l.name]:[])}else s=[];a=new uF({template:i,inputVariables:s,templateFormat:r?.templateFormat,additionalContentFields:o})}else throw new Error("Invalid image template");n.push(a)}else typeof o=="object"&&n.push(new Q2({template:o,templateFormat:r?.templateFormat}));return new this({prompt:n,additionalOptions:r})}async format(e){if(this.prompt instanceof NC){let r=await this.prompt.format(e);return this.createMessage(r)}else{let r=[];for(let n of this.prompt){let o={};if(!("inputVariables"in n))throw new Error(`Prompt${n}doesnothaveinputVariablesdefined.`);for(let i of n.inputVariables)o||(o={[i]:e[i]}),o={...o,[i]:e[i]};if(n instanceof NC){let i=await n.format(o),a;"additionalContentFields"in n&&(a=n.additionalContentFields),r.push({...a,type:"text",text:i})}else if(n instanceof uF){let i=await n.format(o),a;"additionalContentFields"in n&&(a=n.additionalContentFields),r.push({...a,type:"image_url",image_url:i})}else if(n instanceof Q2){let i=await n.format(o),a;"additionalContentFields"in n&&(a=n.additionalContentFields),r.push({...a,...i})}}return this.createMessage(r)}}async formatMessages(e){return[await this.format(e)]}},Jb=class extends r4{static _messageClass(){return Os}static lc_name(){return"HumanMessagePromptTemplate"}},Ahe=class extends r4{static _messageClass(){return gn}static lc_name(){return"AIMessagePromptTemplate"}},BE=class extends r4{static _messageClass(){return TC}static lc_name(){return"SystemMessagePromptTemplate"}};xp=class t extends t4{static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}constructor(e){if(super(e),Object.defineProperty(this,"promptMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),e.templateFormat==="mustache"&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){let r=new Set;for(let s of this.promptMessages)if(!(s instanceof Sl))for(let u of s.inputVariables)r.add(u);let n=this.inputVariables,o=new Set(this.partialVariables?n.concat(Object.keys(this.partialVariables)):n),i=new Set([...o].filter(s=>!r.has(s)));if(i.size>0)throw new Error(`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(e,r){if(typeofe.content=="string")returne;letn=awaitPromise.all(e.content.map(asynco=>{if(o.type!=="image_url")returno;leti="";typeofo.image_url=="string"?i=o.image_url:i=o.image_url.url;lets=awaitDd.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}));returne.content=n,e}asyncformatMessages(e){letr=awaitthis.mergePartialAndUserVariables(e),n=[];for(letoofthis.promptMessages)if(oinstanceofSl)n.push(awaitthis._parseImagePrompts(o,r));else{leti=o.inputVariables.reduce((s,u)=>{if(!(uinr)&&!(Isr(o)&&o.optional))throwME(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(e){letr=this.inputVariables.filter(i=>!(iine)),n={...this.partialVariables??{},...e},o={...this,inputVariables:r,partialVariables:n};returnnewt(o)}staticfromTemplate(e,r){letn=Dd.fromTemplate(e,r),o=newJb({prompt:n});returnthis.fromMessages([o])}staticfromMessages(e,r){letn=e.reduce((a,s)=>a.concat(sinstanceoft?s.promptMessages:[Asr(s,r)]),[]
`}),Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.assign(this,e),this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),IR(this.prefix+this.suffix,this.templateFormat,r)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(e){let r=this.inputVariables.filter(i=>!(i in e)),n={...this.partialVariables??{},...e},o={...this,inputVariables:r,partialVariables:n};return new t(o)}async format(e){let r=await this.mergePartialAndUserVariables(e),n=await this.getExamples(r),o=await Promise.all(n.map(a=>this.examplePrompt.format(a))),i=[this.prefix,...o,this.suffix].join(this.exampleSeparator);return Sp(i,this.templateFormat,r)}serialize(){if(this.exampleSelector||!this.examples)throw new Error("Serializing an example selector is not currently supported");if(this.outputParser!==void 0)throw new Error("Serializing an output parser is not currently supported");return{_type:this._getPromptType(),input_variables:this.inputVariables,example_prompt:this.examplePrompt.serialize(),example_separator:this.exampleSeparator,suffix:this.suffix,prefix:this.prefix,template_format:this.templateFormat,examples:this.examples}}static async deserialize(e){let{example_prompt:r}=e;if(!r)throw new Error("Missing example prompt");let n=await Dd.deserialize(r),o;if(Array.isArray(e.examples))o=e.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new t({inputVariables:e.input_variables,examplePrompt:n,examples:o,exampleSeparator:e.example_separator,prefix:e.prefix,suffix:e.suffix,templateFormat:e.template_format})}},Mhe=class t extends t4{_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"examples",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleSelector",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"examplePrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"suffix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"exampleSeparator",{enumerable:!0,configurable:!0,writable:!0,value:`
`,this.exampleSelector=e.exampleSelector,this.prefix=e.prefix??"",this.suffix=e.suffix??"",this.templateFormat=e.templateFormat??"f-string",this.validateTemplate=e.validateTemplate??!0,this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),IR(this.prefix+this.suffix,this.templateFormat,r)}}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(e){let r=await this.mergePartialAndUserVariables(e),n=await this.getExamples(r);n=n.map(i=>{let a={};return this.examplePrompt.inputVariables.forEach(s=>{a[s]=i[s]}),a});let o=[];for(let i of n){let a=await this.examplePrompt.formatMessages(i);o.push(...a)}return o}async format(e){let r=await this.mergePartialAndUserVariables(e),n=await this.getExamples(r),i=(await Promise.all(n.map(s=>this.examplePrompt.formatMessages(s)))).flat().map(s=>s.content),a=[this.prefix,...i,this.suffix].join(this.exampleSeparator);return Sp(a,this.templateFormat,r)}async partial(e){let r=this.inputVariables.filter(i=>!(i in e)),n={...this.partialVariables??{},...e},o={...this,inputVariables:r,partialVariables:n};return new t(o)}}});var Kb,oF=w(()=>{Df();Kb=class extends Cn{get lc_attributes(){return{partialVariables:void 0}}constructor(e){super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts",this._getPromptType()]}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputParser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"partialVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let{inputVariables:r}=e;if(r.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,e)}async mergePartialAndUserVariables(e){let r=this.partialVariables??{},n={};for(let[i,a]of Object.entries(r))typeof a=="string"?n[i]=a:n[i]=await a();return{...n,...e}}async invoke(e,r){let n={...this.metadata,...r?.metadata},o=[...this.tags??[],...r?.tags??[]];return this._callWithConfig(i=>this.formatPromptValue(i),e,{...r,tags:o,metadata:n,runType:"prompt"})}serialize(){throw new Error("Use .toJSON() instead")}static async deserialize(e){switch(e._type){case"prompt":{let{PromptTemplate:r}=await Promise.resolve().then(()=>(sF(),She));return r.deserialize(e)}case void 0:{let{PromptTemplate:r}=await Promise.resolve().then(()=>(sF(),She));return r.deserialize({...e,_type:"prompt"})}case"few_shot":{let{FewShotPromptTemplate:r}=await Promise.resolve().then(()=>(Rhe(),AHe));return r.deserialize(e)}default:throw new Error(`Invalidprompttypeinconfig:${e._type}`)}}}});var IHe=w(()=>{oF();n4()});var MHe=w(()=>{});var RHe=w(()=>{n4()});var jHe=w(()=>{oF();n4();Rhe();IHe();sF();MHe();G2();MR();xhe();RHe();Phe()});var qE=w(()=>{jHe()});var Sm=w(()=>{dhe()});var jhe,Nhe=w(()=>{jhe=t=>t.map(e=>e.pageContent).join(`
4.Iftheusermentions"@vault",itmeanstheuserwantsyoutosearchtheObsidianvaultforinformationrelevanttothequery.Thesearchresultswillbeprovidedtoyouinthecontextalongwiththeuserquery,readitcarefullyandanswerthequestionbasedontheinformationprovided.Ifthere's no relevant information in the vault, just say so.
5. If the user mentions any other tool with the @ symbol, check the context for their results. If nothing is found, just ignore the @ symbol in the query.
6. Always use $'sinsteadof\\[etc.forLaTeXequations.
13. If the user mentions "tags", it most likely means tags in Obsidian note properties.`,lVe=`Return the new note content or canvas JSON in a special JSON format.
2. Click 'Refresh Index for Vault' and wait for indexing to complete. If you encounter the rate limiting error, please turn your request per second down in QA setting.`,OVe=6e3,ige=.4,PVe=.4,age=15,sge=448e3,t_={DEFAULT:"",READING_FILES:"Reading files",SEARCHING_WEB:"Searching the web",READING_FILE_TREE:"Reading file tree"},FC={SETTINGS:"settings",EXPIRED_MODAL:"expired_modal",CHAT_MODE_SELECT:"chat_mode_select",MODE_SELECT_TOOLTIP:"mode_select_tooltip"},jh={MAX_TOKENS:6e3,TEMPERATURE:.1},LC=(m=>(m.OPENAI="openai",m.OPENAI_FORMAT="3rd party (openai-format)",m.AZURE_OPENAI="azure openai",m.ANTHROPIC="anthropic",m.COHEREAI="cohereai",m.GOOGLE="google",m.XAI="xai",m.OPENROUTERAI="openrouterai",m.GROQ="groq",m.OLLAMA="ollama",m.LM_STUDIO="lm-studio",m.COPILOT_PLUS="copilot-plus",m.MISTRAL="mistralai",m.DEEPSEEK="deepseek",m))(LC||{}),WE={reasoning:"This model supports general reasoning tasks.",vision:"This model supports image inputs.",websearch:"This model can access the internet."},Zb=[{name:"copilot-plus-flash",provider:"copilot-plus",enabled:!0,isBuiltIn:!0,core:!0,plusExclusive:!0,projectEnabled:!1,capabilities:["vision"]},{name:"google/gemini-2.5-flash-lite-preview-06-17",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"google/gemini-2.5-flash",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"google/gemini-2.5-pro",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-4.1",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-4.1-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-4.1-nano",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"o4-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["reasoning"]},{name:"claude-sonnet-4-20250514",provider:"anthropic",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"claude-3-7-sonnet-latest",provider:"anthropic",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"claude-3-5-sonnet-latest",provider:"anthropic",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"claude-3-5-haiku-latest",provider:"anthropic",enabled:!0,isBuiltIn:!0},{name:"grok-3-beta",provider:"xai",enabled:!0,isBuiltIn:!0},{name:"grok-3-mini-beta",provider:"xai",enabled:!0,isBuiltIn:!0},{name:"gemini-2.5-flash",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gemini-2.5-pro",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"command-r",provider:"cohereai",enabled:!0,isBuiltIn:!0},{name:"command-r-plus",provider:"cohereai",enabled:!0,isBuiltIn:!0},{name:"azure-openai",provider:"azure openai",enabled:!0,isBuiltIn:!0},{name:"deepseek-chat",provider:"deepseek",enabled:!0,isBuiltIn:!0},{name:"deepseek-reasoner",provider:"deepseek",enabled:!0,isBuiltIn:!0,capabilities:["reasoning"]}],HE=(l=>(l.OPENAI="openai",l.COHEREAI="cohereai",l.GOOGLE="google",l.AZURE_OPENAI="azure openai",l.OLLAMA="ollama",l.LM_STUDIO="lm-studio",l.OPENAI_FORMAT="3rd party (openai-format)",l.COPILOT_PLUS="copilot-plus",l.COPILOT_PLUS_JINA="copilot-plus-jina",l))(HE||{}),jR=[{name:"copilot-plus-small",provider:"copilot-plus",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,plusExclusive:!0},{name:"copilot-plus-large",provider:"copilot-plus-jina",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,plusExclusive:!0,believerExclusive:!0,dimensions:1024},{name:"copilot-plus-multilingual",provider:"copilot-plus-jina",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,plusExclusive:!0,dimensions:512},{name:"text-embedding-3-small",provider:"openai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0},{name:"text-embedding-3-large",provider:"openai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"embed-multilingual-light-v3.0",provider:"cohereai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{n
If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body`);returno.stream()};returnObject.assign(t,{transformToByteArray:r,transformToString:asynco=>{leti=awaitr();if(o==="base64")returnjT(i);if(o==="hex")returnfat(i);if(o===void0||o==="utf8"||o==="utf-8")returnPZ(i);if(typeofTextDecoder=="function")returnnewTextDecoder(o).decode(i);thrownewError("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(e)thrownewError(mat);if(e=!0,hat(t))returnn(t);if(Cve(t))returnt;thrownewError(`Cannot transform payload to web stream, got ${t}`)}})},hat=t=>typeofBlob=="function"&&tinstanceofBlob});varbat=w(()=>{});var_at=w(()=>{});varPve=w(()=>{wve();Kit();yat();bat();_at();Ove()});varDT,vat=w(()=>{Pve();DT=async(t=newUint8Array,e)=>{if(tinstanceofUint8Array)returndO.mutate(t);if(!t)returndO.mutate(newUint8Array);letr=e.streamCollector(t);returndO.mutate(awaitr)}});varOt,Eve,wat=w(()=>{mve();Hs();Ot=class{constructor(){this.middlewareStack=yk()}staticclassBuilder(){returnnewEve}resolveMiddlewareWithContext(e,r,n,{middlewareFn:o,clientName:i,commandName:a,inputFilterSensitiveLog:s,outputFilterSensitiveLog:u,smithyContext:l,additionalContext:c,CommandCtor:d}){for(letbofo.bind(this)(d,e,r,n))this.middlewareStack.use(b);letf=e.concat(this.middlewareStack),{logger:p}=r,m={logger:p,clientName:i,commandName:a,inputFilterSensitiveLog:s,outputFilterSensitiveLog:u,[dk]:{commandInstance:this,...l},...c},{requestHandler:h}=r;returnf.resolve(b=>h.handle(b.request,n||{}),m)}},Eve=class{constructor(){this._init=()=>{},this._ep={},this._middlewareFn=()=>[],this._commandName="",this._clientName="",this._additionalContext={},this._smithyContext={},this._inputFilterSensitiveLog=e=>e,this._outputFilterSensitiveLog=e=>e,this._serializer=null,this._deserializer=null}init(e){this._init=e}ep(e){returnthis._ep=e,this}m(e){returnthis._middlewareFn=e,this}s(e,r,n={}){returnthis._smithyContext={service:e,operation:r,...n},this}c(e={}){returnthis._additionalContext=e,this}n(e,r){returnthis._clientName=e,this._commandName=r,this}f(e=n=>n,r=n=>n){returnthis._inputFilterSensitiveLog=e,this._outputFilterSensitiveLog=r,this}ser(e){returnthis._serializer=e,this}de(e){returnthis._deserializer=e,this}build(){lete=this,r;returnr=classextendsOt{staticgetEndpointParameterInstructions(){returne._ep}constructor(...[n]){super(),this.serialize=e._serializer,this.deserialize=e._deserializer,this.input=n??{},e._init(this)}resolveMiddleware(n,o,i){returnthis.resolveMiddlewareWithContext(n,o,i,{CommandCtor:r,middlewareFn:e._middlewareFn,clientName:e._clientName,commandName:e._commandName,inputFilterSensitiveLog:e._inputFilterSensitiveLog,outputFilterSensitiveLog:e._outputFilterSensitiveLog,smithyContext:e._smithyContext,additionalContext:e._additionalContext})}}}}});varTZ,Sat=w(()=>{TZ="***SensitiveInformation***"});varAZ,xat=w(()=>{AZ=(t,e)=>{for(letrofObject.keys(t)){letn=t[r],o=asyncfunction(a,s,u){letl=newn(a);if(typeofs=="function")this.send(l,s);elseif(typeofu=="function"){if(typeofs!="object")thrownewError(`Expected http options but got ${typeofs}`);this.send(l,s||{},u)}elsereturnthis.send(l,s)},i=(r[0].toLowerCase()+r.slice(1)).replace(/Command$/,"");e.prototype[i]=o}}});varj1,Umr,Cat,zmr,Oat,Pat,Eat,Tve,Hmr,vk,ln,Tat,Aat,Vmr,Y3,Z3,Ave,Iat,Mat,Rat,Ive=w(()=>{j1=t=>{if(t!=null){if(typeoft=="string"){lete=parseFloat(t);if(!Number.isNaN(e))returnString(e)!==String(t)&&Rat.warn(Mat(`Expected number but observed string: ${t}`)),e}if(typeoft=="number")returnt;thrownewTypeError(`Expected number, got ${typeoft}: ${t}`)}},Umr=Math.ceil(34028234663852886e22),Cat=t=>{lete=j1(t);if(e!==void0&&!Number.isNaN(e)&&e!==1/0&&e!==-1/0&&Math.abs(e)>Umr)thrownewTypeError(`Expected 32-bit float, got ${t}`);returne},zmr=t=>{if(t!=null){if(Number.isInteger(t)&&!Number.isNaN(t))returnt;thrownewTypeError(`Expected integer, got ${typeoft}: ${t}`)}},Oat=t=>Tve(t,32),Pat=t=>Tve(t,16),E
`),Rat={warn:console.warn}});var Wmr,Kmr,jat,Gmr,Nat,vro,wro,Sro,IZ,Dat,xro,Jmr,Ymr,Zmr,N1,Xmr,Qmr,Mve,Lat=w(()=>{Ive();Wmr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Kmr=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),jat=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=Kmr.exec(t);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");let[r,n,o,i,a,s,u,l]=e,c=Ave(Mve(n)),d=N1(o,"month",1,12),f=N1(i,"day",1,31);return Dat(c,d,f,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l})},Gmr=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),Nat=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=Gmr.exec(t);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");let[r,n,o,i,a,s,u,l,c]=e,d=Ave(Mve(n)),f=N1(o,"month",1,12),p=N1(i,"day",1,31),m=Dat(d,f,p,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l});return c.toUpperCase()!="Z"&&m.setTime(m.getTime()-Qmr(c)),m},vro=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),wro=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),Sro=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/),IZ=t=>{if(t==null)return;let e;if(typeof t=="number")e=t;else if(typeof t=="string")e=Tat(t);else if(typeof t=="object"&&t.tag===1)e=t.value;else throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(e)||e===1/0||e===-1/0)throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(e*1e3))},Dat=(t,e,r,n)=>{let o=e-1;return Ymr(t,o,r),new Date(Date.UTC(t,o,r,N1(n.hours,"hour",0,23),N1(n.minutes,"minute",0,59),N1(n.seconds,"seconds",0,60),Xmr(n.fractionalMilliseconds)))},xro=50*365*24*60*60*1e3,Jmr=[31,28,31,30,31,30,31,31,30,31,30,31],Ymr=(t,e,r)=>{let n=Jmr[e];if(e===1&&Zmr(t)&&(n=29),r>n)throw new TypeError(`Invaliddayfor${Wmr[e]}in${t}:${r}`)},Zmr=t=>t%4===0&&(t%100!==0||t%400===0),N1=(t,e,r,n)=>{let o=Iat(Mve(t));if(o<r||o>n)throw new TypeError(`${e}mustbebetween${r}and${n},inclusive`);return o},Xmr=t=>t==null?0:Aat("0."+t)*1e3,Qmr=t=>{let e=t[0],r=1;if(e=="+")r=1;else if(e=="-")r=-1;else throw new TypeError(`Offsetdirection,${e},mustbe"+"or"-"`);let n=Number(t.substring(1,3)),o=Number(t.substring(4,6));return r*(n*60+o)*60*1e3},Mve=t=>{let e=0;for(;e<t.length-1&&t.charAt(e)==="0";)e++;return e===0?t:t.slice(e)}});var wk,qa,Rve=w(()=>{wk=class t extends Error{constructor(e){super(e.message),Object.setPrototypeOf(this,t.prototype),this.name=e.name,this.$fault=e.$fault,this.$metadata=e.$metadata}},qa=(t,e={})=>{Object.entries(e).filter(([,n])=>n!==void 0).forEach(([n,o])=>{(t[n]==null||t[n]==="")&&(t[n]=o)});let r=t.message||t.Message||"UnknownError";return t.message=r,delete t.Message,t}});var ehr,MZ,thr,Fat=w(()=>{Rve();ehr=({output:t,parsedBody:e,exceptionCtor:r,errorCode:n})=>{let o=thr(t),i=o.httpStatusCode?o.httpStatusCode+"":void 0,a=new r({name:e?.code||e?.Code||n||i||"UnknownError",$fault:"client",$metadata:o});throw qa(a,e)},MZ=t=>({output:e,parsedBody:r,errorCode:n})=>{ehr({output:e,parsedBody:r,exceptionCtor:t,errorCode:n})},thr=t=>({httpStatusCode:t.statusCode,requestId:t.headers["x-amzn-requestid"]??t.headers["x-amzn-request-id"]??t.headers["x-amz-request-id"],extendedRequestId:t.headers["x-amz-id-2"],cfId:t.headers["x-amz-cf-id"]})});var RZ,kat=w(()=>{RZ=t=>{switch(t){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":retu
${Dy(i)}`}getCanonicalPath({path:e}){if(this.uriEscapePath){letr=[];for(letiofe.split("/"))i?.length!==0&&i!=="."&&(i===".."?r.pop():r.push(i));letn=`${e?.startsWith("/")?"/":""}${r.join("/")}${r.length>0&&e?.endsWith("/")?"/":""}`;returnYh(n).replace(/%2F/g,"/")}returne}asyncgetSignature(e,r,n,o){leti=awaitthis.createStringToSign(e,r,o),a=newthis.sha256(awaitn);returna.update(kT(i)),Dy(awaita.digest())}getSigningKey(e,r,n,o){returnhut(this.sha256,e,n,r,o||this.service)}validateResolvedCredentials(e){if(typeofe!="object"||typeofe.accessKeyId!="string"||typeofe.secretAccessKey!="string")thrownewError("Resolved credential object is not valid")}},JZ=t=>{lete=xut(t).replace(/[\-:]/g,"");return{longDate:e,shortDate:e.slice(0,8)}},Out=t=>Object.keys(t).sort().join(";")});varEut=w(()=>{Put();Qve();twe();rwe();iwe();awe();Xve()});varYZ,Tut=w(()=>{LT();Eut();YZ=t=>{lete;t.credentials&&(e=pst(t.credentials,fst,Fve)),e||(t.credentialDefaultProvider?e=Ck(t.credentialDefaultProvider(Object.assign({},t,{parentClientConfig:t}))):e=async()=>{thrownewError("`credentials` is missing")});let{signingEscapePath:r=!0,systemClockOffset:n=t.systemClockOffset||0,sha256:o}=t,i;returnt.signer?i=Ck(t.signer):t.regionInfoProvider?i=()=>Ck(t.region)().then(asynca=>[awaitt.regionInfoProvider(a,{useFipsEndpoint:awaitt.useFipsEndpoint(),useDualstackEndpoint:awaitt.useDualstackEndpoint()})||{},a]).then(([a,s])=>{let{signingRegion:u,signingService:l}=a;t.signingRegion=t.signingRegion||u||s,t.signingName=t.signingName||l||t.serviceId;letc={...t,credentials:e,region:t.signingRegion,service:t.signingName,sha256:o,uriEscapePath:r},d=t.signerConstructor||aH;returnnewd(c)}):i=asynca=>{a=Object.assign({},{name:"sigv4",signingName:t.signingName||t.defaultSigningName,signingRegion:awaitCk(t.region)(),properties:{}},a);lets=a.signingRegion,u=a.signingName;t.signingRegion=t.signingRegion||s,t.signingName=t.signingName||u||t.serviceId;letl={...t,credentials:e,region:t.signingRegion,service:t.signingName,sha256:o,uriEscapePath:r},c=t.signerConstructor||aH;returnnewc(l)},{...t,systemClockOffset:n,signingEscapePath:r,credentials:e,signer:i}}});varAut=w(()=>{Gst();Jst();Tut()});varIut=w(()=>{Aut()});varMut=w(()=>{});varRut=w(()=>{ar()});varZZ,swe=w(()=>{ar();ZZ=(t,e)=>DT(t,e).then(r=>e.utf8Encoder(r))});varIs,jut,Nut,Dut=w(()=>{swe();Is=(t,e)=>ZZ(t,e).then(r=>{if(r.length)try{returnJSON.parse(r)}catch(n){thrown?.name==="SyntaxError"&&Object.defineProperty(n,"$responseBodyText",{value:r}),n}return{}}),jut=async(t,e)=>{letr=awaitIs(t,e);returnr.message=r.message??r.Message,r},Nut=(t,e)=>{letr=(i,a)=>Object.keys(i).find(s=>s.toLowerCase()===a.toLowerCase()),n=i=>{leta=i;returntypeofa=="number"&&(a=a.toString()),a.indexOf(",")>=0&&(a=a.split(",")[0]),a.indexOf(":")>=0&&(a=a.split(":")[0]),a.indexOf("#")>=0&&(a=a.split("#")[1]),a},o=r(t.headers,"x-amzn-errortype");if(o!==void0)returnn(t.headers[o]);if(e.code!==void0)returnn(e.code);if(e.__type!==void0)returnn(e.__type)}});varXZ=v(fO=>{"use strict";varLut=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",whr=Lut+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",Fut="["+Lut+"]["+whr+"]*",Shr=newRegExp("^"+Fut+"$"),xhr=function(t,e){letr=[],n=e.exec(t);for(;n;){leto=[];o.startIndex=e.lastIndex-n[0].length;leti=n.length;for(leta=0;a<i;a++)o.push(n[a]);r.push(o),n=e.exec(t)}returnr},Chr=function(t){lete=Shr.exec(t);return!(e===null||typeofe>"u")};fO.isExist=function(t){returntypeoft<"u"};fO.isEmptyObject=function(t){returnObject.keys(t).length===0};fO.merge=function(t,e,r){if(e){letn=Object.keys(e),o=n.length;for(leti=0;i<o;i++)r==="strict"?t[n[i]]=[e[n[i]]]:t[n[i]]=e[n[i]]}};fO.getValue=function(t){returnfO.isExist(t)?t:""};fO.isName=Chr;fO.getAllMatches=xhr;fO.nameRegexp=Fut});varlwe=v(Uut=>{"use strict";varuwe=XZ(),Ohr={allowBooleanAttributes:!1,unpairedTags:[]};Uut.validate=function(t,e){e=Object.assign({},Ohr,e);letr=[],n=!1,
`&&t[i]!=="\r";i++)u+=t[i];if(u=u.trim(),u[u.length-1]==="/"&&(u=u.substring(0,u.length-1),i--),!jhr(u)){let d;return u.trim().length===0?d="Invalid space after '<'.":d="Tag '"+u+"' is an invalid name.",Ms("InvalidTag",d,zf(t,i))}let l=Thr(t,i);if(l===!1)return Ms("InvalidAttr","Attributes for '"+u+"' have open quote.",zf(t,i));let c=l.value;if(i=l.index,c[c.length-1]==="/"){let d=i-c.length;c=c.substring(0,c.length-1);let f=qut(c,e);if(f===!0)n=!0;else return Ms(f.err.code,f.err.msg,zf(t,d+f.err.line))}else if(s)if(l.tagClosed){if(c.trim().length>0)return Ms("InvalidTag","Closing tag '"+u+"' can't have attributes or invalid starting.",zf(t,a));if(r.length===0)return Ms("InvalidTag","Closing tag '"+u+"' has not been opened.",zf(t,a));{let d=r.pop();if(u!==d.tagName){let f=zf(t,d.tagStartPos);return Ms("InvalidTag","Expected closing tag '"+d.tagName+"' (opened in line "+f.line+", col "+f.col+") instead of closing tag '"+u+"'.",zf(t,a))}r.length==0&&(o=!0)}}else return Ms("InvalidTag","Closing tag '"+u+"' doesn't have proper closing.",zf(t,i));else{let d=qut(c,e);if(d!==!0)return Ms(d.err.code,d.err.msg,zf(t,i-c.length+d.err.line));if(o===!0)return Ms("InvalidXml","Multiple possible root nodes found.",zf(t,i));e.unpairedTags.indexOf(u)!==-1||r.push({tagName:u,tagStartPos:a}),n=!0}for(i++;i<t.length;i++)if(t[i]==="<")if(t[i+1]==="!"){i++,i=But(t,i);continue}else if(t[i+1]==="?"){if(i=$ut(t,++i),i.err)return i}else break;else if(t[i]==="&"){let d=Mhr(t,i);if(d==-1)return Ms("InvalidChar","char '&' is not expected.",zf(t,i));i=d}else if(o===!0&&!kut(t[i]))return Ms("InvalidXml","Extra text at the end",zf(t,i));t[i]==="<"&&i--}}else{if(kut(t[i]))continue;return Ms("InvalidChar","char '"+t[i]+"' is not expected.",zf(t,i))}if(n){if(r.length==1)return Ms("InvalidTag","Unclosed tag '"+r[0].tagName+"'.",zf(t,r[0].tagStartPos));if(r.length>0)return Ms("InvalidXml","Invalid '"+JSON.stringify(r.map(i=>i.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return Ms("InvalidXml","Start tag expected.",1);return!0};function kut(t){return t===" "||t===" "||t===`
`||t==="\r"}function $ut(t,e){let r=e;for(;e<t.length;e++)if(t[e]=="?"||t[e]==" "){let n=t.substr(r,e-r);if(e>5&&n==="xml")return Ms("InvalidXml","XML declaration allowed only at the start of the document.",zf(t,e));if(t[e]=="?"&&t[e+1]==">"){e++;break}else continue}return e}function But(t,e){if(t.length>e+5&&t[e+1]==="-"&&t[e+2]==="-"){for(e+=3;e<t.length;e++)if(t[e]==="-"&&t[e+1]==="-"&&t[e+2]===">"){e+=2;break}}else if(t.length>e+8&&t[e+1]==="D"&&t[e+2]==="O"&&t[e+3]==="C"&&t[e+4]==="T"&&t[e+5]==="Y"&&t[e+6]==="P"&&t[e+7]==="E"){let r=1;for(e+=8;e<t.length;e++)if(t[e]==="<")r++;else if(t[e]===">"&&(r--,r===0))break}else if(t.length>e+9&&t[e+1]==="["&&t[e+2]==="C"&&t[e+3]==="D"&&t[e+4]==="A"&&t[e+5]==="T"&&t[e+6]==="A"&&t[e+7]==="["){for(e+=8;e<t.length;e++)if(t[e]==="]"&&t[e+1]==="]"&&t[e+2]===">"){e+=2;break}}return e}var Phr='"',Ehr="'";function Thr(t,e){let r="",n="",o=!1;for(;e<t.length;e++){if(t[e]===Phr||t[e]===Ehr)n===""?n=t[e]:n!==t[e]||(n="");else if(t[e]===">"&&n===""){o=!0;break}r+=t[e]}return n!==""?!1:{value:r,index:e,tagClosed:o}}var Ahr=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function qut(t,e){let r=uwe.getAllMatches(t,Ahr),n={};for(let o=0;o<r.length;o++){if(r[o][1].length===0)return Ms("InvalidAttr","Attribute '"+r[o][2]+"' has no space in starting.",sH(r[o]));if(r[o][3]!==void 0&&r[o][4]===void 0)return Ms("InvalidAttr","Attribute '"+r[o][2]+"' is without value.",sH(r[o]));if(r[o][3]===void 0&&!e.allowBooleanAttributes)return Ms("InvalidAttr","boolean attribute '"+r[o][2]+"' is not allowed.",sH(r[o]));let i=r[o][2];if(!Rhr(i))return Ms("InvalidAttr","Attribute '"+i+"' is an invalid name.",sH(r[o]));if(!n.hasOwnProperty(i))n[i]=1;else return Ms("InvalidAttr","Attribute '"+i+"' is repeated.",sH(r[o]))}return!0}function Ihr(t,e){let r=/\d/;for(t[e]==="x"&&(e++,r=/[\da-fA-F]/);e<t.length;e++){if(t[e]===";")return e;if(!t[e].match(r))break}return-1}function Mhr(t,e){if(e++,t[e]===";")return-1;if(t[e]==="#")return e++,Ihr(t,e);let r=0;for(;e<t.length;e++,r++)if(!(t[e].match(/\w/)&&r<20)){if(t[e]===";")break;return-1}return e}function Ms(t,e,r){return{err:{code:t,msg:e,line:r.line||r,col:r.col}}}function Rhr(t){return uwe.isName(t)}function jhr(t){return uwe.isName(t)}function zf(t,e){let r=t.substring(0,e).split(/\r?\n/);return{line:r.length,col:r[r.length-1].length+1}}function sH(t){return t.startIndex+t[1].length}});var Hut=v(cwe=>{var zut={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,r){return t}},Nhr=function(t){return Object.assign({},zut,t)};cwe.buildOptions=Nhr;cwe.defaultOptions=zut});var Wut=v((Kao,Vut)=>{"use strict";var dwe=class{constructor(e){this.tagname=e,this.child=[],this[":@"]={}}add(e,r){e==="__proto__"&&(e="#__proto__"),this.child.push({[e]:r})}addChild(e){e.tagname==="__proto__"&&(e.tagname="#__proto__"),e[":@"]&&Object.keys(e[":@"]).length>0?this.child.push({[e.tagname]:e.child,":@":e[":@"]}):this.child.push({[e.tagname]:e.child})}};Vut.exports=dwe});var Gut=v((Gao,Kut)=>{var Dhr=XZ();function Lhr(t,e){let r={};if(t[e+3]==="O"&&t[e+4]==="C"&&t[e+5]==="T"&&t[e+6]==="Y"&&t[e+7]==="P"&&t[e+8]==="E"){e=e+9;let n=1,o=!1,i=!1,a="";for(;e<t.length;e++)if(t[e]==="<"&&!i){if(o&&$hr(t,e))e+=7,[entityName,val,e]=Fhr(t,e+1),val.indexOf("&")===-1&&(r[zhr(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(o&&Bhr(t,e))e+=8;else if(o&&qhr(t,e))e+=8;else if(o&&Uhr(t,e))e+=9;else if(khr)i=!0;else throw new Error("Invalid DOCTYPE");n++,a=""}else if(t[e]===">"){if(i?t[e-1]==="-"&&t[e-2]==="-"&&(i=!1,n--):n--,n===0)brea
`);let e=new uH("!xml"),r=e,n="",o="";for(let i=0;i<t.length;i++)if(t[i]==="<")if(t[i+1]==="/"){let s=F1(t,">",i,"Closing Tag is not closed."),u=t.substring(i+2,s).trim();if(this.options.removeNSPrefix){let d=u.indexOf(":");d!==-1&&(u=u.substr(d+1))}this.options.transformTagName&&(u=this.options.transformTagName(u)),r&&(n=this.saveTextToParentTag(n,r,o));let l=o.substring(o.lastIndexOf(".")+1);if(u&&this.options.unpairedTags.indexOf(u)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${u}>`);let c=0;l&&this.options.unpairedTags.indexOf(l)!==-1?(c=o.lastIndexOf(".",o.lastIndexOf(".")-1),this.tagsNodeStack.pop()):c=o.lastIndexOf("."),o=o.substring(0,c),r=this.tagsNodeStack.pop(),n="",i=s}else if(t[i+1]==="?"){let s=pwe(t,i,!1,"?>");if(!s)throw new Error("Pi Tag is not closed.");if(n=this.saveTextToParentTag(n,r,o),!(this.options.ignoreDeclaration&&s.tagName==="?xml"||this.options.ignorePiTags)){let u=new uH(s.tagName);u.add(this.options.textNodeName,""),s.tagName!==s.tagExp&&s.attrExpPresent&&(u[":@"]=this.buildAttributesMap(s.tagExp,o,s.tagName)),this.addChild(r,u,o)}i=s.closeIndex+1}else if(t.substr(i+1,3)==="!--"){let s=F1(t,"-->",i+4,"Comment is not closed.");if(this.options.commentPropName){let u=t.substring(i+4,s-2);n=this.saveTextToParentTag(n,r,o),r.add(this.options.commentPropName,[{[this.options.textNodeName]:u}])}i=s}else if(t.substr(i+1,2)==="!D"){let s=Jhr(t,i);this.docTypeEntities=s.entities,i=s.i}else if(t.substr(i+1,2)==="!["){let s=F1(t,"]]>",i,"CDATA is not closed.")-2,u=t.substring(i+9,s);n=this.saveTextToParentTag(n,r,o);let l=this.parseTextData(u,r.tagname,o,!0,!1,!0,!0);l==null&&(l=""),this.options.cdataPropName?r.add(this.options.cdataPropName,[{[this.options.textNodeName]:u}]):r.add(this.options.textNodeName,l),i=s+2}else{let s=pwe(t,i,this.options.removeNSPrefix),u=s.tagName,l=s.rawTagName,c=s.tagExp,d=s.attrExpPresent,f=s.closeIndex;this.options.transformTagName&&(u=this.options.transformTagName(u)),r&&n&&r.tagname!=="!xml"&&(n=this.saveTextToParentTag(n,r,o,!1));let p=r;if(p&&this.options.unpairedTags.indexOf(p.tagname)!==-1&&(r=this.tagsNodeStack.pop(),o=o.substring(0,o.lastIndexOf("."))),u!==e.tagname&&(o+=o?"."+u:u),this.isItStopNode(this.options.stopNodes,o,u)){let m="";if(c.length>0&&c.lastIndexOf("/")===c.length-1)u[u.length-1]==="/"?(u=u.substr(0,u.length-1),o=o.substr(0,o.length-1),c=u):c=c.substr(0,c.length-1),i=s.closeIndex;else if(this.options.unpairedTags.indexOf(u)!==-1)i=s.closeIndex;else{let b=this.readStopNodeData(t,l,f+1);if(!b)throw new Error(`Unexpected end of ${l}`);i=b.i,m=b.tagContent}let h=new uH(u);u!==c&&d&&(h[":@"]=this.buildAttributesMap(c,o,u)),m&&(m=this.parseTextData(m,u,o,!0,d,!0,!0)),o=o.substr(0,o.lastIndexOf(".")),h.add(this.options.textNodeName,m),this.addChild(r,h,o)}else{if(c.length>0&&c.lastIndexOf("/")===c.length-1){u[u.length-1]==="/"?(u=u.substr(0,u.length-1),o=o.substr(0,o.length-1),c=u):c=c.substr(0,c.length-1),this.options.transformTagName&&(u=this.options.transformTagName(u));let m=new uH(u);u!==c&&d&&(m[":@"]=this.buildAttributesMap(c,o,u)),this.addChild(r,m,o),o=o.substr(0,o.lastIndexOf("."))}else{let m=new uH(u);this.tagsNodeStack.push(r),u!==c&&d&&(m[":@"]=this.buildAttributesMap(c,o,u)),this.addChild(r,m,o),r=m}n="",i=f}}else n+=t[i];return e.child};function ngr(t,e,r){let n=this.options.updateTag(e.tagname,r,e[":@"]);n===!1||(typeof n=="string"&&(e.tagname=n),t.addChild(e))}var ogr=function(t){if(this.options.processEntities){for(let e in this.docTypeEntities){let r=this.docTypeEntities[e];t=t.replace(r.regx,r.val)}for(let e in this.lastEntities){let r=this.lastEntities[e];t=t.replace(r.regex,r.val)}if(this.options.htmlEntities)for(let e in this.htmlEntities){let r=this.htmlEntities[e];t=t.replace(r.regex,r.val)}t=t.replace(this.ampEntity.regex,this.ampEntity.val)}return t};function igr(t,e,r,n){return t&&(n===void 0&&(n=Object.keys(e.child).length===0),t=this.parseTextData(t,e.tagname,r,!1,e[":@"]?Object.keys(e[":@"]).length!==0:!1,n),t!==void 0&&t!==""&&e.add(this.options.textNodeName,t),t=""),t}function agr(t,e,r){let n="*
`;super(r),this.name="AggregateError",this.errors=e}};rxe.exports={AggregateError:txe,kEmptyObject:Object.freeze({}),once(t){let e=!1;return function(...r){e||(e=!0,t.apply(this,r))}},createDeferredPromise:function(){let t,e;return{promise:new Promise((n,o)=>{t=n,e=o}),resolve:t,reject:e}},promisify(t){return new Promise((e,r)=>{t((n,...o)=>n?r(n):e(...o))})},debuglog(){return function(){}},format(t,...e){return t.replace(/%([sdifj])/g,function(...[r,n]){let o=e.shift();return n==="f"?o.toFixed(6):n==="j"?JSON.stringify(o):n==="s"&&typeof o=="object"?`${o.constructor!==Object?o.constructor.name:""} {}`.trim():o.toString()})},inspect(t){switch(typeof t){case"string":if(t.includes("'"))if(t.includes('"')){if(!t.includes("`")&&!t.includes("${"))return`\`${t}\``}else return`"${t}"`;return`'${t}'`;case"number":return isNaN(t)?"NaN":Object.is(t,-0)?String(t):t;case"bigint":return`${String(t)}n`;case"boolean":case"undefined":return String(t);case"object":return"{}"}},types:{isAsyncFunction(t){return t instanceof ewr},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:twr,deprecate(t,e){return t},addAbortListener:FH().addAbortListener||function(e,r){if(e===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);Tyt(e,"signal"),rwr(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[Yvr]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[Zvr](){var o;(o=n)===null||o===void 0||o()}}},AbortSignalAny:Xvr.any||function(e){if(e.length===1)return e[0];let r=new Qvr,n=()=>r.abort();return e.forEach(o=>{Tyt(o,"signals"),o.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{e.forEach(o=>o.removeEventListener("abort",n))},{once:!0}),r.signal}};rxe.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var Kf=v((tvo,Myt)=>{"use strict";var{format:nwr,inspect:GQ,AggregateError:owr}=Gd(),iwr=globalThis.AggregateError||owr,awr=Symbol("kIsNodeError"),swr=["string","function","number","object","Function","Object","boolean","bigint","symbol"],uwr=/^([A-Z][a-z0-9]*)+$/,lwr="__node_internal_",JQ={};function Y1(t,e){if(!t)throw new JQ.ERR_INTERNAL_ASSERTION(e)}function Ayt(t){let e="",r=t.length,n=t[0]==="-"?1:0;for(;r>=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function cwr(t,e,r){if(typeof e=="function")return Y1(e.length<=r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${e.length}).`),e(...r);let n=(e.match(/%[dfijoOs]/g)||[]).length;return Y1(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:nwr(e,...r)}function qc(t,e,r){r||(r=Error);class n extends r{constructor(...i){super(cwr(t,e,i))}toString(){return`${this.name} [${t}]: ${this.message}`}}Object.defineProperties(n.prototype,{name:{value:r.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${t}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),n.prototype.code=t,n.prototype[awr]=!0,JQ[t]=n}function Iyt(t){let e=lwr+t.name;return Object.defineProperty(t,"name",{value:e}),t}function dwr(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new iwr([e,t],e.message);return r.code=e.code,r}return t||e}var nxe=class extends Error{constructor(e="The operation was aborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new JQ.ERR_INVALID_ARG_TYPE("options","Object",r);super(e,r),this.code="ABORT_ERR",this.name="AbortError"}};qc("ERR_ASSERTION","%s",Error);qc("ERR_INVALID_ARG_TYPE",(t,e,r)=>{Y1(typeof t=="string","'name' must be a string"),Array.isArray(e)||(e=[e]);let n="The ";t.endsWith(" argument")?n+=`${t} `:n+=`"${t}" ${t.includes(".")?"property":"argument"} `,n+="must be ";let o=[],i=[],a=[];for(let u of e)Y1(typeof u=="string","All expected entries have to be of type string"),swr.includes(u)?o.push(u.toLowerCase()):uwr.test(u)?i.push(u):(Y1(u!=="object",'Thevalue"object"shouldbewrittenas"Object"'),a.push(u));if(i.length>0){let
`,this.streamTerminator=n.streamTerminator):this.messageTerminator=n.messageTerminator,o?.addEventListener("abort",()=>this.controller.abort())}iterMessages(){returnlSt(this,arguments,function*(){varr,n;this.controller.signal;leto=cSt(this.stream),i="",a=!1;try{for(vars=uSt(o),u;u=yield$y(s.next()),!u.done;){letl=u.value;i+=this.decodeChunk(l);letc;for(;(c=i.indexOf(this.messageTerminator))>=0;){letd=i.slice(0,c+1);if(i=i.slice(c+1),d.length===0)continue;if(!a&&this.prefix!=null){letp=d.indexOf(this.prefix);if(p===-1)continue;a=!0,d=d.slice(p+this.prefix.length)}if(this.streamTerminator!=null&&d.includes(this.streamTerminator))returnyield$y(void0);letf=yield$y(this.parse(JSON.parse(d)));yieldyield$y(f),a=!1}}}catch(l){r={error:l}}finally{try{u&&!u.done&&(n=s.return)&&(yield$y(n.call(s)))}finally{if(r)throwr.error}}})}[Symbol.asyncIterator](){returnlSt(this,arguments,function*(){varr,n;try{for(varo=uSt(this.iterMessages()),i;i=yield$y(o.next()),!i.done;){leta=i.value;yieldyield$y(a)}}catch(a){r={error:a}}finally{try{i&&!i.done&&(n=o.return)&&(yield$y(n.call(o)))}finally{if(r)throwr.error}}})}decodeChunk(e){letr="";if(typeofTextDecoder<"u"){letn=newTextDecoder("utf8");r+=n.decode(e)}elseNTr.RUNTIME.type==="node"&&typeofe<"u"&&(r+=Buffer.isBuffer(e)?e:Buffer.from(e));returnr}};Np.Stream=eOe;functioncSt(t){if(t[Symbol.asyncIterator])returnt;lete=t.getReader();return{next(){returnsSt(this,void0,void0,function*(){try{letr=yielde.read();returnr?.done&&e.releaseLock(),r}catch(r){throwe.releaseLock(),r}})},return(){returnsSt(this,void0,void0,function*(){letr=e.cancel();returne.releaseLock(),yieldr,{done:!0,value:void0}})},[Symbol.asyncIterator](){returnthis}}}Np.readableStreamAsyncIterable=cSt});vardSt=v(Kee=>{"use strict";Object.defineProperty(Kee,"__esModule",{value:!0});Kee.Stream=void0;varLTr=tOe();Object.defineProperty(Kee,"Stream",{enumerable:!0,get:function(){returnLTr.Stream}})});varmSt=v((qwo,pSt)=>{"use strict";varrOe=Object.defineProperty,FTr=Object.getOwnPropertyDescriptor,kTr=Object.getOwnPropertyNames,$Tr=Object.prototype.hasOwnProperty,BTr=(t,e)=>{for(varrine)rOe(t,r,{get:e[r],enumerable:!0})},qTr=(t,e,r,n)=>{if(e&&typeofe=="object"||typeofe=="function")for(letoofkTr(e))!$Tr.call(t,o)&&o!==r&&rOe(t,o,{get:()=>e[o],enumerable:!(n=FTr(e,o))||n.enumerable});returnt},UTr=t=>qTr(rOe({},"__esModule",{value:!0}),t),fSt={};BTr(fSt,{Blob:()=>VTr,File:()=>WTr,FormData:()=>HTr});pSt.exports=UTr(fSt);varzTr=function(){returntypeofglobalThis<"u"?globalThis:typeofself<"u"?self:window}(),{FormData:HTr,Blob:VTr,File:WTr}=zTr});varESt=v((Uwo,PSt)=>{"use strict";variOe=Object.defineProperty,KTr=Object.getOwnPropertyDescriptor,GTr=Object.getOwnPropertyNames,JTr=Object.prototype.hasOwnProperty,YTr=(t,e)=>{for(varrine)iOe(t,r,{get:e[r],enumerable:!0})},ZTr=(t,e,r,n)=>{if(e&&typeofe=="object"||typeofe=="function")for(letoofGTr(e))!JTr.call(t,o)&&o!==r&&iOe(t,o,{get:()=>e[o],enumerable:!(n=KTr(e,o))||n.enumerable});returnt},XTr=t=>ZTr(iOe({},"__esModule",{value:!0}),t),aOe=(t,e,r)=>{if(!e.has(t))throwTypeError("Cannot "+r)},fs=(t,e,r)=>(aOe(t,e,"read from private field"),r?r.call(t):e.get(t)),Y_=(t,e,r)=>{if(e.has(t))throwTypeError("Cannot add the same private member more than once");einstanceofWeakSet?e.add(t):e.set(t,r)},uV=(t,e,r,n)=>(aOe(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),nOe=(t,e,r)=>(aOe(t,e,"access private method"),r),wSt={};YTr(wSt,{FormDataEncoder:()=>aAr,isFile:()=>pj,isFormData:()=>CSt});PSt.exports=XTr(wSt);varTO=t=>typeoft=="function",QTr=t=>TO(t[Symbol.asyncIterator]),hSt=65536;function*SSt(t){if(t.byteLength<=hSt){yieldt;return}lete=0;for(;e<t.byteLength;){letr=Math.min(t.byteLength-e,hSt),n=t.buffer.slice(e,e+r);e+=n.byteLength,yieldnewUint8Array(n)}}asyncfunction*eAr(t){lete=t.getReader();for(;;){let{done:r,value:n}=awaite.read();if(r)break;yieldn}}asyncfunction*gSt(t){forawait(leteoft)yield*SSt(e)}vartAr=t=>{if(QTr(t))returngSt(t);if(TO(t.getReader))returngSt(eAr(t));thrownewTypeError("Unsup
`),Y_(this,lV,void0),Y_(this,Jee,void0),Y_(this,cV,"-".repeat(2)),Y_(this,fj,newTextEncoder),Y_(this,dV,void0),Y_(this,fV,void0),Y_(this,Yee,void0),!CSt(t))thrownewTypeError("Expected first argument to be a FormData instance.");letn;if(bSt(e)?r=e:n=e,n||(n=rAr()),typeofn!="string")thrownewTypeError("Expected boundary argument to be a string.");if(r&&!bSt(r))thrownewTypeError("Expected options argument to be an object.");uV(this,fV,Array.from(t.entries())),uV(this,Yee,{...iAr,...r}),uV(this,lV,fs(this,fj).encode(fs(this,dA))),uV(this,Jee,fs(this,lV).byteLength),this.boundary=`form-data-boundary-${n}`,this.contentType=`multipart/form-data; boundary=${this.boundary}`,uV(this,dV,fs(this,fj).encode(`${fs(this,cV)}${this.boundary}${fs(this,cV)}${fs(this,dA).repeat(2)}`));leto={"Content-Type":this.contentType},i=nOe(this,oOe,OSt).call(this);i&&(this.contentLength=i,o["Content-Length"]=i),this.headers=oAr(Object.freeze(o)),Object.defineProperties(this,{boundary:Gee,contentType:Gee,contentLength:Gee,headers:Gee})}*values(){for(let[t,e]offs(this,fV)){letr=pj(e)?e:fs(this,fj).encode(xSt(e));yieldnOe(this,Zee,sOe).call(this,t,r),yieldr,yieldfs(this,lV)}yieldfs(this,dV)}async*encode(){for(lettofthis.values())pj(t)?yield*tAr(t.stream()):yield*SSt(t)}[Symbol.iterator](){returnthis.values()}[Symbol.asyncIterator](){returnthis.encode()}};dA=newWeakMap;lV=newWeakMap;Jee=newWeakMap;cV=newWeakMap;fj=newWeakMap;dV=newWeakMap;fV=newWeakMap;Yee=newWeakMap;Zee=newWeakSet;sOe=function(t,e){letr="";if(r+=`${fs(this,cV)}${this.boundary}${fs(this,dA)}`,r+=`Content-Disposition: form-data; name="${vSt(t)}"`,pj(e)&&(r+=`; filename="${vSt(e.name)}"${fs(this,dA)}`,r+=`Content-Type: ${e.type||"application/octet-stream"}`),fs(this,Yee).enableAdditionalHeaders===!0){letn=pj(e)?e.size:e.byteLength;n!=null&&!isNaN(n)&&(r+=`${fs(this,dA)}Content-Length: ${n}`)}returnfs(this,fj).encode(`${r}${fs(this,dA).repeat(2)}`)};oOe=newWeakSet;OSt=function(){lett=0;for(let[e,r]offs(this,fV)){letn=pj(r)?r:fs(this,fj).encode(xSt(r)),o=pj(n)?n.size:n.byteLength;if(o==null||isNaN(o))return;t+=nOe(this,Zee,sOe).call(this,e,n).byteLength,t+=o,t+=fs(this,Jee)}returnString(t+fs(this,dV).byteLength)}});varASt=v((Hwo,TSt)=>{TSt.exports=typeofself=="object"?self.FormData:window.FormData});varISt=v(Ql=>{"use strict";varsAr=Ql&&Ql.__createBinding||(Object.create?function(t,e,r,n){n===void0&&(n=r);varo=Object.getOwnPropertyDescriptor(e,r);(!o||("get"ino?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){returne[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void0&&(n=r),t[n]=e[r]}),uAr=Ql&&Ql.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),M$=Ql&&Ql.__importStar||function(t){if(t&&t.__esModule)returnt;vare={};if(t!=null)for(varrint)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&sAr(e,t,r);returnuAr(e,t),e},fA=Ql&&Ql.__awaiter||function(t,e,r,n){functiono(i){returniinstanceofr?i:newr(function(a){a(i)})}returnnew(r||(r=Promise))(function(i,a){functions(c){try{l(n.next(c))}catch(d){a(d)}}functionu(c){try{l(n.throw(c))}catch(d){a(d)}}functionl(c){c.done?i(c.value):o(c.value).then(s,u)}l((n=n.apply(t,e||[])).next())})};Object.defineProperty(Ql,"__esModule",{value:!0});Ql.WebFormData=Ql.Node16FormData=Ql.Node18FormData=Ql.newFormData=void0;varXee=v$();functionuOe(t){returntypeoft=="object"&&t!=null&&"name"int}functionlAr(){returnfA(this,void0,void0,function*(){lett;returnXee.RUNTIME.type==="node"&&Xee.RUNTIME.parsedVersion!=null&&Xee.RUNTIME.parsedVersion>=18?t=newQee:Xee.RUNTIME.type==="node"?t=newete:t=newtte,yieldt.setup(),t})}Ql.newFormData=lAr;varQee=class{setup(){returnfA(this,void0,void0,function*(){this.fd=new(yieldPromise.resolve().then(()=>M$(mSt()))).FormData})}append(e,r){varn;(n=this.fd)===null||n===void0||n.append(e,r)}appendFile(e,r,n){varo,i;returnfA(this,void0,void0,function*(){n==null&&uOe(r)&&(n=r.name),rinstanceof(yieldPromise.resolve().then
`);o.enqueue(s)}catch(i){o.error(i)}})},cancel(){varo;returnbV(this,void0,void0,function*(){yield(o=r.return)===null||o===void0?void0:o.call(r)})}})}};Vs.StreamUtils=AOe;functionMxt(t,e){returnvV(this,arguments,function*(){varn,o;if(!t.body)throwe?.abort(),newB$.CohereError({message:"Attempted to iterate over a response with no body"});leti=newIOe,a=newhA,s=MOe(t.body);try{for(varu=_V(EMr(s)),l;l=yieldTa(u.next()),!l.done;){letc=l.value;for(letdofa.decode(c)){letf=i.decode(d);f&&(yieldyieldTa(f))}}}catch(c){n={error:c}}finally{try{l&&!l.done&&(o=u.return)&&(yieldTa(o.call(u)))}finally{if(n)thrown.error}}for(letcofa.flush()){letd=i.decode(c);d&&(yieldyieldTa(d))}})}Vs._iterSSEMessages=Mxt;functionEMr(t){returnvV(this,arguments,function*(){varr,n;leto=newUint8Array;try{for(vari=_V(t),a;a=yieldTa(i.next()),!a.done;){lets=a.value;if(s==null)continue;letu=sinstanceofArrayBuffer?newUint8Array(s):typeofs=="string"?newTextEncoder().encode(s):s,l=newUint8Array(o.length+u.length);l.set(o),l.set(u,o.length),o=l;letc;for(;(c=TMr(o))!==-1;)yieldyieldTa(o.slice(0,c)),o=o.slice(c)}}catch(s){r={error:s}}finally{try{a&&!a.done&&(n=i.return)&&(yieldTa(n.call(i)))}finally{if(r)throwr.error}}o.length>0&&(yieldyieldTa(o))})}functionTMr(t){for(letn=0;n<t.length-2;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)returnn+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)returnn+4}return-1}varIOe=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)returnnull;leti={event:this.event,data:this.data.join(`
`),raw:this.chunks};returnthis.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))returnnull;let[r,n,o]=IMr(e,":");returno.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},hA=classt{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){letr=this.decodeText(e);if(this.trailingCR&&(r="\r"+r,this.trailingCR=!1),r.endsWith("\r")&&(this.trailingCR=!0,r=r.slice(0,-1)),!r)return[];letn=t.NEWLINE_CHARS.has(r[r.length-1]||""),o=r.split(t.NEWLINE_REGEXP);returnn&&o.pop(),o.length===1&&!n?(this.buffer.push(o[0]),[]):(this.buffer.length>0&&(o=[this.buffer.join("")+o[0],...o.slice(1)],this.buffer=[]),n||(this.buffer=[o.pop()||""]),o)}decodeText(e){varr;if(e==null)return"";if(typeofe=="string")returne;if(typeofBuffer<"u"){if(einstanceofBuffer)returne.toString();if(einstanceofUint8Array)returnBuffer.from(e).toString();thrownewB$.CohereError({message:`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`})}if(typeofTextDecoder<"u"){if(einstanceofUint8Array||einstanceofArrayBuffer)return(r=this.textDecoder)!==null&&r!==void0||(this.textDecoder=newTextDecoder("utf8")),this.textDecoder.decode(e);thrownewB$.CohereError({message:`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`})}thrownewB$.CohereError({message:"Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error."})}flush(){if(!this.buffer.length&&!this.trailingCR)return[];lete=[this.buffer.join("")];returnthis.buffer=[],this.trailingCR=!1,e}};Vs.LineDecoder=hA;hA.NEWLINE_CHARS=newSet([`
`)}}}}catch(S){a={error:S}}finally{try{h&&!h.done&&(s=m.return)&&(yield s.call(m))}finally{if(a)throw a.error}}for(let S of g.flush()){let x=(0,ni.parseAWSEvent)(S);if(x){let O=yield(0,ni.mapResponseFromBedrock)(c,u,x);y.push(JSON.stringify(O)+`
`}});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new Ee.BadRequestError(i.error.body);case 401:throw new Ee.UnauthorizedError(i.error.body);case 403:throw new Ee.ForbiddenError(i.error.body);case 404:throw new Ee.NotFoundError(i.error.body);case 422:throw new Ee.UnprocessableEntityError(st.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new Ee.TooManyRequestsError(st.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new Ee.ClientClosedRequestError(st.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 500:throw new Ee.InternalServerError(i.error.body);case 501:throw new Ee.NotImplementedError(st.NotImplementedErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 503:throw new Ee.ServiceUnavailableError(i.error.body);case 504:throw new Ee.GatewayTimeoutError(st.GatewayTimeoutErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));default:throw new jr.CohereError({statusCode:i.error.statusCode,body:i.error.body})}switch(i.error.reason){case"non-json":throw new jr.CohereError({statusCode:i.error.statusCode,body:i.error.rawBody});case"timeout":throw new jr.CohereTimeoutError;case"unknown":throw new jr.CohereError({message:i.error.errorMessage})}})}generate(e,r){var n,o;return Vp(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:_t.fetcher)({url:(0,Hy.default)((o=yield _t.Supplier.get(this._options.environment))!==null&&o!==void 0?o:zy.CohereEnvironment.Production,"v1/generate"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield _t.Supplier.get(this._options.clientName))!=null?yield _t.Supplier.get(this._options.clientName):void 0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.13.0","User-Agent":"cohere-ai/7.13.0","X-Fern-Runtime":_t.RUNTIME.type,"X-Fern-Runtime-Version":_t.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},st.GenerateRequest.jsonOrThrow(e,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0})),{stream:!1}),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:3e5,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(i.ok)return st.Generation.parseOrThrow(i.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new Ee.BadRequestError(i.error.body);case 401:throw new Ee.UnauthorizedError(i.error.body);case 403:throw new Ee.ForbiddenError(i.error.body);case 404:throw new Ee.NotFoundError(i.error.body);case 422:throw new Ee.UnprocessableEntityError(st.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new Ee.TooManyRequestsError(st.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new Ee.ClientClosedRequestError(st.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{u
`).filter(Boolean).reduce((n,o)=>{let[i,a,...s]=o.split(" "),u=Number.parseInt(a,10);returns.forEach((l,c)=>n[l]=u+c),n},{});for(let[n,o]ofObject.entries(r)){leti=wPt.default.toByteArray(n);this.rankMap.set(i.join(","),o),this.textMap.set(o,i)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[o,i])=>(n[i]=this.textEncoder.encode(o),n),{})}encode(t,e=[],r="all"){letn=newRegExp(this.patStr,"ug"),o=oAe.specialTokenRegex(Object.keys(this.specialTokens)),i=[],a=newSet(e==="all"?Object.keys(this.specialTokens):e),s=newSet(r==="all"?Object.keys(this.specialTokens).filter(l=>!a.has(l)):r);if(s.size>0){letl=oAe.specialTokenRegex([...s]),c=t.match(l);if(c!=null)thrownewError(`The text contains a special token that is not allowed: ${c[0]}`)}letu=0;for(;;){letl=null,c=u;for(;o.lastIndex=c,l=o.exec(t),!(l==null||a.has(l[0]));)c=l.index+1;letd=l?.index??t.length;for(letpoft.substring(u,d).matchAll(n)){letm=this.textEncoder.encode(p[0]),h=this.rankMap.get(m.join(","));if(h!=null){i.push(h);continue}i.push(...U6r(m,this.rankMap))}if(l==null)break;letf=this.specialTokens[l[0]];i.push(f),u=l.index+l[0].length}returni}decode(t){lete=[],r=0;for(leti=0;i<t.length;++i){leta=t[i],s=this.textMap.get(a)??this.inverseSpecialTokens[a];s!=null&&(e.push(s),r+=s.length)}letn=newUint8Array(r),o=0;for(letiofe)n.set(i,o),o+=i.length;returnthis.textDecoder.decode(n)}},jre=oAe;B6r(jre,"specialTokenRegex",t=>newRegExp(t.map(e=>z6r(e)).join("|"),"g"))});varxPt=w(()=>{SPt()});asyncfunctionCPt(t){returntinNre||(Nre[t]=H6r.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>newjre(e)).catch(e=>{throwdeleteNre[t],e})),awaitNre[t]}asyncfunctionOPt(t){returnCPt(iAe(t))}varNre,H6r,aAe=w(()=>{xPt();QL();Nre={},H6r=new_m({})});functionWc(t){returntypeoft!="object"||!t?!1:!!("type"int&&t.type==="function"&&"function"int&&typeoft.function=="object"&&t.function&&"name"int.function&&"parameters"int.function)}varV6r,W6r,dB,fB,r8=w(()=>{vPt();K2();NE();QL();aAe();Df();V6r=t=>t.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":t.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":t.startsWith("gpt-4-32k")?"gpt-4-32k":t.startsWith("gpt-4-")?"gpt-4":t.startsWith("gpt-4o")?"gpt-4o":t;W6r=()=>!1,dB=classextendsCn{getlc_attributes(){return{callbacks:void0,verbose:void0}}constructor(e){super(e),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void0}),this.verbose=e.verbose??W6r(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}},fB=classextendsdB{getcallKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}constructor({callbacks:e,callbackManager:r,...n}){let{cache:o,...i}=n;super({callbacks:e??r,...i}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"_encoding",{enumerable:!0,configurable:!0,writable:!0,value:void0}),typeofo=="object"?this.cache=o:o?this.cache=Rre.global():this.cache=void0,this.caller=new_m(n??{})}asyncgetNumTokens(e){if(typeofe!="string")return0;letr=Math.ceil(e.length/4);if(!this._encoding)try{this._encoding=awaitOPt("modelName"inthis?V6r(this.modelName):"gpt2")}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}if(this._encoding)try{r=this._encoding.encode(e).length}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}returnr}static_convertInputToPromptValue(e){returntypeofe=="string"?newrF(e):Array.isArray(e)?newnF(e.map(fy)):e}_identifyingParams(){return{}}_getSerializedCacheKey
`+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&i.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function iEt(t){var e,r,n,o;let i=[];if(!((r=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||r===void 0)&&r.parts)for(let a of(o=(n=t.candidates)===null||n===void 0?void 0:n[0].content)===null||o===void 0?void 0:o.parts)a.functionCall&&i.push(a.functionCall);if(i.length>0)return i}function qre(t){return!!t.finishReason&&p5r.includes(t.finishReason)}function IA(t){var e,r,n;let o="";if((!t.candidates||t.candidates.length===0)&&t.promptFeedback)o+="Responsewasblocked",!((e=t.promptFeedback)===null||e===void 0)&&e.blockReason&&(o+=` due to ${t.promptFeedback.blockReason}`),!((r=t.promptFeedback)===null||r===void 0)&&r.blockReasonMessage&&(o+=`: ${t.promptFeedback.blockReasonMessage}`);else if(!((n=t.candidates)===null||n===void 0)&&n[0]){let i=t.candidates[0];qre(i)&&(o+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(o+=`: ${i.finishMessage}`))}return o}function i8(t){return this instanceof i8?(this.v=t,this):new i8(t)}function m5r(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIteratorisnotdefined.");var n=r.apply(t,e||[]),o,i=[];return o={},a("next"),a("throw"),a("return"),o[Symbol.asyncIterator]=function(){return this},o;function a(f){n[f]&&(o[f]=function(p){return new Promise(function(m,h){i.push([f,p,m,h])>1||s(f,p)})})}function s(f,p){try{u(n[f](p))}catch(m){d(i[0][3],m)}}function u(f){f.value instanceof i8?Promise.resolve(f.value.v).then(l,c):d(i[0][2],f)}function l(f){s("next",f)}function c(f){s("throw",f)}function d(f,p){f(p),i.shift(),i.length&&s(i[0][0],i[0][1])}}function h5r(t){let e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),r=b5r(e),[n,o]=r.tee();return{stream:y5r(n),response:g5r(o)}}async function g5r(t){let e=[],r=t.getReader();for(;;){let{done:n,value:o}=await r.read();if(n)return bAe(_5r(e));e.push(o)}}function y5r(t){return m5r(this,arguments,function*(){let r=t.getReader();for(;;){let{value:n,done:o}=yield i8(r.read());if(o)break;yield yield i8(bAe(n))}})}function b5r(t){let e=t.getReader();return new ReadableStream({start(n){let o="";return i();function i(){return e.read().then(({value:a,done:s})=>{if(s){if(o.trim()){n.error(new ef("Failedtoparsestream"));return}n.close();return}o+=a;let u=o.match(aEt),l;for(;u;){try{l=JSON.parse(u[1])}catch{n.error(new ef(`Error parsing JSON response: "${u[1]}"`));return}n.enqueue(l),o=o.substring(u[0].length),u=o.match(aEt)}return i()})}}})}function _5r(t){let e=t[t.length-1],r={promptFeedback:e?.promptFeedback};for(let n of t){if(n.candidates)for(let o of n.candidates){let i=o.index;if(r.candidates||(r.candidates=[]),r.candidates[i]||(r.candidates[i]={index:o.index}),r.candidates[i].citationMetadata=o.citationMetadata,r.candidates[i].groundingMetadata=o.groundingMetadata,r.candidates[i].finishReason=o.finishReason,r.candidates[i].finishMessage=o.finishMessage,r.candidates[i].safetyRatings=o.safetyRatings,o.content&&o.content.parts){r.candidates[i].content||(r.candidates[i].content={role:o.content.role||"user",parts:[]});let a={};for(let s of o.content.parts)s.text&&(a.text=s.text),s.functionCall&&(a.functionCall=s.functionCall),s.executableCode&&(a.executableCode=s.executableCode),s.codeExecutionResult&&(a.codeExecutionResult=s.codeExecutionResult),Object.keys(a).length===0&&(a.text=""),r.candidates[i].content.parts.push(a)}}n.usageMetadata&&(r.usageMetadata=n.usageMetadata)}return r}async function cEt(t,e,r,n){let o=await s8(e,kj.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(r),n);return h5r(o)}async function dEt(t,e,r,n){let i=await(await s8(e,kj.GENERATE_CONTENT,t,!1,JSON.stringify(r),n)).json();return{response:bAe(i)}}function fEt(t){if(t!=null){if(typeof t=="string")return{role:"system",parts:[{text:t}]};if(t.text)return{role:"system",parts:[t]};if(t.parts)return t.role?t:{role:"system",parts:t.parts}}}function a8(t){let e=[];if(typeof t=="string")e=[{text:t}];else for(let r of t)typeof r=="string"?e.push({text:r}):e.push(r);return v5r(e)}
`)===0?n.substr(1,n.length):n}).forEach(function(n){var o=n.split(":"),i=o.shift().trim();if(i){var a=o.join(":").trim();try{e.append(i,a)}catch(s){console.warn("Response"+s.message)}}}),e}function mx(t,e){if(!(this instanceof mx))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(e||(e={}),this.type="default",this.status=e.status===void 0?200:e.status,this.status<200||this.status>599)throw new RangeError("Failedtoconstruct'Response':Thestatusprovided(0)isoutsidetherange[200,599].");this.ok=this.status>=200&&this.status<300,this.statusText=e.statusText===void 0?"":""+e.statusText,this.headers=new jl(e.headers),this.url=e.url||"",this._initBody(t)}function TEt(t,e){return new Promise(function(r,n){var o=new qj(t,e);if(o.signal&&o.signal.aborted)return n(new Bj("Aborted","AbortError"));var i=new XMLHttpRequest;function a(){i.abort()}i.onload=function(){var l={statusText:i.statusText,headers:U5r(i.getAllResponseHeaders()||"")};o.url.indexOf("file://")===0&&(i.status<200||i.status>599)?l.status=200:l.status=i.status,l.url="responseURL"in i?i.responseURL:l.headers.get("X-Request-URL");var c="response"in i?i.response:i.responseText;setTimeout(function(){r(new mx(c,l))},0)},i.onerror=function(){setTimeout(function(){n(new TypeError("Network request failed"))},0)},i.ontimeout=function(){setTimeout(function(){n(new TypeError("Network request timed out"))},0)},i.onabort=function(){setTimeout(function(){n(new Bj("Aborted","AbortError"))},0)};function s(l){try{return l===""&&Gc.location.href?Gc.location.href:l}catch{return l}}if(i.open(o.method,s(o.url),!0),o.credentials==="include"?i.withCredentials=!0:o.credentials==="omit"&&(i.withCredentials=!1),"responseType"in i&&(Zf.blob?i.responseType="blob":Zf.arrayBuffer&&(i.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof jl||Gc.Headers&&e.headers instanceof Gc.Headers)){var u=[];Object.getOwnPropertyNames(e.headers).forEach(function(l){u.push(gB(l)),i.setRequestHeader(l,CAe(e.headers[l]))}),o.headers.forEach(function(l,c){u.indexOf(c)===-1&&i.setRequestHeader(c,l)})}else o.headers.forEach(function(l,c){i.setRequestHeader(c,l)});o.signal&&(o.signal.addEventListener("abort",a),i.onreadystatechange=function(){i.readyState===4&&o.signal.removeEventListener("abort",a)}),i.send(typeof o._bodyInit>"u"?null:o._bodyInit)})}var Gc,Zf,xEt,OEt,$5r,z5r,Bj,AEt=w(()=>{Gc=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof window<"u"&&window||{},Zf={searchParams:"URLSearchParams"in Gc,iterable:"Symbol"in Gc&&"iterator"in Symbol,blob:"FileReader"in Gc&&"Blob"in Gc&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in Gc,arrayBuffer:"ArrayBuffer"in Gc};Zf.arrayBuffer&&(xEt=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],OEt=ArrayBuffer.isView||function(t){return t&&xEt.indexOf(Object.prototype.toString.call(t))>-1});jl.prototype.append=function(t,e){t=gB(t),e=CAe(e);var r=this.map[t];this.map[t]=r?r+", "+e:e};jl.prototype.delete=function(t){delete this.map[gB(t)]};jl.prototype.get=function(t){return t=gB(t),this.has(t)?this.map[t]:null};jl.prototype.has=function(t){return this.map.hasOwnProperty(gB(t))};jl.prototype.set=function(t,e){this.map[gB(t)]=CAe(e)};jl.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)};jl.prototype.keys=function(){var t=[];return this.forEach(function(e,r){t.push(r)}),OAe(t)};jl.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),OAe(t)};jl.prototype.entries=function(){var t=[];return this.forEach(function(e,r){t.push([r,e])}),OAe(t)};Zf.iterable&&(jl.prototype[Symbol.iterator]=jl.prototype.entries);$5r=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];qj.prototype.clone=function(){return new qj(this,{body:this._bodyInit})};EEt.call(qj.prototype);EEt.call(mx.pro
`,"\r"]);Vj.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function YAe(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var fTt=w(()=>{});async function*SWr(t,e){if(!t.body)throw e.abort(),new vt("Attempted to iterate over a response with no body");let r=new ZAe,n=new Vj,o=YAe(t.body);for await(let i of xWr(o))for(let a of n.decode(i)){let s=r.decode(a);s&&(yield s)}for(let i of n.flush()){let a=r.decode(i);a&&(yield a)}}async function*xWr(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?new TextEncoder().encode(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let i;for(;(i=cTt(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function CWr(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var yx,ZAe,ane=w(()=>{c8();Kp();dTt();fTt();Vn();Kp();yx=class t{constructor(e,r){this.iterator=e,this.controller=r}static fromSSEResponse(e,r){let n=!1;async function*o(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let i=!1;try{for await(let a of SWr(e,r))if(!i){if(a.data.startsWith("[DONE]")){i=!0;continue}if(a.event===null||a.event.startsWith("response.")||a.event.startsWith("transcript.")){let s;try{s=JSON.parse(a.data)}catch(u){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),u}if(s&&s.error)throw new Ys(void 0,s.error,void 0,XAe(e.headers));yield s}else{let s;try{s=JSON.parse(a.data)}catch(u){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),u}if(a.event=="error")throw new Ys(void 0,s.error,s.message,void 0);yield{event:a.event,data:s}}}i=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{i||r.abort()}}return new t(o,r)}static fromReadableStream(e,r){let n=!1;async function*o(){let a=new Vj,s=YAe(e);for await(let u of s)for(let l of a.decode(u))yield l;for(let u of a.flush())yield u}async function*i(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{for await(let s of o())a||s&&(yield JSON.parse(s));a=!0}catch(s){if(s instanceof Error&&s.name==="AbortError")return;throw s}finally{a||r.abort()}}return new t(i,r)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),o=i=>({next:()=>{if(i.length===0){let a=n.next();e.push(a),r.push(a)}return i.shift()}});return[new t(()=>o(e),this.controller),new t(()=>o(r),this.controller)]}toReadableStream(){let e=this,r,n=new TextEncoder;return new HAe({async start(){r=e[Symbol.asyncIterator]()},async pull(o){try{let{value:i,done:a}=await r.next();if(a)return o.close();let s=n.encode(JSON.stringify(i)+`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=CWr(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function tIe(t,e,r){if(t=await t,mTt(t))return t;if(pTt(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=d8(o)?[await o.arrayBuffer()]:[o];return new tne(i,e,r)}let n=await PWr(t);if(e||(e=TWr(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new tne(n,e,r)}async function PWr(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(d8(t))e.push(await t.arrayBuffer());else if(AWr(t))for await(let r of t)e.push(r);else throw new Error(`Unexpecteddatatype:${typeoft};constructor:${t?.constructor?.name};props:${EWr(t)}`);return e}function EWr(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function TWr(t){return QAe(t.name)||QAe(t.filename)||QAe(t.path)?.split(/[\\/]/).pop()}var pTt,mTt,d8,OWr,QAe,AWr,rIe,fg,hTt,eIe,sne=w(()=>{c8();c8();pTt=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",mTt=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&d8(t),d8=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",OWr=t=>mTt(t)||pTt(t)||KAe(t);QAe=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},AWr=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",rIe=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody",fg=async t=>{let e=await hTt(t.body);return VAe(e,t)},hTt=async t=>{let e=new zAe;return await Promise.all(Object.entries(t||{}).map(([r,n])=>eIe(e,r,n))),e},eIe=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Receivednullfor"${e}";topassnullinFormData,youmustusethestring'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(OWr(r)){let n=await tIe(r);t.append(e,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>eIe(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>eIe(t,`${e}[${n}]`,o)));else throw new TypeError(`Invalidvaluegiventoform,expectedastring,number,boolean,object,Array,FileorBlobbutgot${r}instead`)}}});async function wTt(t){let{response:e}=t;if(t.options.stream)return UO("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):yx.fromSSEResponse(e,t.controller);if(e.status===204)return null;if(t.options.__binaryResponse)return e;let n=e.headers.get("content-type")?.split(";")[0]?.trim();if(n?.includes("application/json")||n?.endsWith("+json")){let a=await e.json();return UO("response",e.status,e.url,e.headers,a),STt(a,e)}let i=await e.text();return UO("response",e.status,e.url,e.headers,i),i}function STt(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}function DWr(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let o=n[1]||0,i=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${i}.${a}`}}}return null}function xTt(t){if(!t)return!0;for(let e in t)return!1;return!0}function CTt(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function _Tt(t,e){for(let r
\r `.includes(t[n]);)n++};returna()},EIe=t=>YWr(t,oc.ALL^oc.NUM)});functionXWr(t,e){let{id:r,choices:n,created:o,model:i,system_fingerprint:a,...s}=t,u={...s,id:r,choices:n.map(({message:l,finish_reason:c,index:d,logprobs:f,...p})=>{if(!c)thrownewvt(`missing finish_reason for choice ${d}`);let{content:m=null,function_call:h,tool_calls:b,...g}=l,y=l.role;if(!y)thrownewvt(`missing role for choice ${d}`);if(h){let{arguments:S,name:x}=h;if(S==null)thrownewvt(`missing function_call.arguments for choice ${d}`);if(!x)thrownewvt(`missing function_call.name for choice ${d}`);return{...p,message:{content:m,function_call:{arguments:S,name:x},role:y,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}returnb?{...p,index:d,finish_reason:c,logprobs:f,message:{...g,role:y,content:m,refusal:l.refusal??null,tool_calls:b.map((S,x)=>{let{function:O,type:P,id:E,...A}=S,{arguments:I,name:R,...N}=O||{};if(E==null)thrownewvt(`missing choices[${d}].tool_calls[${x}].id
${Sne(t)}`);return{...A,id:E,type:P,function:{...N,name:R,arguments:I}}})}}:{...p,message:{...g,content:m,role:y,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}),created:o,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};returnjTt(u,e)}functionSne(t){returnJSON.stringify(t)}varkB,Ti,Dl,WO,$B,kA,TIe,vne,AIe,IIe,MIe,wne,RIe,BTt,BB,jIe=w(()=>{Kp();CIe();ane();LB();$Tt();kB=function(t,e,r,n,o){if(n==="m")thrownewTypeError("Private method is not writable");if(n==="a"&&!o)thrownewTypeError("Private accessor was defined without a setter");if(typeofe=="function"?t!==e||!o:!e.has(t))thrownewTypeError("Cannot write private member to an object whose class did not declare it");returnn==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r},Ti=function(t,e,r,n){if(r==="a"&&!n)thrownewTypeError("Private accessor was defined without a getter");if(typeofe=="function"?t!==e||!n:!e.has(t))thrownewTypeError("Cannot read private member from an object whose class did not declare it");returnr==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},BB=classtextendsFB{constructor(e){super(),Dl.add(this),WO.set(this,void0),$B.set(this,void0),kA.set(this,void0),kB(this,WO,e,"f"),kB(this,$B,[],"f")}getcurrentChatCompletionSnapshot(){returnTi(this,kA,"f")}staticfromReadableStream(e){letr=newt(null);returnr._run(()=>r._fromReadableStream(e)),r}staticcreateChatCompletion(e,r,n){leto=newt(r);returno._run(()=>o._runChatCompletion(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async_createChatCompletion(e,r,n){super._createChatCompletion;leto=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),Ti(this,Dl,"m",TIe).call(this);leti=awaite.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();forawait(letaofi)Ti(this,Dl,"m",AIe).call(this,a);if(i.controller.signal?.aborted)thrownewLi;returnthis._addChatCompletion(Ti(this,Dl,"m",wne).call(this))}async_fromReadableStream(e,r){letn=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),Ti(this,Dl,"m",TIe).call(this),this._connected();leto=yx.fromReadableStream(e,this.controller),i;forawait(letaofo)i&&i!==a.id&&this._addChatCompletion(Ti(this,Dl,"m",wne).call(this)),Ti(this,Dl,"m",AIe).call(this,a),i=a.id;if(o.controller.signal?.aborted)thrownewLi;returnthis._addChatCompletion(Ti(this,Dl,"m",wne).call(this))}[(WO=newWeakMap,$B=newWeakMap,kA=newWeakMap,Dl=newWeakSet,TIe=function(){this.ended||kB(this,kA,void0,"f")},vne=function(r){letn=Ti(this,$B,"f")[r.index];returnn||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:newSet,current_tool_call_index:null},Ti(this,$B,"f")[r.index]=n,n)},AIe=function(r){if(this.ended)return;letn=Ti(this,Dl,"m",BTt).call(this,r);this._emit("chunk",r,n);for(letoofr.choices){leti=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??[]});leta=Ti(this,Dl,"m",vne).call(this,i);i.finish_reason&&(Ti(this,Dl,"m",MIe).call(this,i),a.current_tool_call_index!=null&&Ti(this,Dl,"m",IIe).call(this,i,a.current_tool_call_index));for(letsofo.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(Ti(this,Dl,"m",MIe).call(this,i),a.current_tool_call_index!=null&&Ti(this,Dl,"m",IIe).call(this,i,a.current_tool_call_index)),a.cur
`);super({baseURL:a.baseURL,timeout:a.timeout??6e5,httpAgent:a.httpAgent,maxRetries:a.maxRetries,fetch:a.fetch}),this.completions=newQj(this),this.chat=newHO(this),this.embeddings=neweN(this),this.files=newBA(this),this.images=newaN(this),this.audio=new_x(this),this.moderations=newuN(this),this.models=newUA(this),this.fineTuning=newYy(this),this.vectorStores=newZm(this),this.beta=newJy(this),this.batches=newDA(this),this.uploads=newWA(this),this.responses=newVA(this),this.evals=newxx(this),this._options=a,this.apiKey=r,this.organization=n,this.project=o}defaultQuery(){returnthis._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){returnqAe(e,{arrayFormat:"brackets"})}};sAt=Wt;Wt.OpenAI=sAt;Wt.DEFAULT_TIMEOUT=6e5;Wt.OpenAIError=vt;Wt.APIError=Ys;Wt.APIConnectionError=qO;Wt.APIConnectionTimeoutError=Xf;Wt.APIUserAbortError=Li;Wt.NotFoundError=SB;Wt.ConflictError=xB;Wt.RateLimitError=OB;Wt.BadRequestError=_B;Wt.AuthenticationError=vB;Wt.InternalServerError=PB;Wt.PermissionDeniedError=wB;Wt.UnprocessableEntityError=CB;Wt.toFile=tIe;Wt.fileFromPath=rne;Wt.Completions=Qj;Wt.Chat=HO;Wt.ChatCompletionsPage=NA;Wt.Embeddings=eN;Wt.Files=BA;Wt.FileObjectsPage=nN;Wt.Images=aN;Wt.Audio=_x;Wt.Moderations=uN;Wt.Models=UA;Wt.ModelsPage=sN;Wt.FineTuning=Yy;Wt.VectorStores=Zm;Wt.VectorStoresPage=lN;Wt.VectorStoreSearchResponsesPage=cN;Wt.Beta=Jy;Wt.Batches=DA;Wt.BatchesPage=Wj;Wt.Uploads=WA;Wt.Responses=VA;Wt.Evals=xx;Wt.EvalListResponsesPage=rN;jne=classextendsWt{constructor({baseURL:e=MA("OPENAI_BASE_URL"),apiKey:r=MA("AZURE_OPENAI_API_KEY"),apiVersion:n=MA("OPENAI_API_VERSION"),endpoint:o,deployment:i,azureADTokenProvider:a,dangerouslyAllowBrowser:s,...u}={}){if(!n)thrownewvt("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeofa=="function"&&(s=!0),!a&&!r)thrownewvt("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(a&&r)thrownewvt("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(r??(r=aAt),u.defaultQuery={...u.defaultQuery,"api-version":n},e){if(o)thrownewvt("baseURL and endpoint are mutually exclusive")}else{if(o||(o=process.env.AZURE_OPENAI_ENDPOINT),!o)thrownewvt("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${o}/openai`}super({apiKey:r,baseURL:e,...u,...s!==void0?{dangerouslyAllowBrowser:s}:{}}),this.apiVersion="",this._azureADTokenProvider=a,this.apiVersion=n,this.deploymentName=i}buildRequest(e,r={}){if(O9r.has(e.path)&&e.method==="post"&&e.body!==void0){if(!AB(e.body))thrownewError("Expected request body to be an object");letn=this.deploymentName||e.body.model||e.__metadata?.model;n!==void0&&!this.baseURL.includes("/deployments")&&(e.path=`/deployments/${n}${e.path}`)}returnsuper.buildRequest(e,r)}async_getAzureADToken(){if(typeofthis._azureADTokenProvider=="function"){lete=awaitthis._azureADTokenProvider();if(!e||typeofe!="string")thrownewvt(`Expected 'azureADTokenProvider' argument to return a string but it returned ${e}`);returne}}authHeaders(e){return{}}asyncprepareOptions(e){if(e.headers?.["api-key"])returnsuper.prepareOptions(e);letr=awaitthis._getAzureADToken();if(e.headers??(e.headers={}),r)e.headers.Authorization=`Bearer ${r}`;elseif(this.apiKey!==aAt)e.headers["api-key"]=this.apiKey;elsethrownewvt("Unable to handle auth");returnsuper.prepareOptions(e)}},O9r=newSet(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations"]),aAt="<Missing Key>"});functionJp(t,e){if(t.function===void0)return;letr;if(e?.part
`))}let n={name:t.function.name,args:r,type:"tool_call"};return e?.returnId&&(n.id=t.id),n}function Ox(t){if(t.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:t.id,type:"function",function:{name:t.name,arguments:JSON.stringify(t.args)}}}function Xm(t,e){return{name:t.function?.name,args:t.function?.arguments,id:t.id,error:e,type:"invalid_tool_call"}}var fMe,Zc,uAt=w(()=>{tF();bhe();$E();SR();fMe=class extends AR{static lc_name(){return"JsonOutputToolsParser"}constructor(e){super(e),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","openai_tools"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.returnId=e?.returnId??this.returnId}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,r=!0){let n=e[0].message,o;if(Oi(n)&&n.tool_calls?.length?o=n.tool_calls.map(a=>{let{id:s,...u}=a;return this.returnId?{id:s,...u}:u}):n.additional_kwargs.tool_calls!==void 0&&(o=JSON.parse(JSON.stringify(n.additional_kwargs.tool_calls)).map(s=>Jp(s,{returnId:this.returnId,partial:r}))),!o)return[];let i=[];for(let a of o)if(a!==void 0){let s={type:a.name,args:a.args,id:a.id};i.push(s)}return i}},Zc=class extends fMe{static lc_name(){return"JsonOutputKeyToolsParser"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","openai_tools"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"keyName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"returnSingle",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"zodSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){if(this.zodSchema===void 0)return e;let r=await this.zodSchema.safeParseAsync(e);if(r.success)return r.data;throw new vm(`Failedtoparse.Text:"${JSON.stringify(e,null,2)}".Error:${JSON.stringify(r.error.errors)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){let n=(await super.parsePartialResult(e)).filter(i=>i.type===this.keyName),o=n;if(n.length)return this.returnId||(o=n.map(i=>i.args)),this.returnSingle?o[0]:o}async parseResult(e){let n=(await super.parsePartialResult(e,!1)).filter(a=>a.type===this.keyName),o=n;return n.length?(this.returnId||(o=n.map(a=>a.args)),this.returnSingle?this._validateResult(o[0]):await Promise.all(o.map(a=>this._validateResult(a)))):void 0}}});var lAt=w(()=>{uAt()});var aq=w(()=>{lAt()});var dAt,cAt,fAt,Nne=w(()=>{dAt=Symbol("Let zodToJsonSchema decide on which parser to use"),cAt={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},fAt=t=>typeof t=="string"?{...cAt,basePath:["#"],definitions:{},name:t}:{...cAt,basePath:["#"],definitions:{},...t}});function pAt(t){if(!t)return!0;for(let e in t)return!1;return!0}var P8,pMe=w(()=>{P8=t=>"_def"in t?t._def:t});var mAt,mMe=w(()=>{Nne();pMe();mAt=t=>{let e=fAt(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[P8(o),{def:P8(o),path:[...e.ba
]`;continue}i+=o[l],o[l]==="\\"?a=!0:s&&o[l]==="]"?s=!1:!s&&o[l]==="["&&(s=!0)}try{letl=newRegExp(i)}catch{returnconsole.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}returni}});functionFne(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===de.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:pr(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};letr={type:"object",additionalProperties:pr(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")returnr;if(t.keyType?._def.typeName===de.ZodString&&t.keyType._def.checks?.length){letn=Object.entries(Dne(t.keyType._def,e)).reduce((o,[i,a])=>i==="type"?o:{...o,[i]:a},{});return{...r,propertyNames:n}}elseif(t.keyType?._def.typeName===de.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};returnr}varkne=w(()=>{Td();Zs();Lne()});functionEAt(t,e){if(e.mapStrategy==="record")returnFne(t,e);letr=pr(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=pr(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}varIMe=w(()=>{Zs();kne()});functionTAt(t){lete=t.values,n=Object.keys(t.values).filter(i=>typeofe[e[i]]!="number").map(i=>e[i]),o=Array.from(newSet(n.map(i=>typeofi)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}varMMe=w(()=>{});functionAAt(){return{not:{}}}varRMe=w(()=>{});functionIAt(t){returnt.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}varjMe=w(()=>{});functionRAt(t,e){if(e.target==="openApi3")returnMAt(t,e);letr=t.optionsinstanceofMap?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeNameinE8&&(!n._def.checks||!n._def.checks.length))){letn=r.reduce((o,i)=>{leta=E8[i._def.typeName];returna&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}elseif(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){letn=r.reduce((o,i)=>{leta=typeofi._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:returno}},[]);if(n.length===r.length){leto=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],[])}}}elseif(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};returnMAt(t,e)}varE8,MAt,$ne=w(()=>{Zs();E8={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};MAt=(t,e)=>{letr=(t.optionsinstanceofMap?Array.from(t.options.values()):t.options).map((n,o)=>pr(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeofn=="object"&&Object.keys(n).length>0));returnr.length?{anyOf:r}:void0}});functionjAt(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))returne.target==="openApi3"||e.nullableStrategy==="property"?{type:E8[t.innerType._def.typeName],nullable:!0}:{type:[E8[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){letn=pr(t.innerType._def,{...e,currentPath:[...e.currentPath]});returnn&&"$ref"inn?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}letr=pr(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});returnr&&{anyOf:[r,{type:"null"}]}}varNMe=w(()=>{Zs();$ne()});functionNAt(t,e){letr={type:"number"};if(!t.checks)returnr;for(letnoft.checks)switch(n.kind){case"int":r.type="integer",hMe(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?Wn(r,"
Details: ${m.message}`),newwR(h,JSON.stringify(e))}else{letm=oa(o,this.schema);if(!m.valid){leth="Received tool input did not match expected schema";throwthis.verboseParsingErrors&&(h=`${h}
`)}`),newwR(h,JSON.stringify(e))}i=o}leta=CR(r),u=awaitBs.configure(a.callbacks,this.callbacks,a.tags||n,this.tags,a.metadata,this.metadata,{verbose:this.verbose})?.handleToolStart(this.toJSON(),typeofe=="string"?e:JSON.stringify(e),a.runId,void0,void0,void0,a.runName);deletea.runId;letl;try{l=awaitthis._call(i,u,a)}catch(m){throwawaitu?.handleToolError(m),m}letc,d;if(this.responseFormat==="content_and_artifact")if(Array.isArray(l)&&l.length===2)[c,d]=l;elsethrownewError(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
Result: ${JSON.stringify(l)}`);elsec=l;letf;RE(e)&&(f=e.id),!f&&U4e(a)&&(f=a.toolCall.id);letp=$9r({content:c,artifact:d,toolCallId:f,name:this.name});returnawaitu?.handleToolEnd(p),p}},ZO=classextendsVne{constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:Wr.object({input:Wr.string().optional()}).transform(r=>r.input)})}call(e,r){letn=typeofe=="string"||e==null?{input:e}:e;returnsuper.call(n,r)}},XMe=classextendsZO{staticlc_name(){return"DynamicTool"}constructor(e){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void0}),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}asynccall(e,r){letn=CR(r);returnn.runName===void0&&(n.runName=this.name),super.call(e,n)}async_call(e,r,n){returnthis.func(e,r,n)}},QMe=classextendsVne{staticlc_name(){return"DynamicStructuredTool"}constructor(e){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void0}),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}asynccall(e,r,n){leto=CR(r);returno.runName===void0&&(o.runName=this.name),super.call(e,o,n)}_call(e,r,n){returnthis.func(e,r,n)}}});varZA=w(()=>{lIt()});vareRe,cIt=w(()=>{Dn();pg();ZA();eRe=classextendsZO{staticlc_name(){return"DallEAPIWrapper"}constructor(e){e?.responseFormat!==void0&&["url","b64_json"].includes(e.responseFormat)&&(e.dallEResponseFormat=e.responseFormat,e.responseFormat="content"),super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"dalle_api_wrapper"}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:"A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description."}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"dall-e-3"}),Object.defineProperty(this,"style",{enumerable:!0,configurable:!0,writable:!0,value:"vivid"}),Object.defineProperty(this,"quality",{enumerable:!0,configurable:!0,writable:!0,value:"standard"}),Object.defineProperty(this,"n",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:"1024x1024"}),Object.defineProperty(this,"dallEResponseFormat",{enumerable:!0,configurable:!0,writable:!0,value:"url"}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,writable:!0,value:void0});letr=e?.apiKey??e?.openAIApiKey??ot("OPENAI_API_KEY"),n=e?.organization??ot("OPENAI_ORGANIZATION"),o={apiKey:r,organization:n,dangerouslyAllowBrowser:!0,baseURL:e?.baseUrl};this.client=newWt(o),this.model=e?.model??e?.modelName??this.model,this.style=e?.style??this.style,this.quality=e?.quality??this.quality,this.n=e?.n??this.n,this.size=e?.size??this.size,this.dallEResponseFormat=e?.dallEResponseFormat??this.dallEResponseFormat,this.user=e?.user}processMultipleGeneratedUrls(e){returnthis.dallEResponseFormat==="url"?e.flatMap(r=>r.data.flatMap(o=>o.url?{type:"image_url",image_url:o.url}:[]).filter(o=>o!==void0&&o.type==="image_url"&&typeofo.image_url=="string"&&o.image_url!==void0)):e.flatMap(r=>r.data.flatMap(o=>o.b64_json?{type:"image_url",image_url:{url:o.b64_json}}:[]).filter(o=>o!==void0&&o.type==="image_url"&&typeofo.image_url=="object"&&"url"in
- `),G9r={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported.
- ${K9r}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmer property must be a function.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.oramasearch.com/open-source/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Custom stop words array must only contain strings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boost value must be a number greater than, or less than 0.",INVALID_FILTER_OPERATION:"You can only use one operation per filter, you requested %d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sort is disabled. Please read the documentation at https://docs.oramasearch for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead.
Input vectors must be of the size declared in the schema, as calculating similarity between vectors of different sizes can lead to unexpected results.`,WRONG_SEARCH_PROPERTY_TYPE:'Property "%s" is not searchable. Only "string" properties are searchable.',FACET_NOT_SUPPORTED:`Facet doens't support the type "%s".`,INVALID_DISTANCE_SUFFIX:'Invalid distance suffix "%s". Valid suffixes are: cm, m, km, mi, yd, ft.',INVALID_SEARCH_MODE:'Invalid search mode "%s". Valid modes are: "fulltext", "vector", "hybrid".',MISSING_VECTOR_AND_SECURE_PROXY:"No vector was provided and no secure proxy was configured. Please provide a vector or configure an Orama Secure Proxy to perform hybrid search.",MISSING_TERM:'"term" is a required parameter when performing hybrid search. Please provide a search term.',INVALID_VECTOR_INPUT:'Invalid "vector" property. Expected an object with "value" and "property" properties, but got "%s" instead.',PLUGIN_CRASHED:"A plugin crashed during initialization. Please check the error message for more information:",PLUGIN_SECURE_PROXY_NOT_FOUND:`Could not find '@orama/secure-proxy-plugin' installed in your Orama instance.
Please install it before proceeding with creating an answer session.
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL:`Could not find a chat model defined in the secure proxy plugin configuration.
Please provide a chat model before proceeding with creating an answer session.
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages."}});functionEIt(t){return{raw:Number(t),formatted:mN(t)}}functionTIt(t){if(t.id){if(typeoft.id!="string")throwqt("DOCUMENT_ID_MUST_BE_STRING",typeoft.id);returnt.id}returnI8()}functionnRe(t,e){for(let[r,n]ofObject.entries(e)){leto=t[r];if(!(typeofo>"u")&&!(n==="geopoint"&&typeofo=="object"&&typeofo.lon=="number"&&typeofo.lat=="number")&&!(n==="enum"&&(typeofo=="string"||typeofo=="number"))){if(n==="enum[]"&&Array.isArray(o)){leti=o.length;for(leta=0;a<i;a++)if(typeofo[a]!="string"&&typeofo[a]!="number")returnr+"."+a;continue}if(XO(n)){leti=iRe(n);if(!Array.isArray(o)||o.length!==i)throwqt("INVALID_INPUT_VECTOR",r,i,o.length);continue}if(pq(n)){if(!Array.isArray(o))returnr;leti=oRe(n),a=o.length;for(lets=0;s<a;s++)if(typeofo[s]!==i)returnr+"."+s;continue}if(typeofn=="object"){if(!o||typeofo!="object")returnr;leti=nRe(o,n);if(i)returnr+"."+i;continue}if(typeofo!==n)returnr}}}functionAIt(t){returnt==="geopoint"}functionXO(t){returntypeoft=="string"&&/^vector\[\d+\]$/.test(t)}functionpq(t){returntypeoft=="string"&&J9r[t]}functionoRe(t){returnY9r[t]}functioniRe(t){lete=Number(t.slice(7,-1));switch(!0){caseisNaN(e):throwqt("INVALID_VECTOR_VALUE",t);casee<=0:throwqt("INVALID_VECTOR_SIZE",t);default:returne}}varJ9r,Y9r,M8=w(()=>{ic();Ds();Ds();J9r={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},Y9r={"string[]":"string","number[]":"number","boolean[]":"boolean","enum[]":"enum"}});functionIIt(){return{idToInternalId:newMap,internalIdToId:[],save:Z9r,load:X9r}}functionZ9r(t){return{internalIdToId:t.internalIdToId}}functionX9r(t,e){let{internalIdToId:r}=e;t.internalDocumentIDStore.idToInternalId.clear(),t.internalDocumentIDStore.internalIdToId=[];letn=r.length;for(leto=0;o<n;o++){leti=r[o];t.internalDocumentIDStore.idToInternalId.set(i,o+1),t.internalDocumentIDStore.internalIdToId.push(i)}}functionwi(t,e){if(typeofe=="string"){letr=t.idToInternalId.get(e);if(r)returnr;letn=t.idToInternalId.size+1;returnt.idToInternalId.set(e,n),t.internalIdToId.push(e),n}returne>t.internalIdToId.length?wi(t,e.toString()):e}functionhg(t,e){if(t.internalIdToId.length<e)thrownewError(`Invalid internalId ${e}`);returnt.internalIdToId[e-1]}vargg=w(()=>{});functioneKr(t,e){return{sharedInternalDocumentStore:e,docs:{},count:0}}functiontKr(t,e){letr=wi(t.sharedInternalDocumentStore,e);returnt.docs[r]}functionrKr(t,e){letr=e.length,n=Array.from({length:r});for(leto=0;o<r;o++){leti=wi(t.sharedInternalDocumentStore,e[o]);n[o]=t.docs[i]}returnn}functionnKr(t){returnt.docs}functionoKr(t,e,r){letn=wi(t.sharedInternalDocumentStore,e);returntypeoft.docs[n]<"u"?!1:(t.docs[n]=r,t.count++,!0)}functioniKr(t,e){letr=wi(t.sharedInternalDocumentStore,e);returntypeoft.docs[r]>"u"?!1:(deletet.docs[r],t.count--,!0)}functionaKr(t){returnt.count}functionsKr(t,e){letr=e;return{docs:r.docs,count:r.count,sharedInternalDocumentStore:t}}functionuKr(t){return{docs:t.docs,count:t.count}}functionMIt(){return{create:eKr,get:tKr,getMultiple:rKr,getAll:nKr,store:oKr,remove:iKr,count:aKr,load:sKr,save:uKr}}varaRe=w(()=>{gg()});functionjIt(t,e){letr=[],n=t.plugins?.length;if(!n)returnr;for(leto=0;o<n;o++)try{leti=t.plugins[o];typeofi[e]=="function"&&r.push(i[e])}catch(i){throwconsole.error("Caught error in getAllPluginsByHook:",i),qt("PLUGIN_CRASHED")}returnr}varRIt,NIt=w(()=>{ic();RIt=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeLoad","afterLoad","afterCreate"]});functioneb(t,e,r,n){if(t.some(Qs))return(async()=>{for(letioft)awaiti(e,r,n)})();for(letioft)i(e,r,n)}functionhN(t,e,r){if(t.some(Qs))return(async()=>{for(letooft)awaito(e,r)})();for(letoof
whichislongerthanthespecified${this.chunkSize}`),o.length>0)){let l=this.joinDocs(o,r);for(l!==null&&n.push(l);i>this.chunkOverlap||i+u+o.length*r.length>this.chunkSize&&i>0;)i-=await this.lengthFunction(o[0]),o.shift()}o.push(s),i+=u}let a=this.joinDocs(o,r);return a!==null&&n.push(a),n}},aie=class t extends HRe{static lc_name(){return"RecursiveCharacterTextSplitter"}constructor(e){super(e),Object.defineProperty(this,"separators",{enumerable:!0,configurable:!0,writable:!0,value:[`
`+a;returnn&&o&&r.push({sender:n===Pi?Pi:e_,message:o.trim(),isVisible:!0,timestamp:i?Qhe(i):null}),r}asyncfunctionvN(t,e){awaite.clearChatMemory();for(letr=0;r<t.length-1;r++){letn=t[r];if(n.sender===Pi){leto=t[r+1];o?.sender===e_&&awaite.getMemory().saveContext({input:n.message},{output:o.message})}}}$r();yo();yo();yn();varwN=require("obsidian"),Rx=class{staticasyncisImageUrl(e,r){try{letn,o=!1;try{leti=newURL(e),a=i.pathname,s=a.lastIndexOf("."),u=a.lastIndexOf("/");if(s>u&&s>-1&&(n=a.substring(s+1).toLowerCase()),n&&!this.IMAGE_EXTENSIONS.some(c=>c.toLowerCase()===`.${n}`))returnfe(`Unsupported image format from URL path: .${n}. Supported formats: ${this.IMAGE_EXTENSIONS.join(", ")}`,e),!1;try{letc=(awaitUs(e,{method:"HEAD",headers:{}})).headers.get("content-type");returnc?.startsWith("image/")?!0:(console.warn(`HEAD request succeeded for ${e} but Content-Type (${c}) is not image/*.`),!1)}catch(l){console.warn(`HEAD request failed for URL: ${e}. Proceeding to heuristic check.`,l);letc=i.searchParams,f=[c.has("w")||c.has("width"),c.has("h")||c.has("height"),c.has("format"),c.has("fit"),c.has("quality"),i.pathname.includes("/image/"),i.pathname.includes("/images/"),i.pathname.includes("/img/"),c.has("auto"),c.has("crop")].filter(Boolean).length;returnf>=2?(fe(`Identified as image based on URL heuristics (indicator count: ${f}): ${e}`),!0):!1}}catch{o=!0;leti=e.lastIndexOf(".");if(i>-1)n=e.substring(i+1).toLowerCase();elsereturn!1}if(o)if(n&&this.IMAGE_EXTENSIONS.some(i=>i.toLowerCase()===`.${n}`)){leti=r.getAbstractFileByPath(e);returniinstanceofwN.TFile?i.stat.size>this.MAX_IMAGE_SIZE?(fe(`Vault file too large: ${i.stat.size} bytes for path: ${e}`),!1):!0:(fe(`File with image extension not found in vault: ${e}.`),!1)}elsereturnn&&fe(`Unsupported image format for potential vault path: .${n}. Supported formats: ${this.IMAGE_EXTENSIONS.join(", ")}`,e),!1;returnfe(`Could not determine image status for URL/path: ${e}`),!1}catch(n){returnfe(`Unexpected error in isImageUrl for "${e}":`,n),!1}}staticasynchandleVaultImage(e,r){try{if(e.stat.size>this.MAX_IMAGE_SIZE)returnfe(`Image too large: ${e.stat.size} bytes, skipping: ${e.path}`),null;letn=awaitr.readBinary(e),o=awaitthis.getMimeType(n,e.extension);if(!o.startsWith("image/"))returnfe(`Invalid MIME type: ${o}, skipping: ${e.path}`),null;leta=Buffer.from(n).toString("base64");return`data:${o};base64,${a}`}catch(n){returnfe("Error processing vault image:",n),null}}staticasynchandleWebImage(e){try{letr=awaitUs(e,{method:"GET",headers:{}});if(!r.ok)returnfe(`Failed to fetch image: ${r.statusText}, URL: ${e}`),null;letn=r.headers.get("content-type");if(!n?.startsWith("image/"))returnfe(`Invalid content type: ${n}, URL: ${e}`),null;leto=awaitr.arrayBuffer();if(o.byteLength>this.MAX_IMAGE_SIZE)returnfe(`Image too large: ${o.byteLength} bytes, URL: ${e}`),null;leta=Buffer.from(o).toString("base64");return`data:${n};base64,${a}`}catch(r){returnfe("Error converting web image to base64:",r),null}}staticasynchandleLocalImage(e,r){try{letn=decodeURIComponent(e.replace("app://","")),o=r.getAbstractFileByPath(n);if(!o||!(oinstanceofwN.TFile))returnfe(`Local image not found: ${n}`),null;if(o.stat.size>this.MAX_IMAGE_SIZE)returnfe(`Image too large: ${o.stat.size} bytes, path: ${n}`),null;leti=awaitr.readBinary(o),a=awaitthis.getMimeType(i,o.extension);if(!a.startsWith("image/"))returnfe(`Invalid MIME type: ${a}, path: ${n}`),null;letu=Buffer.from(i).toString("base64");return`data:${a};base64,${u}`}catch(n){returnfe("Error processing local image:",n),null}}staticasyncimageToBase64(e,r){if(e.startsWith("data:"))returne;if(e.startsWith("attachment:")){leto=e.substring(11),i=r.getAbstractFileByPath(o);returniinstanceofwN.TFile?awaitthis.handleVaultImage(i,r):(console.warn(`Could not find attachment file in vault: ${o}`),null)}if(e.startsWith("app://"))returnawaitthis.handleLocalImage(e,r);letn=r.getAbstractFileByPath(e);returnninstanceofwN.TFile?awaitthis.handleVaultImage(n,r):awaitthis.handleWebImage(e)}staticas
ExplicitChunks:`,s),console.log("Orama Chunks: ",l),console.log("Combined Chunks: ",c),console.log("Max Orama Score: ",f),m?console.log("Reranked Chunks: ",d):console.log("No reranking applied.")),d})}async rewriteQuery(r){try{let n=await this.queryRewritePrompt.format({question:r}),o=await yy(()=>ac.instance.getCurrentChainManager().chatModelManager.getChatModel().bind({temperature:0}).invoke(n));return o&&"content"in o?kR(o.content):(console.warn("Unexpected rewrittenQuery format. Falling back to original query."),r)}catch(n){return console.error("Error in rewriteQuery:",n),r}}async getExplicitChunks(r){let n=[];for(let o of r){let i=await ma.getInstance().getDb(),a=await eP.getDocsByPath(i,o.path);if(a){let s=a.map(u=>new tP({pageContent:u.document.content,metadata:{...u.document.metadata,score:u.score,path:u.document.path,mtime:u.document.mtime,ctime:u.document.ctime,title:u.document.title,id:u.document.id,embeddingModel:u.document.embeddingModel,tags:u.document.tags,extension:u.document.extension,created_at:u.document.created_at,nchars:u.document.nchars}}));n.push(...s)}}return n}async getOramaChunks(r,n,o){let i;try{i=await this.convertQueryToVector(r)}catch(l){throw console.error("Error in convertQueryToVector, please ensure your embedding model is working and has an adequate context length:",l,`
Query:`,r),l}let a=await ma.getInstance().getDb(),s={similarity:this.options.minSimilarityScore,limit:this.options.maxK,includeVectors:!0};if(n.length>0){let l;o||(o=.5),l=1-o;let c=!0;for(let d of n)if(!d.startsWith("#")){c=!1;break}c&&(ue().debug&&console.log("Tag only query detected, setting textWeight to 1 and vectorWeight to 0."),o=1,l=0),s.mode="hybrid",s.term=n.join(" "),s.vector={value:i,property:"embedding"},s.hybridWeights={text:o,vector:l}}else s.mode="vector",s.vector={value:i,property:"embedding"};if(this.options.timeRange){let{startTime:l,endTime:c}=this.options.timeRange,d=this.generateDailyNoteDateRange(l,c);ie("==== Daily note date range: ====",d[0],d[d.length-1]);let f=DC(d.join(", "),app.vault),m=(await this.getExplicitChunks(f)).map(S=>({...S,metadata:{...S.metadata,includeInContext:!0}}));ie("==== Modified time range: ====",l,c),s.where={mtime:{between:[l,c]}};let b=(await Xc(a,s)).hits.map(S=>new tP({pageContent:S.document.content,metadata:{...S.document.metadata,score:S.score,path:S.document.path,mtime:S.document.mtime,ctime:S.document.ctime,title:S.document.title,id:S.document.id,embeddingModel:S.document.embeddingModel,tags:S.document.tags,extension:S.document.extension,created_at:S.document.created_at,nchars:S.document.nchars}})),g=[...m,...b];return Array.from(new Set(g.map(S=>S.metadata.id))).map(S=>g.find(x=>x.metadata.id===S)).filter(S=>S!==void 0)}ue().debug&&console.log(`====OramaSearchParams:====
`,s);let u=await Xc(a,s);return!u||!u.hits?(console.warn("Search results or hits are undefined"),[]):u.hits.map(l=>!l||!l.document?(console.warn("Invalid hit or document in search results"),null):((typeof l.score!="number"||isNaN(l.score))&&console.warn("NaN/invalid score detected:",{score:l.score,path:l.document.path,title:l.document.title}),new tP({pageContent:l.document.content||"",metadata:{...l.document.metadata||{},score:l.score,path:l.document.path||"",mtime:l.document.mtime,ctime:l.document.ctime,title:l.document.title||"",id:l.document.id,embeddingModel:l.document.embeddingModel,tags:l.document.tags||[],extension:l.document.extension,created_at:l.document.created_at,nchars:l.document.nchars}}))).filter(l=>l!==null)}async convertQueryToVector(r){let o=await(await Xs.getInstance().getEmbeddingsAPI()).embedQuery(r);if(o.length===0)throw new Error("Query embedding returned an empty vector");return o}generateDailyNoteDateRange(r,n){let o=[],i=new Date(r),a=new Date(n),s=new Date(i);for(;s<=a;)o.push(`[[${s.toLocaleDateString("en-CA")}]]`),s.setDate(s.getDate()+1);return o}filterAndFormatChunks(r,n){let o=this.options.minSimilarityScore,i=r.filter(u=>{let l=u.metadata.score;return typeof l!="number"||isNaN(l)?!0:l>=o}),a=new Set(n.map(u=>u.pageContent)),s=[...n];for(let u of i){let l=u.pageContent;a.has(l)||(a.add(l),s.push(u))}return s.map(u=>({...u,metadata:{...u.metadata,includeInContext:!0}}))}};nr();var t1e=require("obsidian"),N1t=t=>{switch(t){case"@vault":return"Search through your vault for relevant information";case"@websearch":return"Search the web for information";case"@youtube":return"Get the transcript of a YouTube video. Example: @youtube <video_url>";case"@pomodoro":return"Start a pomodoro timer. Example: @pomodoro 25m";case"@composer":return"Edit existing notes or create new notes.";default:return""}},Eq=class{static async callTool(e,r){try{if(!e)throw new Error("Tool is undefined");let n=await e.call(r);return n??(console.warn(`Tool${e.name}returnednull/undefinedresult`),null)}catch(n){return console.error("Error calling tool:",n),n instanceof Error?new t1e.Notice(n.message):new t1e.Notice("An error occurred while executing the tool. Check console for details."),null}}};yn();var KNt=require("obsidian");Cl();ZA();Td();_g();function tJr(t){return"children"in t&&"path"in t}function rJr(t){return"path"in t&&!("children"in t)}function nJr(t){let e=t.split(".");return e.length>1&&e.pop()?.toLowerCase()||""}function r1e(t,e=!0){let r=[],n={},o={},{inclusions:i,exclusions:a}=rf();for(let u of t.children)if(rJr(u)){if(eu(u,i,a)){e&&r.push(u.name);let l=nJr(u.name)||"unknown";l&&(n[l]=(n[l]||0)+1)}}else if(tJr(u)){let l=r1e(u,e);if(Object.keys(l).length>0&&(o[u.name]=l[u.name],l[u.name].extensionCounts))for(let[c,d]of Object.entries(l[u.name].extensionCounts))n[c]=(n[c]||0)+d}let s={};return Object.keys(n).length>0&&(s.extensionCounts=n),e&&r.length>0&&(s.files=r),Object.keys(o).length>0&&(s.subFolders=o),Object.keys(s).length===0?{}:t.name?{[t.name]:s}:{vault:s}}var D1t=t=>Qm(async()=>{let e=r1e(t,!0),r=`AJSONrepresentsthefiletreeasanestedstructure:
`,n=JSON.stringify(e);if(n.length>5e5){let o=r1e(t,!1);return r+JSON.stringify(o)}return r+n},{name:"getFileTree",description:"Get the file tree as a nested structure of folders and files",schema:Wr.void()});$r();wT();mg();Mx();nr();ZA();Td();var n1e=Qm(async({timeRange:t,query:e,salientTerms:r})=>{if(await ma.getInstance().isIndexEmpty())throw new Rr(iJ);let o=t!==void 0,i=ue().maxSourceChunks<age?age:ue().maxSourceChunks;ue().debug&&console.log("returnAll:",o);let u=(await new jx({minSimilarityScore:o?0:.1,maxK:o?1e3:i,salientTerms:r,timeRange:t?{startTime:t.startTime.epoch,endTime:t.endTime.epoch}:void 0,textWeight:PVe,returnAll:o,useRerankerThreshold:.5}).getRelevantDocuments(e)).map(l=>({title:l.metadata.title,content:l.pageContent,path:l.metadata.path,score:l.metadata.score,rerank_score:l.metadata.rerank_score,includeInContext:l.metadata.includeInContext}));return JSON.stringify(u)},{name:"localSearch",description:"Search for notes based on the time range and query",schema:Wr.object({timeRange:Wr.object({startTime:Wr.any(),endTime:Wr.any()}).optional(),query:Wr.string().describe("The search query"),salientTerms:Wr.array(Wr.string()).describe("List of salient terms extracted from the query")})}),L1t=Qm(async()=>{try{let t=await ma.getInstance().indexVaultToVectorStore();return`Pleasereportwhethertheindexingwassuccessful.
Ifsuccessistrue,justsayitissuccessful.If0filesisindexed,saytherearenonewfilestoindex.`+JSON.stringify({success:!0,message:t===0?"No new files to index.":`Indexed${t}filesinthevault.`})}catch(t){return console.error("Error indexing vault:",t),JSON.stringify({success:!1,message:"An error occurred while indexing the vault."})}},{name:"indexVault",description:"Index the vault to the Copilot index"}),o1e=Qm(async({query:t,chatHistory:e})=>{try{let r=await mie(t,e),n=await Fi.getInstance().webSearch(r),o=n.response.citations||[],i=o.length>0?`
`,e),e}async handleError(e,r,n){let o=ei(e);fe("Error during LLM invocation:",o);let i=e?.response?.data?.error||o,a=i?.code||o,s="";if(e?.message?.includes("Invalid license key")?s="Invalid Copilot Plus license key. Please check your license key in settings.":a==="model_not_found"?s="You do not have access to this model or the model does not exist, please check with your API provider.":s=`${a}`,fe(i),r&&n){n("");let u=s.search("Troubleshooting URL");s=u!==-1?s.slice(0,u):s,o.search(/401|invalid|not valid/gi)!==-1&&(s=`Somethingwentwrong.PleasecheckifyouhavesetyourAPIkey.
ErrorDetails:`+s),r({message:s,isErrorMessage:!0,sender:e_,isVisible:!0,timestamp:Vl(new Date)})}else new KNt.Notice(s),fe(i)}},Hie=class extends e5{async run(e,r,n,o,i){let a=new Q6(n);try{let l=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),c=LR(l),d=[],f=Yb(),p=this.chainManager.chatModelManager.getChatModel();f&&d.push({role:oJ(p),content:f});for(let h of c)d.push({role:h.role,content:h.content});d.push({role:"user",content:e.message}),ie(`====FinalRequesttoAI====
`,d);let m=await yy(()=>this.chainManager.chatModelManager.getChatModel().stream(d,{signal:r.signal}));for await(let h of m){if(r.signal.aborted){ie("Stream iteration aborted",{reason:r.signal.reason});break}a.processChunk(h)}}catch(u){u.name==="AbortError"||r.signal.aborted?ie("Stream aborted by user",{reason:r.signal.reason}):await this.handleError(u,o,n)}let s=a.close();return r.signal.aborted&&r.signal.reason==="new-chat"?(n(""),""):this.handleResponse(s,e,r,o,n)}},Vie=class extends e5{async run(e,r,n,o,i){let a=new Q6(n);try{if(await this.chainManager.vectorStoreManager.isIndexEmpty())return this.handleResponse(iJ,e,r,o,n);let c=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),d=LR(c),f=e.message;d.length>0&&(f=e.message);let m=await new jx({minSimilarityScore:.01,maxK:ue().maxSourceChunks,salientTerms:[]}).getRelevantDocuments(f);this.chainManager.storeRetrieverDocuments(m);let h=m.map(P=>P.pageContent).join(`
`+h,S=g+y,x=this.chainManager.chatModelManager.getChatModel();S&&b.push({role:oJ(x),content:S});for(let P of d)b.push({role:P.role,content:P.content});b.push({role:"user",content:e.message}),ie(`====FinalRequesttoAI====
`,b);let O=await yy(()=>this.chainManager.chatModelManager.getChatModel().stream(b,{signal:r.signal}));for await(let P of O){if(r.signal.aborted){ie("VaultQA stream iteration aborted",{reason:r.signal.reason});break}a.processChunk(P)}}catch(u){u.name==="AbortError"||r.signal.aborted?ie("VaultQA stream aborted by user",{reason:r.signal.reason}):await this.handleError(u,o,n)}let s=a.close();return r.signal.aborted&&r.signal.reason==="new-chat"?(n(""),""):(s=this.addSourcestoResponse(s),this.handleResponse(s,e,r,o,n))}addSourcestoResponse(e){let r=yVe(this.chainManager.getRetrievedDocuments());if(r.length>0){let n=r.map(o=>`-[[${o}]]`).join(`
IMPORTANT:Maintainconsistencywithpreviousresponsesintheconversation.Ifyou've provided information about a person or topic before, use that same information in follow-up questions.`});for(let g of s)u.push({role:g.role,content:g.content});let d=this.chainManager.chatModelManager.getChatModel(),p=this.isMultimodalModel(d)?await this.buildMessageContent(e,r):e;u.push({role:"user",content:p});let m=p instanceof Array?p[0].text:p;ie("Enhanced user message: ",m),ie(`==== Final Request to AI ====
</project_context>`),e}};yo();nr();yn();qE();var Jle=require("obsidian");Cl();$r();qR();yo();nr();yn();u8();var RN="0.39.0";var GNt=!1,jN,sje,XYr,QYr,eZr,JNt,tZr,Kie,uje,YNt,lje,Gie,ZNt;function XNt(t,e={auto:!1}){if(GNt)throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${t.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(jN)throw new Error(`can't\`import '@anthropic-ai/sdk/shims/${t.kind}'\` after \`import '@anthropic-ai/sdk/shims/${jN}'\``);GNt=e.auto,jN=t.kind,sje=t.fetch,XYr=t.Request,QYr=t.Response,eZr=t.Headers,JNt=t.FormData,tZr=t.Blob,Kie=t.File,uje=t.ReadableStream,YNt=t.getMultipartRequestOptions,lje=t.getDefaultAgent,Gie=t.fileFromPath,ZNt=t.isFsReadStream}varJie=class{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}};functionQNt({manuallyImported:t}={}){lete=t?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from '@anthropic-ai/sdk'`:\n- `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)\n- `import '@anthropic-ai/sdk/shims/web'` (otherwise)\n",r,n,o,i;try{r=fetch,n=Request,o=Response,i=Headers}catch(a){thrownewError(`this environment is missing the following Web Fetch API type: ${a.message}. ${e}`)}return{kind:"web",fetch:r,Request:n,Response:o,Headers:i,FormData:typeofFormData<"u"?FormData:class{constructor(){thrownewError(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${e}`)}},Blob:typeofBlob<"u"?Blob:class{constructor(){thrownewError(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${e}`)}},File:typeofFile<"u"?File:class{constructor(){thrownewError(`file uploads aren't supported in this environment yet as 'File' is undefined. ${e}`)}},ReadableStream:typeofReadableStream<"u"?ReadableStream:class{constructor(){thrownewError(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${e}`)}},getMultipartRequestOptions:async(a,s)=>({...s,body:newJie(a)}),getDefaultAgent:a=>{},fileFromPath:()=>{thrownewError("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/anthropics/anthropic-sdk-typescript#file-uploads")},isFsReadStream:a=>!1}}jN||XNt(QNt(),{auto:!0});varOr=classextendsError{},cc=classtextendsOr{constructor(e,r,n,o){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=o,this.request_id=o?.["request-id"],this.error=r}staticmakeMessage(e,r,n){leto=r?.message?typeofr.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;returne&&o?`${e}${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}staticgenerate(e,r,n,o){if(!e||!o)returnnewwI({message:n,cause:Yie(r)});leti=r;returne===400?newr5(e,i,n,o):e===401?newn5(e,i,n,o):e===403?newo5(e,i,n,o):e===404?newi5(e,i,n,o):e===409?newa5(e,i,n,o):e===422?news5(e,i,n,o):e===429?newu5(e,i,n,o):e>=500?newl5(e,i,n,o):newt(e,i,n,o)}},ed=classextendscc{constructor({message:e}={}){super(void0,void0,e||"Request was aborted.",void0)}},wI=classextendscc{constructor({message:e,cause:r}){super(void0,void0,e||"Connection error.",void0),r&&(this.cause=r)}},Zq=classextendswI{constructor({message:e}={}){super({message:e??"Request timed out."})}},r5=classextendscc{},n5=classextendscc{},o5=classextendscc{},i5=classextendscc{},a5=classextendscc{},s5=classextendscc{},u5=classextendscc{},l5=classextendscc{};varZie=function(t,e,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(typeofe=="function"?t!==e||!o:!e.has(t))thrownewTypeError("Cannot write private member to an object whose class did not declare it");returnn==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r},NN=function(t,e,r,n){if(r==="a"&&!n)thrownewTypeError("Private accessor was defined without a getter");if(typeofe=="function"?t!==e||!n:!e.has(t))thrownewTypeError("Cannot read private member from an object whose class did not declare it");retur
`,"\r"]);uP.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function oZr(t,e){for(let o=e??0;o<t.length;o++){if(t[o]===10)return{preceding:o,index:o+1,carriage:!1};if(t[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function eDt(t){for(let n=0;n<t.length-1;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)return n+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)return n+4}return-1}function c5(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var Nx=class t{constructor(e,r){this.iterator=e,this.controller=r}static fromSSEResponse(e,r){let n=!1;async function*o(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let i=!1;try{for await(let a of iZr(e,r)){if(a.event==="completion")try{yield JSON.parse(a.data)}catch(s){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),s}if(a.event==="message_start"||a.event==="message_delta"||a.event==="message_stop"||a.event==="content_block_start"||a.event==="content_block_delta"||a.event==="content_block_stop")try{yield JSON.parse(a.data)}catch(s){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),s}if(a.event!=="ping"&&a.event==="error")throw cc.generate(void 0,`SSEError:${a.data}`,a.data,dje(e.headers))}i=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{i||r.abort()}}return new t(o,r)}static fromReadableStream(e,r){let n=!1;async function*o(){let a=new uP,s=c5(e);for await(let u of s)for(let l of a.decode(u))yield l;for(let u of a.flush())yield u}async function*i(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{for await(let s of o())a||s&&(yield JSON.parse(s));a=!0}catch(s){if(s instanceof Error&&s.name==="AbortError")return;throw s}finally{a||r.abort()}}return new t(i,r)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),o=i=>({next:()=>{if(i.length===0){let a=n.next();e.push(a),r.push(a)}return i.shift()}});return[new t(()=>o(e),this.controller),new t(()=>o(r),this.controller)]}toReadableStream(){let e=this,r,n=new TextEncoder;return new uje({async start(){r=e[Symbol.asyncIterator]()},async pull(o){try{let{value:i,done:a}=await r.next();if(a)return o.close();let s=n.encode(JSON.stringify(i)+`
`);o.enqueue(s)}catch(i){o.error(i)}},async cancel(){await r.return?.()}})}};async function*iZr(t,e){if(!t.body)throw e.abort(),new Or("Attempted to iterate over a response with no body");let r=new cje,n=new uP,o=c5(t.body);for await(let i of aZr(o))for(let a of n.decode(i)){let s=r.decode(a);s&&(yield s)}for(let i of n.flush()){let a=r.decode(i);a&&(yield a)}}async function*aZr(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?new TextEncoder().encode(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let i;for(;(i=eDt(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}var cje=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=sZr(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}};function sZr(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var uZr=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",lZr=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&d5(t),d5=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function";async function tDt(t,e,r){if(t=await t,lZr(t))return t;if(uZr(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=d5(o)?[await o.arrayBuffer()]:[o];return new Kie(i,e,r)}let n=await cZr(t);if(e||(e=fZr(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new Kie(n,e,r)}async function cZr(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(d5(t))e.push(await t.arrayBuffer());else if(pZr(t))for await(let r of t)e.push(r);else throw new Error(`Unexpecteddatatype:${typeoft};constructor:${t?.constructor?.name};props:${dZr(t)}`);return e}function dZr(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function fZr(t){return fje(t.name)||fje(t.filename)||fje(t.path)?.split(/[\\/]/).pop()}var fje=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},pZr=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",pje=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody";var hZr=function(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r},gZr=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Xie;async function aDt(t){let{response:e}=t;if(t.options.stream)return Xq("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):Nx.fromSSEResponse(e,t.controller);if(e.status===204)return null;if(t.options.__binaryResponse)return e;let r=e.headers.get("content-type");if(r?.includes("application/json")||r?.includes("application/vnd.api+json")){let i=await e.json();return Xq("response",e.status,e.url,e.headers,i),sDt(i,e)}let o=await e.text();return Xq("response",e.status,e.url,e.headers,o),o}function sDt(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var eae=class t extends Promise{constructor(e,r=aDt){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=r}_thenUnwrap(e){return new t(this.responsePromise,async r=>sDt(e(await this.parseResponse(r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}},tae=class{constructor({baseURL:e,maxRetries:r=2,timeout:n=6e5,httpAgent:o,fetch:i}){this.baseURL=e,this.maxRetries=mje("maxRetries",r),this.timeout=mje("timeout",n),this.httpAgent=o,this.f
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages?beta=true",{body:o,timeout:this._client._options.timeout??(o.stream?6e5:this._client._calculateNonstreamingTimeout(o.max_tokens)),...r,headers:{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void0,...r?.headers},stream:e.stream??!1})}stream(e,r){returndae.createMessage(this,e,r)}countTokens(e,r){let{betas:n,...o}=e;returnthis._client.post("/v1/messages/count_tokens?beta=true",{body:o,...r,headers:{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString(),...r?.headers}})}};xI.Batches=LN;xI.BetaMessageBatchesPage=tU;varLx=classextendsdc{constructor(){super(...arguments),this.models=newDN(this._client),this.messages=newxI(this._client)}};Lx.Models=DN;Lx.BetaModelInfosPage=Qq;Lx.Messages=xI;varFN=classextendsdc{create(e,r){returnthis._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...r,stream:e.stream??!1})}};varkN=classextendsdc{create(e,r){returnthis._client.post("/v1/messages/batches",{body:e,...r})}retrieve(e,r){returnthis._client.get(`/v1/messages/batches/${e}`,r)}list(e={},r){returnPg(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",oU,{query:e,...r})}delete(e,r){returnthis._client.delete(`/v1/messages/batches/${e}`,r)}cancel(e,r){returnthis._client.post(`/v1/messages/batches/${e}/cancel`,r)}asyncresults(e,r){letn=awaitthis.retrieve(e);if(!n.results_url)thrownewOr(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);returnthis._client.get(n.results_url,{...r,headers:{Accept:"application/binary",...r?.headers},__binaryResponse:!0})._thenUnwrap((o,i)=>eU.fromResponse(i.response,i.controller))}},oU=classextendsDx{};kN.MessageBatchesPage=oU;varaf=function(t,e,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(typeofe=="function"?t!==e||!o:!e.has(t))thrownewTypeError("Cannot write private member to an object whose class did not declare it");returnn==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r},vn=function(t,e,r,n){if(r==="a"&&!n)thrownewTypeError("Private accessor was defined without a getter");if(typeofe=="function"?t!==e||!n:!e.has(t))thrownewTypeError("Cannot read private member from an object whose class did not declare it");returnr==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Tg,CI,b5,fae,_5,v5,pae,w5,cP,S5,mae,hae,iU,gae,yae,wje,mDt,Sje,xje,Cje,Oje,hDt,gDt="__json_buf",bae=classt{constructor(){Tg.add(this),this.messages=[],this.receivedMessages=[],CI.set(this,void0),this.controller=newAbortController,b5.set(this,void0),fae.set(this,()=>{}),_5.set(this,()=>{}),v5.set(this,void0),pae.set(this,()=>{}),w5.set(this,()=>{}),cP.set(this,{}),S5.set(this,!1),mae.set(this,!1),hae.set(this,!1),iU.set(this,!1),gae.set(this,void0),yae.set(this,void0),Sje.set(this,e=>{if(af(this,mae,!0,"f"),einstanceofError&&e.name==="AbortError"&&(e=newed),einstanceofed)returnaf(this,hae,!0,"f"),this._emit("abort",e);if(einstanceofOr)returnthis._emit("error",e);if(einstanceofError){letr=newOr(e.message);returnr.cause=e,this._emit("error",r)}returnthis._emit("error",newOr(String(e)))}),af(this,b5,newPromise((e,r)=>{af(this,fae,e,"f"),af(this,_5,r,"f")}),"f"),af(this,v5,newPromise((e,r)=>{af(this,pae,e,"f"),af(this,w5,r,"f")}),"f"),vn(this,b5,"f").catch(()=>{}),vn(this,v5,"f").catch(()=>{})}getresponse(){returnvn(this,gae,"f")}getrequest_id(){returnvn(this,yae,"f")}asyncwithResponse(){lete=awaitvn(this,b5,"f");if(!e)thrownewError("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}staticfromReadableStream(e){letr=newt;returnr._run(()=>r._fromReadableStream(e)),r}staticcreateMessage(e,r,n){leto=newt;for(letiofr.messages)o._addMessageParam(i);returno._run(()=>o._createMessage(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages",{body:e,timeout:this._client._options.timeout??(e.stream?6e5:this._client._calculateNonstreamingTimeout(e.max_tokens)),...r,stream:e.stream??!1})}stream(e,r){return bae.createMessage(this,e,r)}countTokens(e,r){return this._client.post("/v1/messages/count_tokens",{body:e,...r})}},yDt={"claude-1.3":"November6th,2024","claude-1.3-100k":"November6th,2024","claude-instant-1.1":"November6th,2024","claude-instant-1.1-100k":"November6th,2024","claude-instant-1.2":"November6th,2024","claude-3-sonnet-20240229":"July21st,2025","claude-2.1":"July21st,2025","claude-2.0":"July21st,2025"};dP.Batches=kN;dP.MessageBatchesPage=oU;var OI=class extends dc{retrieve(e,r){return this._client.get(`/v1/models/${e}`,r)}list(e={},r){return Pg(e)?this.list({},e):this._client.getAPIList("/v1/models",$N,{query:e,...r})}},$N=class extends Dx{};OI.ModelInfosPage=$N;var bDt,mi=class extends tae{constructor({baseURL:e=nae("ANTHROPIC_BASE_URL"),apiKey:r=nae("ANTHROPIC_API_KEY")??null,authToken:n=nae("ANTHROPIC_AUTH_TOKEN")??null,...o}={}){let i={apiKey:r,authToken:n,...o,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&lDt())throw new Or(`It looks like you're running in a browser-like environment.
`);super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=newFN(this),this.messages=newdP(this),this.models=newOI(this),this.beta=newLx(this),this._options=i,this.apiKey=r,this.authToken=n}defaultQuery(){returnthis._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void0,"anthropic-version":"2023-06-01",...this._options.defaultHeaders}}validateHeaders(e,r){if(!(this.apiKey&&e["x-api-key"])&&r["x-api-key"]!==null&&!(this.authToken&&e.authorization)&&r.authorization!==null)thrownewError('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}authHeaders(e){letr=this.apiKeyAuth(e),n=this.bearerAuth(e);returnr!=null&&!f5(r)?r:n!=null&&!f5(n)?n:{}}apiKeyAuth(e){returnthis.apiKey==null?{}:{"X-Api-Key":this.apiKey}}bearerAuth(e){returnthis.authToken==null?{}:{Authorization:`Bearer ${this.authToken}`}}};bDt=mi;mi.Anthropic=bDt;mi.HUMAN_PROMPT=`
Assistant:`;mi.DEFAULT_TIMEOUT=6e5;mi.AnthropicError=Or;mi.APIError=cc;mi.APIConnectionError=wI;mi.APIConnectionTimeoutError=Zq;mi.APIUserAbortError=ed;mi.NotFoundError=i5;mi.ConflictError=a5;mi.RateLimitError=u5;mi.BadRequestError=r5;mi.AuthenticationError=n5;mi.InternalServerError=l5;mi.PermissionDeniedError=o5;mi.UnprocessableEntityError=s5;mi.toFile=tDt;mi.fileFromPath=Gie;mi.Completions=FN;mi.Messages=dP;mi.Models=OI;mi.ModelInfosPage=$N;mi.Beta=Lx;var{HUMAN_PROMPT:yWo,AI_PROMPT:bWo}=mi;gs();Qd();Dn();fx();Wm();Ec();Sm();mB();Km();gy();varx5=classextendsPR{staticlc_name(){return"AnthropicToolsOutputParser"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","anthropic","output_parsers"]}),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"keyName",{enumerable:!0,configurable:!0,writable:!0,value:void0}),Object.defineProperty(this,"returnSingle",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"zodSchema",{enumerable:!0,configurable:!0,writable:!0,value:void0}),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async_validateResult(e){letr=e;if(typeofe=="string")try{r=JSON.parse(e)}catch(o){thrownewvm(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(o.message)}`,e)}elser=e;if(this.zodSchema===void0)returnr;letn=awaitthis.zodSchema.safeParseAsync(r);if(n.success)returnn.data;thrownewvm(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.errors)}`,JSON.stringify(r,null,2))}asyncparseResult(e){letr=e.flatMap(i=>{let{message:a}=i;returnArray.isArray(a.content)?Pje(a.content)[0]:[]});if(r[0]===void0)thrownewError("No parseable tool calls provided to AnthropicToolsOutputParser.");let[n]=r;returnawaitthis._validateResult(n.args)}};functionPje(t){lete=[];for(letroft)r.type==="tool_use"&&e.push({name:r.name,args:r.input,id:r.id,type:"tool_call"});returne}function_Dt(t){if(t)returnt==="any"?{type:"any"}:t==="auto"?{type:"auto"}:typeoft=="string"?{type:"tool",name:t}:t}gs();functionvDt(t){returnt==null||typeoft!="object"||!("type"int)||t.type!=="image"||!("source"int)||typeoft.source!="object"||t.source==null||!("type"int.source)?!1:t.source.type==="base64"?!(!("media_type"int.source)||typeoft.source.media_type!="string"||!("data"int.source)||typeoft.source.data!="string"):t.source.type==="url"?!(!("url"int.source)||typeoft.source.url!="string"):!1}functionwDt(t){lete=lme({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};letr;try{r=newURL(t)}catch{thrownewError([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
`))}if(r.protocol==="http:"||r.protocol==="https:")return{type:"url",url:t};thrownewError([`Invalid image URL protocol: ${JSON.stringify(r.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
`))}functionLZr(t){lete=[];for(letroft)if(r._getType()==="tool")if(typeofr.content=="string"){letn=e[e.length-1];n?._getType()==="human"&&Array.isArray(n.content)&&"type"inn.content[0]&&n.content[0].type==="tool_result"?n.content.push({type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}):e.push(newOs({content:[{type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}]}))}elsee.push(newOs({content:[{type:"tool_result",content:Eje(r.content),tool_use_id:r.tool_call_id}]}));elsee.push(r);returne}functionSDt(t){if(t.id===void0)thrownewError('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:t.id,name:t.name,input:t.args}}varFZr={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){lete=lme({dataUrl:t.url,asTypedArray:!1});returne?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};thrownewError(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){lete=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};thrownewError(`Unsupported file mime type for file url source: ${t.mime_type}`)}elseif(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};thrownewError(`Unsupported file mime type for file text source: ${t.mime_type}`)}elseif(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};thrownewError(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}elsethrownewError(`Unsupported file source type: ${t.source_type}`)}};functionEje(t){lete=["tool_use","tool_result","input_json_delta"],r=["text","text_delta"];returntypeoft=="string"?t:t.map(o=>{if(jE(o))returnW4e(o,FZr);leti="cache_control"ino?o.cache_control:void0;if(o.type==="image_url"){leta;returntypeofo.image_url=="string"?a=wDt(o.image_url):a=wDt(o.image_url.url),{type:"image",source:a,...i?{cache_control:i}:{}}}else{if(vDt(o))returno;if
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=eXr(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},hU=class t{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){let r=this.decodeText(e);if(this.trailingCR&&(r="\r"+r,this.trailingCR=!1),r.endsWith("\r")&&(this.trailingCR=!0,r=r.slice(0,-1)),!r)return[];let n=t.NEWLINE_CHARS.has(r[r.length-1]||""),o=r.split(t.NEWLINE_REGEXP);return o.length===1&&!n?(this.buffer.push(o[0]),[]):(this.buffer.length>0&&(o=[this.buffer.join("")+o[0],...o.slice(1)],this.buffer=[]),n||(this.buffer=[o.pop()||""]),o)}decodeText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new fc(`Unexpected:receivednon-Uint8Array(${e.constructor.name})streamchunkinanenvironmentwithaglobal"Buffer"defined,whichthislibraryassumestobeNode.Pleasereportthiserror.`)}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new fc(`Unexpected:receivednon-Uint8Array/ArrayBuffer(${e.constructor.name})inawebplatform.Pleasereportthiserror.`)}throw new fc("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}};hU.NEWLINE_CHARS=new Set([`
`,"\r","\v","\f","","","","\x85","\u2028","\u2029"]);hU.NEWLINE_REGEXP=/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g;function eXr(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}function NDt(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var DDt=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",LDt=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Iae(t),Iae=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",tXr=t=>LDt(t)||DDt(t)||qje(t);async function Wje(t,e,r){if(t=await t,r??(r=LDt(t)?{lastModified:t.lastModified,type:t.type}:{}),DDt(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file"),new Oae([o],e,r)}let n=await rXr(t);if(e||(e=oXr(t)??"unknown_file"),!r.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new Oae(n,e,r)}async function rXr(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Iae(t))e.push(await t.arrayBuffer());else if(iXr(t))for await(let r of t)e.push(r);else throw new Error(`Unexpecteddatatype:${typeoft};constructor:${t?.constructor?.name};props:${nXr(t)}`);return e}function nXr(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function oXr(t){return Hje(t.name)||Hje(t.filename)||Hje(t.path)?.split(/[\\/]/).pop()}var Hje=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},iXr=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Kje=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody";var P5=async t=>{let e=await FDt(t.body);return $je(e,t)},FDt=async t=>{let e=new Fje;return await Promise.all(Object.entries(t||{}).map(([r,n])=>Vje(e,r,n))),e};var Vje=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Receivednullfor"${e}";topassnullinFormData,youmustusethestring'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(tXr(r)){let n=await Wje(r);t.append(e,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>Vje(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>Vje(t,`${e}[${n}]`,o)));else throw new TypeError(`Invalidvaluegiventoform,expectedastring,number,boolean,object,Array,FileorBlobbutgot${r}instead`)}};var sXr=function(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r},uXr=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Mae;async function zDt(t){let{response:e}=t;if(t.options.stream)return gU("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):Aae.fromSSEResponse(e,t.controller);if(e.status===204)return null;if(t.options.__binaryResponse)return e;let r=e.headers.get("content-type");if(r?.includes("application/json")||r?.includes("application/vnd.api+json")){let i=await e.json();return gU("response",e.status,e.url,e.headers,i),i}let o=await e.text();return gU("response",e.status,e.url,e.headers,o),o}var Rae=class t extends Promise{constructor(e
Received:${JSON.stringify(o,null,2)}`)};if(typeof o=="string")return o;if(Array.isArray(o)){let s=e(i),u=[];return o.forEach(l=>{if(l.type==="text"||l.type==="image_url")u.push(a(l,s));else throw new Error('Mistral only supports types "text" or "image_url" for complex message types.')}),u}throw new Error(`Messagecontentmustbeastringoranarray.
`;this.qaPrompt=xp.fromMessages([BE.fromTemplate(e)])}escapeTemplateString(e){returne.replace(/\{/g,"{{").replace(/\}/g,"}}")}getChatPrompt(){returnthis.chatPrompt}asyncgetQAPrompt({question:e,context:r,systemMessage:n}){returnawaitthis.qaPrompt.format({question:e,context:r,system_message:n})}};varvW=class{constructor(e,r){this.retrievedDocuments=[];this.chatMessages=[];this.chatMessages=[],this.app=e,this.vectorStoreManager=r,this.memoryManager=bW.getInstance(),this.chatModelManager=ED.getInstance(),this.promptManager=_W.getInstance(),this.initialize(),xa(async()=>{awaitthis.createChainWithNewModel()})}getRetrievedDocuments(){returnthis.retrievedDocuments}asyncinitialize(){awaitthis.createChainWithNewModel()}getChain(){returnthis.chain}getRetrievalChain(){returnthis.retrievalChain}validateChainType(e){if(e==null)thrownewError("No chain type set")}validateChatModel(){if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){lete="Chat model is not initialized properly, check your API key in Copilot setting and make sure you have API access.";thrownewJle.Notice(e),newError(e)}}validateChainInitialization(){(!this.chain||!mVe(this.chain))&&(console.error("Chain is not initialized properly, re-initializing chain: ",Fh()),this.createChainWithNewModel({},!1))}storeRetrieverDocuments(e){this.retrievedDocuments=e}asynccreateChainWithNewModel(e={},r=!0){letn=Fh(),o=Mc();if(n==="project"&&!o)return;leti=n==="project"?o?.projectModelKey:hJ();if(!i)thrownewJle.Notice("No model key found"),newError("No model key found");try{if(r){leta=tJ(i,ue().activeModels);if(a||(console.error("Resetting default model. No model configuration found for: ",i),a=Zb[0],i=a.name+"|"+a.provider),n==="project"&&!a.projectEnabled){letu=ue().activeModels.find(l=>l.enabled&&l.projectEnabled);if(u)a=u,i=u.name+"|"+u.provider,newJle.Notice(`Model ${a.name} is not available in project mode. Switching to ${u.name}.`);elsethrownewError("No project-enabled models available. Please enable a model for project mode in settings.")}lets={...a,...o?.modelConfigs};awaitthis.chatModelManager.setChatModel(s)}this.setChain(n,e),ie(`Setting model to ${i}`)}catch(a){fe(`createChainWithNewModel failed: ${a}`),ie(`modelKey: ${i}`)}}asyncsetChain(e,r={}){if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){console.error("setChain failed: No chat model set.");return}this.validateChainType(e);letn=this.chatModelManager.getChatModel(),o=this.memoryManager.getMemory(),i=this.promptManager.getChatPrompt();switch(e){case"llm_chain":{this.chain=d4.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),UR("llm_chain");break}case"vault_qa":{awaitthis.initializeQAChain(r);leta=newjx({minSimilarityScore:.01,maxK:ue().maxSourceChunks,salientTerms:[]});this.retrievalChain=d4.createConversationalRetrievalChain({llm:n,retriever:a,systemMessage:Yb()},this.storeRetrieverDocuments.bind(this),ue().debug),UR("vault_qa"),ue().debug&&(console.log("New Vault QA chain with hybrid retriever created for entire vault"),console.log("Set chain:","vault_qa"));break}case"copilot_plus":{awaitthis.initializeQAChain(r),this.chain=d4.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),UR("copilot_plus");break}case"project":{awaitthis.initializeQAChain(r),this.chain=d4.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),UR("project");break}default:this.validateChainType(e);break}}getChainRunner(){lete=Fh();switch(e){case"llm_chain":returnnewHie(this);case"vault_qa":returnnewVie(this);case"copilot_plus":returnnewt5(this);case"project":returnnewWie(this);default:thrownewError(`Unsupported chain type: ${e}`)}}asyncinitializeQAChain(e){e.refreshIndex&&awaitthis.vectorStoreManager.indexVaultToVectorStore()}asyncrunChain(e,r,n,o,i={}){let{debug:a=!1,ignoreSystemMessage:s=!1}=i;a&&console.log(`==== Step 0: Initial user message ====
`,e),this.validateChatModel(),this.validateChainInitialization();letu=this.chatModelManager.getChatModel();if(s||FR(u)){letc=xp.fromMessages([newGb("history"),Jb.fromTemplate("{input}")]);FR(u)&&(c=xp.fromMessages([[Pi,Yb()||""],c])),this.createChainWithNewModel({prompt:c},!1)}returnawaitthis.getChainRunner().run(e,r,n,o,i)}asyncupdateMemoryWithLoadedMessages(e){awaitthis.memoryManager.clearChatMemory();for(letr=0;r<e.length;r+=2){letn=e[r],o=e[r+1];n&&o&&n.sender===Pi&&awaitthis.memoryManager.getMemory().saveContext({input:n.message},{output:o.message})}}clearHistory(){this.chatMessages=[]}getChatMessages(){returnthis.chatMessages}setChatMessages(e){this.chatMessages=[...e]}addChatMessage(e){this.chatMessages.push(e)}};varac=classt{constructor(e,r,n){this.defaultProjectKey="defaultProjectKey";this.app=e,this.plugin=n,this.currentProjectId=null,this.chainMangerInstance=newvW(e,r),this.projectContextCache=tb.getInstance(),this.chatMessageCache=newMap,this.fileParserManager=newoI(Fi.getInstance(),this.app.vault,!0,null),t8e(async()=>{awaitthis.getCurrentChainManager().createChainWithNewModel()}),r8e(async()=>{HR()||awaitthis.getCurrentChainManager().createChainWithNewModel({refreshIndex:ue().indexVaultToVectorStore==="ON MODE SWITCH"&&(Fh()==="vault_qa"||Fh()==="copilot_plus")})}),xF(asynco=>{awaitthis.switchProject(o)}),this.setupProjectListChangeMonitor()}setupProjectListChangeMonitor(){xa(async(e,r)=>{if(!e||!r)return;letn=e.projectList||[],o=r.projectList||[];for(letiofo){leta=n.find(s=>s.id===i.id);a&&JSON.stringify(a)!==JSON.stringify(i)&&(awaitthis.compareAndUpdateCache(a,i),this.currentProjectId===i.id&&awaitPromise.all([this.loadProjectContext(i),this.getCurrentChainManager().createChainWithNewModel()]))}})}staticgetInstance(e,r,n){returnt.instance||(t.instance=newt(e,r,n)),t.instance}getCurrentChainManager(){returnthis.chainMangerInstance}asyncswitchProject(e){try{if(GE(!0),ie("Project loading started..."),!e){awaitthis.saveCurrentProjectMessage(),this.currentProjectId=null,awaitthis.loadNextProjectMessage(),this.refreshChatView();return}letr=e.id;if(this.currentProjectId===r)return;awaitthis.saveCurrentProjectMessage(),this.currentProjectId=r,awaitthis.loadNextProjectMessage(),awaitthis.getCurrentChainManager().createChainWithNewModel(),this.fileParserManager=newoI(Fi.getInstance(),this.app.vault,!0,e),awaitthis.loadProjectContext(e),this.refreshChatView(),ie(`Switched to project: ${e.name}`)}catch(r){throwfe(`Failed to switch project: ${r}`),r}finally{GE(!1)}}asyncsaveCurrentProjectMessage(){this.chatMessageCache.set(this.currentProjectId?this.currentProjectId:this.defaultProjectKey,this.getCurrentChainManager().getChatMessages()),awaitthis.plugin.autosaveCurrentChat()}asyncloadNextProjectMessage(){lete=this.getCurrentChainManager(),r=this.chatMessageCache.get(this.currentProjectId?this.currentProjectId:this.defaultProjectKey)??[];e.setChatMessages(r),awaitvN(r,e.memoryManager)}asyncloadProjectContext(e){try{if(!e.contextSource)returnMh(`[loadProjectContext] Project ${e.name}: No contextSource. Aborting.`),null;ie(`[loadProjectContext] Starting for project: ${e.name}`);letr=awaitthis.projectContextCache.get(e),n=r||{markdownContext:"",webContexts:{},youtubeContexts:{},fileContexts:{},timestamp:Date.now(),markdownNeedsReload:!0};r?ie(`[loadProjectContext] Project ${e.name}: Existing cache found. MarkdownNeedsReload: ${n.markdownNeedsReload}`):ie(`[loadProjectContext] Project ${e.name}: No existing cache found, building fresh context.`);let[o]=awaitPromise.all([this.processMarkdownFiles(e,n),this.processWebUrls(e,n),this.processYoutubeUrls(e,n)]);if(o.fileContexts){leti=Object.keys(o.fileContexts).length;if(ie(`[loadProjectContext] Project ${e.name}: Checking ${i} fileContexts for non-markdown processing.`),i>0){this.fileParserManager=newoI(Fi.getInstance(),this.app.vault,!0,e);leta=0;for(letsino.fileContexts){letu=this.app.vault.getAbstractFileByPath(s);if(uinstanceofwW.TFile&&u.extension!=="md"&&this.fileParserManager.supportsExtension(u.extension))tr
`).filter(m=>m.trim());for(let m of f)p.includes(m)||await this.projectContextCache.removeWebUrl(r,m)}let c=e.contextSource?.youtubeUrls||"",d=r.contextSource?.youtubeUrls||"";if(c!==d){let f=c.split(`
`).filter(m=>m.trim()),p=d.split(`
`).filter(m=>m.trim());for(let m of f)p.includes(m)||await this.projectContextCache.removeYoutubeUrl(r,m)}}catch(n){fe(`Errorcomparingprojectconfigurations:${n}`)}}refreshChatView(){let e=this.app.workspace.getLeavesOfType(Es)[0]?.view;e&&e.updateView()}async getProjectContext(e){let r=ue().projectList.find(o=>o.id===e);if(!r)return Mh(`[getProjectContext]ProjectnotfoundforID:${e}`),null;ie(`[getProjectContext]Gettingcontextforproject:${r.name}(ID:${e})`);let n=this.projectContextCache.getSync(r);if(!n||n.markdownNeedsReload){n?ie(`[getProjectContext]Project${r.name}:Markdownneedsreload.Triggeringfullload.`):ie(`[getProjectContext]Project${r.name}:Memorycachemiss.Triggeringfullload.`);let o=await this.loadProjectContext(r);if(!o)return fe(`[getProjectContext]Project${r.name}:loadProjectContextreturnednull.`),null;n=o}else ie(`[getProjectContext]Project${r.name}:MemorycachehitandmarkdownOK.Usingexistingcontext.`);return this.formatProjectContextWithFiles(n,r)}async formatProjectContextWithFiles(e,r){let n=[];if(e.markdownContext&&n.push(`##MarkdownFiles
`).filter(c=>c.trim());ie(`[processWebUrls]Project${e.name}:Found${o.length}URLsinconfig.`);let i=Object.keys(r.webContexts),a=o.filter(c=>!r.webContexts[c]);a.length>0&&ie(`[processWebUrls]Project${e.name}:Fetchingcontentfor${a.length}new/updated Web URLs.`);let s=i.filter(c=>!o.includes(c));if(s.length>0){ie(`[processWebUrls] Project ${e.name}: Removing ${s.length} obsolete Web URL contexts.`);for(let c of s)delete r.webContexts[c]}let u=a.map(async c=>{let d=await this.processWebUrlsContext(c);return d&&ie(`[processWebUrls] Project ${e.name}: Successfully fetched content for URL: ${c.substring(0,50)}...`),{url:c,context:d}});return(await Promise.all(u)).forEach(c=>{c&&c.context?r.webContexts[c.url]=c.context:c&&!c.context&&Mh(`[processWebUrls] Project ${e.name}: Fetched empty content for Web URL: ${c.url}`)}),ie(`[processWebUrls] Completed for project: ${e.name}. Total Web contexts: ${Object.keys(r.webContexts).length}`),r}async processYoutubeUrls(e,r){ie(`[processYoutubeUrls] Starting for project: ${e.name}`);let n=e.contextSource?.youtubeUrls?.trim()||"";if(!n)return Object.keys(r.youtubeContexts).length>0&&(ie(`[processYoutubeUrls] Project ${e.name}: Clearing all YouTube contexts as none are configured.`),r.youtubeContexts={}),r;let o=n.split(`
`)&&(o=o.slice(0,-1)),o}returnr}},Xle=class{constructor(){this.processors=[];this.processors.push(newrFe),this.processors.push(neweFe),this.processors.push(newtFe)}process(e,r,n,o){leta={prefix:e,suffix:r,completion:n,context:o};for(letsofthis.processors)a.completion=s.process(a);returna.completion}};f4();varv3t=require("obsidian");functionw3t(t,e=20){letr=app.metadataCache.getFileCache(t),n=[];if(r?.links)for(letoofr.links){leti=app.metadataCache.getFirstLinkpathDest(o.link,t.path);if(i&&(n.push(i),n.length>=e))break}if(r?.embeds&&n.length<e)for(letoofr.embeds){leti=app.metadataCache.getFirstLinkpathDest(o.link,t.path);if(i&&(n.push(i),n.length>=e))break}return[...newSet(n)]}functionS3t(t,e=20){letr=[],n=app.metadataCache.getBacklinksForFile(t);if(n?.data)for(let[o]ofn.data){leti=app.vault.getAbstractFileByPath(o);if(iinstanceofv3t.TFile&&(r.push(i),r.length>=e))break}returnr}rie();nr();varnFe=require("obsidian"),Xwn=.4,Qwn=20,x3t=.7,Qle=.3;asyncfunctione0n(t,e){letr=ue().debug,n=awaiteP.getDocsByPath(e,t);if(!n)returnr&&console.log("No hits found for note:",t),[];leto=[];for(letiofn){if(!i?.document?.embedding){r&&console.log("No embedding found for note:",t);continue}o.push(i.document.embedding)}returno}functiont0n(t){if(t.length===0)return[];lete=t[0].length,r=Array(e).fill(0);returnt.forEach(n=>{n.forEach((o,i)=>{r[i]+=o/e})}),r}functionr0n(t,e){letr=newMap;for(letnoft){leto=r.get(n.document.path);o?n.score>o&&r.set(n.document.path,n.score):r.set(n.document.path,n.score)}returnr.delete(e),r}asyncfunctionn0n({db:t,filePath:e}){letr=ue().debug,n=awaite0n(e,t),o=t0n(n);if(o.length===0)returnr&&console.log("No embeddings found for note:",e),newMap;leti=awaiteP.getDocsByEmbedding(t,o,{limit:Qwn,similarity:Xwn});returnr0n(i,e)}functiono0n(t){lete=newMap,n=w3t(t).map(a=>a.path);for(letaofn)e.set(a,{links:!0,backlinks:!1});leti=S3t(t).map(a=>a.path);for(letaofi)e.has(a)?e.set(a,{links:!0,backlinks:!0}):e.set(a,{links:!1,backlinks:!0});returne}functioni0n(t,e){letr=newMap,n=x3t+Qle;for(let[o,i]oft)r.set(o,i*x3t/n);for(let[o,i]ofe){leta=0;i.links&&i.backlinks?a=Qle:(i.links||i.backlinks)&&(a=Qle*.8),r.set(o,(r.get(o)??0)+a)}returnr}asyncfunctiontce({db:t,filePath:e}){letr=app.vault.getAbstractFileByPath(e);if(!(rinstanceofnFe.TFile))return[];letn=awaitn0n({db:t,filePath:e}),o=o0n(r),i=i0n(n,o);returnArray.from(i.entries()).sort((s,u)=>{letl=s[0],c=u[0],d=ece(n.get(l)??0),f=ece(n.get(c)??0);returnd!==f?f-d:u[1]-s[1]}).map(([s,u])=>{letl=app.vault.getAbstractFileByPath(s);returnlinstanceofnFe.TFile?{document:{path:s,title:l.basename},metadata:{score:u,similarityScore:n.get(s),hasOutgoingLinks:o.get(s)?.links??!1,hasBacklinks:o.get(s)?.backlinks??!1}}:null}).filter(s=>s!==null)}functionece(t){returnt>.7?3:t>.55?2:1}Mx();varC3t=require("obsidian"),a0n={cjk:[[19968,40959],[13312,19903],[131072,173791],[173824,177983],[177984,178207],[178208,183983]],japanese:[[12352,12447],[12448,12543]],korean:[[44032,55215],[4352,4607]],other:[[3584,3711],[1536,1791],[2304,2431],[2432,2559],[2688,2815],[2944,3071]]};functions0n(t,e){letr=t.codePointAt(0);returnr?e.some(([n,o])=>r>=n&&r<=o):!1}functionO3t(t){lete=t.replace(/[\p{Emoji}\p{Symbol}\p{Punctuation}]/gu,"");if(!e)return!1;for(letrofe)if(Object.values(a0n).some(n=>s0n(r,n)))return!0;return!1}functionP3t(t,e){letr="",n="",o=Math.max(0,e.line-5);for(letu=o;u<e.line;u++)r+=t.getLine(u)+`
`).pop()||"";if(/^\s*[-*+]\s/.test(r))return"UnorderedList";if(/^\s*\d+\.\s/.test(r))return"NumberedList";if(/^\s*[-*+]\s\[[ x]\]\s/.test(r))return"TaskList";if(e.includes("```")&&(e.split("```").length-1)%2===1)return"CodeBlock"}triggerCompletion(){this.isActive&&(this.clearActiveRequests(),this.forceFetch())}clearActiveRequests(){this.activeRequests.size>0&&this.activeRequests.clear()}getWordCompletionManager(){return this.wordCompletionManager}setCacheEnabled(e){this.cacheEnabled=e,e||this.cache.clear()}getCacheEnabled(){return this.cacheEnabled}};var oce=class t{constructor(e){this.plugin=e;let r=ue();this.cmIntegration=nce.getInstance({delay:Nh.DELAY_MS,minTriggerLength:Nh.MIN_TRIGGER_LENGTH,maxContextLength:Nh.MAX_CONTEXT_LENGTH}),this.unsubscribeSettings=xa((o,i)=>{let a=(o.enableAutocomplete||o.enableWordCompletion)&&o.isPlusUser===!0,s=(i.enableAutocomplete||i.enableWordCompletion)&&i.isPlusUser===!0;a!==s&&this.cmIntegration.setActive(s)});let n=(r.enableAutocomplete||r.enableWordCompletion)&&r.isPlusUser===!0;this.cmIntegration.setActive(n),this.registerExtension()}static getInstance(e){return t.instance||(t.instance=new t(e)),t.instance}registerExtension(){try{this.plugin.registerEditorExtension([this.cmIntegration.getExtension()])}catch(e){fe("[Copilot Autocomplete] Failed to register CodeMirror extension:",e)}}destroy(){this.unsubscribeSettings(),this.cmIntegration.setActive(!1),this.cmIntegration.destroy()}};Cl();Fd();var T3t=require("obsidian"),ice=class extends T3t.Modal{constructor(r,n){super(r);this.placeholderText="Please enter your custom ad-hoc prompt here, press enter to send.";this.onSubmit=n}onOpen(){let{contentEl:r}=this,n=createFragment(i=>{i.createEl("strong",{text:"- {} represents the selected text (not required). "}),i.createEl("br"),i.createEl("strong",{text:"- {[[Note Title]]} represents a note. "}),i.createEl("br"),i.createEl("strong",{text:"- {activeNote} represents the active note. "}),i.createEl("br"),i.createEl("strong",{text:"- {FolderPath} represents a folder of notes. "}),i.createEl("br"),i.createEl("strong",{text:"- {#tag1, #tag2} represents ALL notes with ANY of the specified tags in their property (an OR operation). "}),i.createEl("br"),i.createEl("br"),i.appendText("Tip: turn on debug mode to show the processed prompt in the chat window."),i.createEl("br"),i.createEl("br")});r.appendChild(n);let o=r.createEl("textarea",{attr:{placeholder:this.placeholderText}});o.style.width="100%",o.style.height="100px",o.style.padding="10px",o.style.resize="vertical",o.addEventListener("input",i=>{this.result=i.target.value}),o.addEventListener("keydown",i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),this.close(),this.onSubmit(this.result))})}onClose(){let{contentEl:r}=this;r.empty()}};F8();var ZI=require("obsidian"),ace=class extends ZI.Modal{constructor(e,r){super(e),this.plugin=r}onOpen(){let{contentEl:e}=this;e.empty(),e.createEl("h2",{text:"Debug: Search OramaDB"});let r=e.createEl("p");r.innerHTML='Enter a JSON search params object. Example:<br><pre>{<br> "term": "#tag",<br> "mode": "hybrid",<br> "limit": 10,<br> "includeVectors": true<br>}</pre>',this.searchInput=e.createEl("textarea",{attr:{placeholder:"Enter search params JSON...",rows:"10",style:"width: 100%; min-height: 200px; margin: 10px 0; padding: 10px; font-family: monospace;"}}),e.createEl("div",{cls:"search-button-container"}).createEl("button",{text:"Search",cls:"mod-cta"}).addEventListener("click",async()=>{try{let i=JSON.parse(this.searchInput.value);i.vector?.value&&!Array.isArray(i.vector.value)&&(i.vector.value=Object.values(i.vector.value));let a=await this.plugin.vectorStoreManager.getDb();if(!a){new ZI.Notice("Database not found");return}let s=await Xc(a,i),u=["## Search Parameters","```json",JSON.stringify(i,null,2),"```","","## Results",`Totalhits:${s.hits.length}`,"","### Hits","```json",JSON.stringify(s.hits,null,2),"```"].join(`
`),l="OramaDB-Debug-Search.md",c=this.app.vault.getAbstractFileByPath(l);c instanceof ZI.TFile?await this.app.vault.modify(c,u):await this.app.vault.create(l,u);let d=this.app.vault.getAbstractFileByPath(l);d instanceof ZI.TFile&&(await this.app.workspace.getLeaf().openFile(d),this.close())}catch(i){console.error("Error in debug search:",i),new ZI.Notice("Error executing search. Check console for details.")}})}onClose(){let{contentEl:e}=this;e.empty()}};yn();var OW=require("obsidian"),sce=class extends OW.Modal{constructor(e,r){super(e),this.plugin=r}onOpen(){let{contentEl:e}=this;e.empty(),e.createEl("h2",{text:"Inspect Copilot Index by Note Paths"}),this.searchInput=e.createEl("textarea",{attr:{placeholder:`Enternotepathsasmarkdownlist:
-[[Note2]]`,rows:"10",style:"width: 100%; min-height: 200px; margin: 10px 0; padding: 10px; font-family: monospace;"}}),e.createEl("div",{cls:"search-button-container"}).createEl("button",{text:"Show Index Data",cls:"mod-cta"}).addEventListener("click",async()=>{let o=this.searchInput.value,i=DC(o,this.app.vault).map(a=>a.path);if(i.length===0){new OW.Notice("No valid note paths found. Use format: - [[Note Name]]");return}try{let s=await(await this.plugin.vectorStoreManager.getDbOps()).getDocsJsonByPaths(i),u="CopilotDB-Search-Results.md",l=["## Searched Paths",...i.map(f=>`-[[${f}]]`),"","## Index Data","```json",JSON.stringify(s,null,2),"```"].join(`
`),c=this.app.vault.getAbstractFileByPath(u);c?await this.app.vault.modify(c,l):await this.app.vault.create(u,l);let d=this.app.vault.getAbstractFileByPath(u);d&&await this.app.workspace.getLeaf().openFile(d),this.close()}catch(a){console.error("Error searching DB:",a),new OW.Notice("Error searching database. Check console for details.")}})}onClose(){let{contentEl:e}=this;e.empty()}};var PW=require("obsidian"),uce=class extends PW.Modal{constructor(r,n){super(r);this.filePaths="";this.onSubmit=n}onOpen(){let{contentEl:r}=this;r.createEl("h2",{text:"Remove Files from Copilot Index"});let n=r.createDiv({cls:"remove-files-container"});new PW.Setting(n).setName("File paths").setDesc("Paste the markdown list of file paths to remove from the index. You can get the list by running the command `Listallindexedfiles`.").setClass("remove-files-setting").addTextArea(o=>o.setPlaceholder(`-[[path/to/file1.md]]
`})}onClose(){let{contentEl:r}=this;r.empty()}};_g();nr();var Ji=require("obsidian");c2();$r();function df(t,e,r){t.addCommand({id:e,name:uge[e],callback:r})}function A3t(t,e,r){t.addCommand({id:e,name:uge[e],editorCallback:r})}function iFe(t,e,r){A3t(t,Br.COUNT_WORD_AND_TOKENS_SELECTION,async n=>{let o=await n.getSelection(),i=o.split(" ").length,a=await t.projectManager.getCurrentChainManager().chatModelManager.countTokens(o);new Ji.Notice(`Selectedtextcontains${i}wordsand${a}tokens.`)}),df(t,Br.COUNT_TOTAL_VAULT_TOKENS,async()=>{try{let n=await e1t(t.app),o=await t.projectManager.getCurrentChainManager().chatModelManager.countTokens(n);new Ji.Notice(`Totaltokensinyourvault:${o}`)}catch(n){console.error("Error counting tokens: ",n),new Ji.Notice("An error occurred while counting tokens.")}}),df(t,Br.TOGGLE_COPILOT_CHAT_WINDOW,()=>{t.toggleView()}),df(t,Br.OPEN_COPILOT_CHAT_WINDOW,()=>{t.activateView()}),df(t,Br.NEW_CHAT,()=>{t.newChat()}),df(t,Br.APPLY_ADHOC_PROMPT,async()=>{new ice(t.app,async o=>{try{t.processCustomPrompt(Br.APPLY_ADHOC_PROMPT,o)}catch(i){console.error(i),new Ji.Notice("An error occurred.")}}).open()}),df(t,Br.CLEAR_LOCAL_COPILOT_INDEX,async()=>{await t.vectorStoreManager.clearIndex()}),df(t,Br.GARBAGE_COLLECT_COPILOT_INDEX,async()=>{try{let n=await t.vectorStoreManager.garbageCollectVectorStore();new Ji.Notice(`${n}documentsremovedfromCopilotindex.`)}catch(n){console.error("Error garbage collecting the Copilot index:",n),new Ji.Notice("An error occurred while garbage collecting the Copilot index.")}}),df(t,Br.INDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let n=await t.vectorStoreManager.indexVaultToVectorStore();new Ji.Notice(`${n}vaultfilesindexedtoCopilotindex.`)}catch(n){console.error("Error indexing vault to Copilot index:",n),new Ji.Notice("An error occurred while indexing vault to Copilot index.")}}),df(t,Br.FORCE_REINDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let n=await t.vectorStoreManager.indexVaultToVectorStore(!0);new Ji.Notice(`${n}vaultfilesre-indexedtoCopilotindex.`)}catch(n){console.error("Error re-indexing vault to Copilot index:",n),new Ji.Notice("An error occurred while re-indexing vault to Copilot index.")}}),df(t,Br.LOAD_COPILOT_CHAT_CONVERSATION,()=>{t.loadCopilotChatHistory()}),df(t,Br.LIST_INDEXED_FILES,async()=>{try{let n=await t.vectorStoreManager.getIndexedFiles(),o=new Set(n),i=t.app.vault.getMarkdownFiles(),a=new Set,s=new Set,u=new Set,l=await t.vectorStoreManager.getDbOps();for(let h of i){let b=await t.app.vault.cachedRead(h);!b||b.trim().length===0?a.add(h.path):o.has(h.path)?await l.hasEmbeddings(h.path)||u.add(h.path):s.add(h.path)}if(n.length===0&&a.size===0&&s.size===0){new Ji.Notice("No files found to list.");return}let c=["# Copilot Files Status",`-Indexedfiles:${n.length}`,`-Filesmissingembeddings:${u.size}`,`-Unindexedfiles:${s.size}`,`-Emptyfiles:${a.size}`,"","## Indexed Files",...n.map(h=>{let b=u.has(h);return`-[[${h}]]${b?" *(embedding missing)*":""}`}),"","## Unindexed Files",...s.size>0?Array.from(s).sort().map(h=>`-[[${h}]]`):["No unindexed files found."],"","## Empty Files",...a.size>0?Array.from(a).sort().map(h=>`-[[${h}]]`):["No empty files found."]].join(`
`),f=`${`Copilot-Indexed-Files-${newDate().toLocaleDateString().replace(/\//g,"-")}.md`}`,p=t.app.vault.getAbstractFileByPath(f);p instanceof Ji.TFile?await t.app.vault.modify(p,c):await t.app.vault.create(f,c);let m=t.app.vault.getAbstractFileByPath(f);m instanceof Ji.TFile&&(await t.app.workspace.getLeaf().openFile(m),new Ji.Notice(`Listed${n.length}indexedfiles`))}catch(n){console.error("Error listing indexed files:",n),new Ji.Notice("Failed to list indexed files.")}}),r.debug&&(df(t,Br.INSPECT_COPILOT_INDEX_BY_NOTE_PATHS,()=>{new sce(t.app,t).open()}),df(t,Br.SEARCH_ORAMA_DB,()=>{new ace(t.app,t).open()}),df(t,Br.REMOVE_FILES_FROM_COPILOT_INDEX,async()=>{new uce(t.app,async n=>{let o=await t.vectorStoreManager.getDbOps();try{for(let i of n)await o.removeDocs(i);await o.saveDB(),new Ji.Notice(`Successfullyremoved${n.length}filesfromtheindex.`)}catch(i){console.error("Error removing files from index:",i),new Ji.Notice("An error occurred while removing files from the index.")}}).open()})),df(t,Br.CLEAR_COPILOT_CACHE,async()=>{try{await t.fileParserManager.clearPDFCache(),await tb.getInstance().clearAllCache(),await Cq.getInstance().clear();let{AutocompleteCache:o}=await Promise.resolve().then(()=>(GLe(),g3t));o.getInstance().clear(),new Ji.Notice("All Copilot caches cleared successfully")}catch(n){console.error("Error clearing Copilot caches:",n),new Ji.Notice("Failed to clear Copilot caches")}}),df(t,Br.TOGGLE_AUTOCOMPLETE,()=>{let o=!ue().enableAutocomplete;dt("enableAutocomplete",o),new Ji.Notice(`Copilotautocomplete${o?"enabled":"disabled"}`)}),A3t(t,Br.ADD_SELECTION_TO_CHAT_CONTEXT,async n=>{let o=Fh();if(o!=="copilot_plus"&&o!=="project"){new Ji.Notice("Selected text context is only available in Copilot Plus and Project modes");return}let i=n.getSelection();if(!i){new Ji.Notice("No text selected");return}let a=t.app.workspace.getActiveFile();if(!a){new Ji.Notice("No active file");return}let s=n.listSelections()[0];if(!s){new Ji.Notice("Could not determine selection range");return}let u=s.anchor.line+1,l=s.head.line+1,c={id:bC(),content:i,noteTitle:a.basename,notePath:a.path,startLine:Math.min(u,l),endLine:Math.max(u,l)};o8e(c),t.activateView()})}Cl();Fd();var aFe="{copilot-selection}";var XI={title:"",content:"",showInContextMenu:!1,showInSlashMenu:!1,order:Number.MAX_SAFE_INTEGER,modelKey:"",lastUsedMs:0},ID="copilot-command-context-menu-enabled",MD="copilot-command-slash-enabled",RD="copilot-command-context-menu-order",jD="copilot-command-model-key",ND="copilot-command-last-used",I3t=[{title:"Fix grammar and spelling",content:"Fix the grammar and spelling of {}. Preserve all formatting, line breaks, and special characters. Do not add or remove any content. Return only the corrected text.",showInContextMenu:!0,showInSlashMenu:!0,order:1e3,modelKey:"",lastUsedMs:0},{title:"Translate to Chinese",content:`Translate{}intoChinese:
Returnonlythetranslatedtext.`,showInContextMenu:!0,showInSlashMenu:!0,order:1010,modelKey:"",lastUsedMs:0},{title:"Summarize",content:"Create a bullet-point summary of {}. Each bullet point should capture a key point. Return only the bullet-point summary.",showInContextMenu:!0,showInSlashMenu:!0,order:1020,modelKey:"",lastUsedMs:0},{title:"Simplify",content:"Simplify {} to a 6th-grade reading level (ages 11-12). Use simple sentences, common words, and clear explanations. Maintain the original key concepts. Return only the simplified text.",showInContextMenu:!0,showInSlashMenu:!0,order:1030,modelKey:"",lastUsedMs:0},{title:"Explain like I am 5",content:`Explain{}insimpletermsthata5-year-oldwouldunderstand:
Returnonlytheexpandedtext.`,showInContextMenu:!0,showInSlashMenu:!0,order:1070,modelKey:"",lastUsedMs:0},{title:"Generate table of contents",content:"Generate a hierarchical table of contents for {}. Use appropriate heading levels (H1, H2, H3, etc.). Include page numbers if present. Return only the table of contents.",showInContextMenu:!1,showInSlashMenu:!1,order:1080,modelKey:"",lastUsedMs:0},{title:"Generate glossary",content:'Create a glossary of important terms, concepts, and phrases from {}. Format each entry as "Term: Definition". Sort entries alphabetically. Return only the glossary.',showInContextMenu:!1,showInSlashMenu:!1,order:1090,modelKey:"",lastUsedMs:0},{title:"Remove URLs",content:"Remove all URLs from {}. Preserve all other content and formatting. URLs may be in various formats (http, https, www). Return only the text with URLs removed.",showInContextMenu:!1,showInSlashMenu:!1,order:1100,modelKey:"",lastUsedMs:0},{title:"Rewrite as tweet",content:`Rewrite{}asasingletweetwiththeserequirements:
1.Maximum280characters
2.Useconcise,impactfullanguage
3.Maintainthecoremessage
Returnonlythetweettext.`,showInContextMenu:!1,showInSlashMenu:!1,order:1110,modelKey:"",lastUsedMs:0},{title:"Rewrite as tweet thread",content:`Convert{}intoaTwitterthreadfollowingtheserules:
${u}`,s.files.push(r))}else new GU.Notice("No active note found.");else if(a.startsWith("#")){let u=a.slice(1).split(",").map(d=>d.trim()),l=await pVe(e,u),c=[];for(let d of l){let f=await mF(d,e);f&&(c.push(`##${eJ(d)}
`)}}returne}asyncprocessContextNotes(e,r,n,o,i,a,s){letu="",l=async(d,f=p4)=>{try{if(e.has(d.path)){console.log(`Skipping note ${d.path} as it was included via custom prompt.`);return}if(console.log(`Processing note: ${d.path}, extension: ${d.extension}, chain: ${s}`),!r.supportsExtension(d.extension)){console.warn(`Unsupported file type: ${d.extension}`);return}if(s!=="copilot_plus"&&d.extension!=="md"&&d.extension!=="canvas"){console.warn(`File type ${d.extension} requires Copilot Plus mode for context processing.`);return}letp=awaitr.parseFile(d,n);d.extension==="md"&&s==="copilot_plus"&&(p=awaitthis.processEmbeddedPDFs(p,n,r)),u+=`
</selected_text>`}returnr}};varrde=require("obsidian");wT();varlm=classt{staticgetInstance(){returnt.instance||(t.instance=newt),t.instance}asynccreateCommand(e,r,n=!1){n||lce(e);leto=QI(),i=DD(e);awaitapp.vault.adapter.exists(o)||awaitapp.vault.createFolder(o);lets=awaitapp.vault.create(i,r);awaitapp.fileManager.processFrontMatter(s,u=>{u[ID]=!1,u[MD]=!1,u[RD]=Number.MAX_SAFE_INTEGER,u[jD]="",u[ND]=0})}asyncrecordUsage(e){this.updateCommand({...e,lastUsedMs:Date.now()},e.title)}asyncupdateCommand(e,r,n=!1){n||TW(e,r);leto=app.vault.getAbstractFileByPath(DD(e.title));if(e.title!==r){leti=DD(e.title);if(app.vault.getAbstractFileByPath(i))thrownewRr("Error saving custom prompt. Please check if the title already exists.");lets=DD(r),u=app.vault.getAbstractFileByPath(s);uinstanceofrde.TFile&&(awaitapp.vault.rename(u,i),o=u)}o||(awaitthis.createCommand(e.title,e.content,n),o=app.vault.getAbstractFileByPath(DD(e.title))),oinstanceofrde.TFile&&(awaitapp.vault.modify(o,e.content),awaitapp.fileManager.processFrontMatter(o,i=>{i[ID]=e.showInContextMenu,i[MD]=e.showInSlashMenu,i[RD]=e.order,i[jD]=e.modelKey,i[ND]=e.lastUsedMs}))}asyncupdateCommands(e){cce(e),awaitPromise.all(e.map(r=>this.updateCommand(r,r.title,!0)))}asyncdeleteCommand(e){EW(e.title);letr=app.vault.getAbstractFileByPath(DD(e.title));rinstanceofrde.TFile&&awaitapp.vault.delete(r)}};nr();yn();bn();varCM=require("obsidian"),at=F(X());varwn=F(X()),Mi=F(r5t());functionxM(t,e,r,n){functiono(i){returniinstanceofr?i:newr(function(a){a(i)})}returnnew(r||(r=Promise))(function(i,a){functions(c){try{l(n.next(c))}catch(d){a(d)}}functionu(c){try{l(n.throw(c))}catch(d){a(d)}}functionl(c){c.done?i(c.value):o(c.value).then(s,u)}l((n=n.apply(t,e||[])).next())})}varpOn=newMap([["1km","application/vnd.1000minds.decision-model+xml"],["3dml","text/vnd.in3d.3dml"],["3ds","image/x-3ds"],["3g2","video/3gpp2"],["3gp","video/3gp"],["3gpp","video/3gpp"],["3mf","model/3mf"],["7z","application/x-7z-compressed"],["7zip","application/x-7z-compressed"],["123","application/vnd.lotus-1-2-3"],["aab","application/x-authorware-bin"],["aac","audio/x-acc"],["aam","application/x-authorware-map"],["aas","application/x-authorware-seg"],["abw","application/x-abiword"],["ac","application/vnd.nokia.n-gage.ac+xml"],["ac3","audio/ac3"],["acc","application/vnd.americandynamics.acc"],["ace","application/x-ace-compressed"],["acu","application/vnd.acucobol"],["acutc","application/vnd.acucorp"],["adp","audio/adpcm"],["aep","application/vnd.audiograph"],["afm","application/x-font-type1"],["afp","application/vnd.ibm.modcap"],["ahead","application/vnd.ahead.space"],["ai","application/pdf"],["aif","audio/x-aiff"],["aifc","audio/x-aiff"],["aiff","audio/x-aiff"],["air","application/vnd.adobe.air-application-installer-package+zip"],["ait","application/vnd.dvb.ait"],["ami","application/vnd.amiga.ami"],["amr","audio/amr"],["apk","application/vnd.android.package-archive"],["apng","image/apng"],["appcache","text/cache-manifest"],["application","application/x-ms-application"],["apr","application/vnd.lotus-approach"],["arc","application/x-freearc"],["arj","application/x-arj"],["asc","application/pgp-signature"],["asf","video/x-ms-asf"],["asm","text/x-asm"],["aso","application/vnd.accpac.simply.aso"],["asx","video/x-ms-asf"],["atc","application/vnd.acucorp"],["atom","application/atom+xml"],["atomcat","application/atomcat+xml"],["atomdeleted","application/atomdeleted+xml"],["atomsvc","application/atomsvc+xml"],["atx","application/vnd.antix.game-component"],["au","audio/x-au"],["avi","video/x-msvideo"],["avif","image/avif"],["aw","application/applixware"],["azf","application/vnd.airzip.filesecure.azf"],["azs","application/vnd.airzip.filesecure.azs"],["azv","image/vnd.airzip.accelerator.azv"],["azw","application/vnd.amazon.ebook"],["b16","image/vnd.pco.b16"],["bat","application/x-msdownload"],["bcpio","application/x-bcpio"],["bdf","application/x-font-bdf"],["bdm","application/vnd.syncml.dm+wbxml"],["bdoc","application/x-bdoc"],["bed","application/vnd.realvnc.bed"],["bh2","applicatio
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function OOn(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function POn(t){if(Array.isArray(t))return Nke(t)}function c5t(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),r.push.apply(r,n)}return r}function d5t(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?c5t(Object(r),!0).forEach(function(n){m5t(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):c5t(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}function m5t(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function t9(t,e){return AOn(t)||TOn(t,e)||h5t(t,e)||EOn()}function EOn(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function h5t(t,e){if(t){if(typeof t=="string")return Nke(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Nke(t,e)}}function Nke(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function TOn(t,e){var r=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(r!=null){var n=[],o=!0,i=!1,a,s;try{for(r=r.call(t);!(o=(a=r.next()).done)&&(n.push(a.value),!(e&&n.length===e));o=!0);}catch(u){i=!0,s=u}finally{try{!o&&r.return!=null&&r.return()}finally{if(i)throw s}}return n}}function AOn(t){if(Array.isArray(t))return t}var IOn=typeof ode.default=="function"?ode.default:ode.default.default,MOn="file-invalid-type",ROn="file-too-large",jOn="file-too-small",NOn="too-many-files";var DOn=function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",r=e.split(","),n=r.length>1?"oneof".concat(r.join(",")):r[0];return{code:MOn,message:"Filetypemustbe".concat(n)}},f5t=function(e){return{code:ROn,message:"Fileislargerthan".concat(e,"").concat(e===1?"byte":"bytes")}},p5t=function(e){return{code:jOn,message:"Fileissmallerthan".concat(e,"").concat(e===1?"byte":"bytes")}},g5t={code:NOn,message:"Toomanyfiles"};function Dke(t,e){var r=t.type==="application/x-moz-file"||IOn(t,e);return[r,r?null:DOn(e)]}function Lke(t,e,r){if(eL(t.size))if(eL(e)&&eL(r)){if(t.size>r)return[!1,f5t(r)];if(t.size<e)return[!1,p5t(e)]}else{if(eL(e)&&t.size<e)return[!1,p5t(e)];if(eL(r)&&t.size>r)return[!1,f5t(r)]}return[!0,null]}function eL(t){return t!=null}function y5t(t){var e=t.files,r=t.accept,n=t.minSize,o=t.maxSize,i=t.multiple,a=t.maxFiles,s=t.validator;return!i&&e.length>1||i&&a>=1&&e.length>a?!1:e.every(function(u){var l=Dke(u,r),c=t9(l,1),d=c[0],f=Lke(u,n,o),p=t9(f,1),m=p[0],h=s?s(u):null;return d&&m&&!h})}function r9(t){return typeof t.isPropagationStopped=="function"?t.isPropagationStopped():typeof t.cancelBubble<"u"?t.cancelBubble:!1}function n9(t){return t.dataTransfer?Array.prototype.some.call(t.dataTransfer.types,function(e){return e==="Files"||e==="application/x-moz-file"}):!!t.target&&!!t.target.files}function Fke(t){t.preventDefault()}function LOn(t){return t.indexOf("MSIE")!==-1||t.indexOf("Trident/")!==-1}function FOn(t){return t.indexOf("Edge/")!==-1}function b5t(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.navigator.userAgent;return LOn(t)||FOn(t)}function Pb(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return function(n){for(var o=arguments.length,i=new Array(o>1?o-1:0),a=1;a<o;a++)i[a-1]=arguments[a];return e.some(function(s){return!r9(n)&&s&&s.apply(void 0,[n].concat(i)),r9(n)})}}function _5t(){return"showOpenFilePicker"in window}function v5t(t){if(eL(t)){var e=Object.entries(t).filter(function(r){var n=t9(r,2),o=n[0],i=n[1],a=!0;return C5t(o)||(console.warn('Skipped "'.concat(o,'" because it is not a valid MIME type. Check https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for a list of valid MIME types.')),a=!1),(!Array.isArray(i)||!i.every(O5t))&&(console.warn('Skipped "'.concat(o,'" because an invalid file extension was provided.')),a=!1),a}).reduce(function(r,n){var o=t9(n,2),i=o[0],a=o[1];return d5t(d5t({},r),{},m5t({},i,a))},{});return[{description:"Files",accept:e}]}return t}function w5t(t){if(eL(t))return Object.entries(t).reduce(function(e,r){var n=t9(r,2),o=n[0],i=n[1];return[].concat(l5t(e),[o],l5t(i))},[]).filter(function(e){return C5t(e)||O5t(e)}).join(",")}function S5t(t){return t instanceof DOMException&&(t.name==="AbortError"||t.code===t.ABORT_ERR)}function x5t(t){return t instanceof DOMException&&(t.name==="SecurityError"||t.code===t.SECURITY_ERR)}function C5t(t){return t==="audio/*"||t==="video/*"||t==="image/*"||t==="text/*"||t==="application/*"||/\w+\/[-+.\w]+/g.test(t)}function
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function HOn(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function VOn(t){if(Array.isArray(t))return $ke(t)}function kke(t,e){return GOn(t)||KOn(t,e)||T5t(t,e)||WOn()}function WOn(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function T5t(t,e){if(t){if(typeof t=="string")return $ke(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return $ke(t,e)}}function $ke(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function KOn(t,e){var r=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(r!=null){var n=[],o=!0,i=!1,a,s;try{for(r=r.call(t);!(o=(a=r.next()).done)&&(n.push(a.value),!(e&&n.length===e));o=!0);}catch(u){i=!0,s=u}finally{try{!o&&r.return!=null&&r.return()}finally{if(i)throw s}}return n}}function GOn(t){if(Array.isArray(t))return t}function P5t(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),r.push.apply(r,n)}return r}function ts(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?P5t(Object(r),!0).forEach(function(n){Bke(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):P5t(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}function Bke(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function ide(t,e){if(t==null)return{};var r=JOn(t,e),n,o;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(o=0;o<i.length;o++)n=i[o],!(e.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function JOn(t,e){if(t==null)return{};var r={},n=Object.keys(t),o,i;for(i=0;i<n.length;i++)o=n[i],!(e.indexOf(o)>=0)&&(r[o]=t[o]);return r}var Uke=(0,wn.forwardRef)(function(t,e){var r=t.children,n=ide(t,kOn),o=zke(n),i=o.open,a=ide(o,$On);return(0,wn.useImperativeHandle)(e,function(){return{open:i}},[i]),wn.default.createElement(wn.Fragment,null,r(ts(ts({},a),{},{open:i})))});Uke.displayName="Dropzone";var A5t={disabled:!1,getFilesFromEvent:Rke,maxSize:1/0,minSize:0,multiple:!0,maxFiles:0,preventDropOnDocument:!0,noClick:!1,noKeyboard:!1,noDrag:!1,noDragEventsBubbling:!1,validator:null,useFsAccessApi:!1,autoFocus:!1};Uke.defaultProps=A5t;Uke.propTypes={children:Mi.default.func,accept:Mi.default.objectOf(Mi.default.arrayOf(Mi.default.string)),multiple:Mi.default.bool,preventDropOnDocument:Mi.default.bool,noClick:Mi.default.bool,noKeyboard:Mi.default.bool,noDrag:Mi.default.bool,noDragEventsBubbling:Mi.default.bool,minSize:Mi.default.number,maxSize:Mi.default.number,maxFiles:Mi.default.number,disabled:Mi.default.bool,getFilesFromEvent:Mi.default.func,onFileDialogCancel:Mi.default.func,onFileDialogOpen:Mi.default.func,useFsAccessApi:Mi.default.bool,autoFocus:Mi.default.bool,onDragEnter:Mi.default.func,onDragLeave:Mi.default.func,onDragOver:Mi.default.func,onDrop:Mi.default.func,onDropAccepted:Mi.default.func,onDropRejected:Mi.default.func,onError:Mi.default.func,validator:Mi.default.func};var qke={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function zke(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=ts(ts({},A5t),t),r=e.accept,n=e.disabled,o=e.getFilesFromEvent,i=e.maxSize,a=e.minSize,s=e.multiple,u=e.maxFiles,l=e.onDragEnter,c=e.onDragLeave,d=e.onDragOver,f=e.onDrop,p=e.onDropAccepted,m=e.onDropRejected,h=e.onFileDialogCancel,b=e.onFileDialogOpen,g=e.useFsAccessApi,y=e.autoFocus,S=e.preventDropOnDocument,x=e.noClick,O=e.noKeyboard,P=e.noDrag,E=e.noDragEventsBubbling,A=e.onError,I=e.validator,R=(0,wn.useMemo)(function(){return w5t(r)},[r]),N=(0,wn.useMemo)(function(){return v5t(r)},[r]),j=(0,wn.useMemo)(function(){return typeof b=="function"?b:E5t},[b]),$=(0,wn.useMemo)(function(){return typeof h=="function"?h:E5t},[h]),k=(0,wn.useRef)(null),z=(0,wn.useRef)(null),V=(0,wn
`))},placeholder:"Enter web URLs, one per line",className:"tw-min-h-20 tw-w-full"})),Kt.default.createElement(Yn,{label:"YouTube URLs"},Kt.default.createElement(yE,{value:u.contextSource?.youtubeUrls,onChange:h=>{letg=h.target.value.split(`
`));letxn={message:yf,originalMessage:bf,sender:Pi,isVisible:!1,timestamp:Pe,content:oe,context:{notes:se,urls:f==="copilot_plus"?[...et||[],...xc.imageUrls]:et||[],selectedTextContexts:z}};l(xn),h&&n(h),a.autosaveChat&&Y(),awaitUBe(xn,e,l,m,y,{debug:a.debug,updateLoadingMessage:P}),a.autosaveChat&&Y(),x(!1),P(t_.DEFAULT)},Y=(0,xr.useCallback)(async()=>{if(!U){console.error("App instance is not available.");return}lette=t.getMessages().filter(Pe=>Pe.isVisible);if(te.length===0){newpm.Notice("No messages to save.");return}letet=te[0].timestamp?.epoch||Date.now(),Re=te.map(Pe=>`**${Pe.sender}**: ${Pe.message}
${Re}`,Cd=U.vault.getAbstractFileByPath(ta);Cdinstanceofpm.TFile?awaitU.vault.modify(Cd,xc):(awaitU.vault.create(ta,xc),newpm.Notice(`Chat saved as note: ${ta}`))}catch(Pe){console.error("Error saving chat as note:",ei(Pe)),newpm.Notice("Failed to save chat as note. Check console for details.")}},[U,t,d,a.defaultConversationTag,a.defaultSaveFolder,a.defaultConversationNoteName]),ae=(0,xr.useCallback)(te=>{g&&(a.debug&&console.log(`stopping generation..., reason: ${te}`),g.abort(te),x(!1),P(t_.DEFAULT))},[g,a.debug]),Oe=(0,xr.useCallback)(asyncte=>{letet=te-1;if(et<0||u[et].sender!==Pi){newpm.Notice("Cannot regenerate the first message or a user message.");return}letRe=u[et],Pe=u.slice(0,te);c(),Pe.forEach(l),e.memoryManager.clearChatMemory();for(letoe=0;oe<Pe.length;oe+=2){letse=Pe[oe],ce=Pe[oe+1];se&&ce&&awaite.memoryManager.getMemory().saveContext({input:se.message},{output:ce.message})}x(!0);try{awaite.runChain(Re,newAbortController,m,l,{debug:a.debug})&&a.debug&&console.log("Message regenerated successfully")}catch(oe){console.error("Error regenerating message:",oe),newpm.Notice("Failed to regenerate message. Please try again.")}finally{x(!1)}a.autosaveChat&&Y()},[l,e,u,c,a.debug,a.autosaveChat,Y]),le=(0,xr.useCallback)(async(te,et)=>{letRe=u[te].message;if(Re===et)return;letPe=[...u];for(letoe=te;oe<Pe.length;oe++)Pe[oe].originalMessage===Re&&(Pe[oe].message=et,Pe[oe].originalMessage=et,Pe[oe].context={notes:[],urls:[]});c(),Pe.forEach(l),awaitvN(Pe,e.memoryManager),Pe[te].sender===Pi&&te<Pe.length-1&&Oe(te+1),a.autosaveChat&&Y()},[l,e.memoryManager,u,c,Oe,a.autosaveChat,Y]);(0,xr.useEffect)(((te,et)=>()=>{letRe=ue().debug,Pe=asyncoe=>{letce={message:awaitet(oe.detail.selectedText,oe.detail.eventSubtype),sender:Pi,isVisible:Re,timestamp:Vl(newDate)};Re&&l(ce),x(!0),awaitUBe(ce,e,l,m,y,{debug:Re,ignoreSystemMessage:!0}),x(!1)};returns?.addEventListener(te,Pe),()=>{s?.removeEventListener(te,Pe)}})(Br.APPLY_ADHOC_PROMPT,async(te,et)=>et?(awaitfce(et,te,U.vault,U.workspace.getActiveFile())).processedPrompt:te),[]),(0,xr.useEffect)(()=>{r&&r(Y)},[r,Y]);letze=(0,xr.useCallback)(asyncte=>{letet=[...u];et.splice(te,1),c(),et.forEach(l),awaitvN(et,e.memoryManager)},[l,e.memoryManager,u,c]),rt=(0,xr.useCallback)(te=>{letet=a.projectList||[];if(et.findIndex(se=>se.name===te.name)>=0)thrownewError(`Project "${te.name}" already exists, please use a different name`);letPe=[...et,te];returndt("projectList",Pe),Mc()?.id===te.id?Xce().then(()=>{newpm.Notice(`${te.name} added and context loaded`)}).catch(se=>{console.error("Error loading project context:",se),newpm.Notice(`${te.name} added but context loading failed`)}):newpm.Notice(`${te.name} added successfully`),!0},[a.projectList]),cr=(0,xr.useCallback)((te,et)=>{letRe=a.projectList||[];if(!Re.find(ce=>ce.name===te.name))thrownewError(`Project "${te.name}" does not exist`);letoe=Re.map(ce=>ce.name===te.name?et:ce);returndt("projectList",oe),Mc()?.id===te.id?(zR(et),Xce().then(()=>{newpm.Notice(`${te.name} updated and context reloaded`)}).catch(ce=>{console.error("Error reloading project context:",ce),newpm.Notice(`${te.name} updated but context reload failed`)})):newpm.Notice(`${te.name} updated successfully`),!0},[a.projectList]),Sn=(0,xr.useCallback)(te=>{b(et=>`${et}${te} `)},[]),je=(0,xr.useCallback)(te=>{i8e(te)},[]),mt=(0,xr.useCallback)(async()=>{ae("new-chat"),awaiti.handleNewChat(),m(""),A([]),a8e(),J!=="copilot_plus"?R(!1):R(a.includeActiveNoteAsContext)},[ae,i,a.includeActiveNoteAsContext,J]),ht=(0,xr.useCallback)(()=>{i.loadCopilotChatHistory()},[i]);(0,xr.useEffect)(()=>{lette=et=>{letRe=et.detail?.reason||"new-chat";ae(Re)};returns?.addEventListener(Dh.ABORT_STREAM,te),()=>{s?.removeEventListener(Dh.ABORT_STREAM,te)}},[s,ae]),(0,xr.useEffect)(()=>{a.includeActiveNoteAsContext!==void0&&(J==="copilot_plus"?R(a.includeActiveNoteAsContext):R(!1))},[a.includeActiveNoteAsContext,J]);letft=()=>xr.default.createElement(xr.default.Fragment,null,xr.default.createElement("div",{className:"tw-flex tw-size-full tw-flex-col
Wefound${r.length}unsupportedcommands.Theyaresavedin${QI()}/unsupported.Tofixthem,pleaseresolvetheerrorsandmovethenotefileoutoftheunsupportedfolder.`),dt("inlineEditCommands",[]),new sd(app,()=>{},i,"\u{1F680} New Copilot Custom Commands","OK","").open()}async function Pqe(){let t=Jx(),e=I3t.filter(n=>!t.some(o=>o.title===n.title)),r=[...t,...e];lm.getInstance().updateCommands(r)}async function AYt(){if(ue().suggestedDefaultCommands)return;Jx().length===0&&(new sd(app,()=>{Pqe()},"Would you like to add Copilot recommended commands in your custom prompts folder? These commands will be available through the right-click context menu and slash commands in chat.","Welcome to Copilot","Confirm","Skip").open(),dt("suggestedDefaultCommands",!0))}var LRn=({command:t,commands:e,onUpdate:r,onRemove:n})=>{let{attributes:o,listeners:i,setNodeRef:a,transform:s,transition:u,isDragging:l}=J9({id:t.title}),c={transform:Rb.Transform.toString(s),transition:u},d=()=>{n(t)};return it.default.createElement(BM,{ref:a,style:c,className:_e("tw-transition-colors",l&&"tw-relative tw-z-[100] tw-cursor-grabbing tw-shadow-lg tw-backdrop-blur-sm tw-border-accent/50")},it.default.createElement(gf,{className:"tw-w-10"},it.default.createElement("div",{...o,...i,className:"tw-flex tw-cursor-grab tw-items-center tw-justify-center"},it.default.createElement(d_,{className:"tw-size-4"}))),it.default.createElement(gf,null,t.title),it.default.createElement(gf,{className:"tw-text-center"},it.default.createElement(wd,{checked:t.showInContextMenu,onCheckedChange:f=>{r({...t,showInContextMenu:f===!0},t.title)},className:"tw-mx-auto"})),it.default.createElement(gf,{className:"tw-text-center"},it.default.createElement(wd,{checked:t.showInSlashMenu,onCheckedChange:f=>r({...t,showInSlashMenu:f===!0},t.title),className:"tw-mx-auto"})),it.default.createElement(gf,{className:"tw-text-center"},it.default.createElement("div",{className:"tw-flex tw-justify-center tw-space-x-1"},it.default.createElement(ge,{variant:"ghost",size:"icon",onClick:()=>{new Ofe(app,e,t,async p=>{await r(p,t.title)}).open()}},it.default.createElement(p_,{className:"tw-size-4"})),it.default.createElement(ge,{variant:"ghost",size:"icon",onClick:()=>{new sd(app,d,`Areyousureyouwanttodeletethecommand"${t.title}"?Thiswillpermanentlyremovethecommandfileandcannotbeundone.`,"Delete Command","Delete","Cancel").open()}},it.default.createElement(Rm,{className:"tw-size-4"})))))},IYt=()=>{let t=M3t(),e=(0,it.useMemo)(()=>IW([...t]),[t]),[r,n]=it.default.useState(""),o=Rn(),i=gfe(Xz(VM,{activationConstraint:{distance:8}}),Xz(HM,{coordinateGetter:xfe})),a=JU(r,e),s=!a&&r.trim()!=="",u=async()=>{if(s)try{await lm.getInstance().createCommand(r.trim(),""),n(""),new rK.Notice(`Command"${r.trim()}"createdsuccessfully!`)}catch(p){console.error("Failed to create command:",p),new rK.Notice("Failed to create command. Please try again.")}},l=async(p,m)=>{await lm.getInstance().updateCommand(p,m)},c=async p=>{try{await lm.getInstance().deleteCommand(p),new rK.Notice(`Command"${p.title}"deletedsuccessfully!`)}catch(m){throw console.error("Failed to delete command:",m),new rK.Notice("Failed to delete command. Please try again."),m}},d=async p=>{let{active:m,over:h}=p;if(!h||m.id===h.id)return;let b=e.findIndex(x=>x.title===m.id),g=e.findIndex(x=>x.title===h.id);if(b===-1||g===-1)return;let y=[...e],[S]=y.splice(b,1);y.splice(g,0,S);for(let x=0;x<y.length;x++)y[x]={...y[x],order:x*10};await lm.getInstance().updateCommands(y)},f=Y9();return it.default.createElement("div",{className:"tw-space-y-4"},it.default.createElement("section",null,it.default.createElement("div",{className:"tw-mb-4 tw-flex tw-flex-col tw-gap-2"},it.default.createElement("div",{className:"tw-text-xl tw-font-bold"},"Custom Commands"),it.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Custom commands are preset prompts that you can trigger in the editor by right-clicking and selecting them from the context menu or by using a ",it.default.createElement("code",null,"/")," command in the cha
with CORS Error: `+ei(J);thrownewError(D)}}letz=awaitk.json(),V=DYt(I,z);l(Q=>({...Q,[I]:V})),d(null)}catch(N){console.error(`Error fetching models for ${I}:`,N),p(I),d(null),newDb.Notice(`Failed to load models for ${kf(I)}: ${ei(N)}`,5e3)}},A=async()=>{if(!m){newDb.Notice("Please select a model first");return}g(!0);try{letI=S(m.provider),R={name:m.name,provider:m.provider,apiKey:I,enabled:!0};if(awaitac.instance.getCurrentChainManager().chatModelManager.ping(R),e.activeModels.find(j=>j.name===m.name&&j.provider===m.provider))newDb.Notice(`Model ${m.name} verified successfully! It already exists in your models list.`);else{letj=[...e.activeModels,R];dt("activeModels",j),newDb.Notice(`Model ${m.name} verified successfully and added to your models list!`)}}catch(I){console.error("Model verification failed:",I),newDb.Notice("Model verification failed: "+ei(I),1e4)}finally{g(!1)}};returnHt.default.createElement("div",{className:"tw-max-h-[600px] tw-overflow-y-auto tw-p-4 sm:tw-max-w-[500px]"},Ht.default.createElement("div",{className:"tw-mb-4"},Ht.default.createElement("h2",{className:"tw-text-xl tw-font-bold"},"AI Provider Settings"),Ht.default.createElement("p",{className:"tw-text-sm tw-text-muted"},"Configure your AI providers by adding their API keys.")),Ht.default.createElement("div",{className:"tw-space-y-6 tw-py-4"},Ht.default.createElement("div",{className:"tw-space-y-4"},x.map(I=>Ht.default.createElement(Ht.default.Fragment,{key:I.provider},Ht.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Ht.default.createElement("div",{className:"tw-flex tw-items-end tw-gap-2 tw-font-medium"},Ht.default.createElement("div",{className:"tw-truncate"},kf(I.provider))),Ht.default.createElement("div",{className:"tw-flex tw-flex-row tw-items-center tw-gap-2"},Ht.default.createElement("div",{className:"tw-flex-1"},Ht.default.createElement(aC,{className:"tw-max-w-full",value:I.apiKey,onChange:R=>O(I.provider,R),disabled:r.has(I.provider)})),Ht.default.createElement("div",{className:"tw-w-[72px]"},I.isVerified?Ht.default.createElement("span",{className:"tw-flex tw-h-9 tw-items-center tw-justify-center tw-text-sm tw-text-success"},"Verified"):Ht.default.createElement(ge,{onClick:()=>P(I.provider,I.apiKey),disabled:!I.apiKey||r.size>0,variant:"secondary",size:"sm",className:"tw-w-full tw-whitespace-nowrap"},r.has(I.provider)?Ht.default.createElement(Yl,{className:"tw-mr-2 tw-size-4 tw-animate-spin"}):"Verify")),Ht.default.createElement("div",{className:""},Ht.default.createElement(ge,{onClick:()=>{letR=a===I.provider?null:I.provider;s(R),R&&I.apiKey&&u[I.provider]===void0&&c!==I.provider&&f!==I.provider&&E(I.provider,I.apiKey)},disabled:!I.apiKey||r.size>0,variant:"secondary",size:"sm",className:"tw-flex tw-w-full tw-items-center tw-justify-center tw-gap-1 tw-whitespace-nowrap tw-p-0.5"},"Add Model",a===I.provider?Ht.default.createElement(Ey,{className:"tw-ml-1 tw-size-4"}):Ht.default.createElement(Hi,{className:"tw-ml-1 tw-size-4"})))),Ht.default.createElement("div",null,Xb(I.provider).keyManagementURL&&Ht.default.createElement("a",{href:Xb(I.provider).keyManagementURL,target:"_blank",rel:"noopener noreferrer",className:"tw-text-[10px] tw-text-accent hover:tw-text-accent-hover sm:tw-text-xs"},"Get ",kf(I.provider)," Key"))),Ht.default.createElement(cE,{open:a===I.provider,className:"tw-mt-2"},Ht.default.createElement(dE,{className:"tw-rounded-md tw-p-3"},Ht.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Ht.default.createElement(Yn,{label:"Model",description:"Add the currently selected model to model List. After adding, please check the Model Tab."},Ht.default.createElement("div",null,Ht.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Ht.default.createElement("div",{className:"tw-flex-1"},Ht.default.createElement(Wde,{options:u[I.provider]?.sort((R,N)=>R.name.localeCompare(N.name)).map(R=>({label:R.name,value:R.id}))||[],onChange:R=>{letN=R.target.value,j=u[I.provider]?.find($=>$.id===N);j&&h({id:j.id,name:j.name,provider:I.provider})},onClick:()=>{I.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*)
crypto-js/ripemd160.js:
(** @preserve
(c) 2012 by Cédric Mesnil. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
crypto-js/mode-ctr-gladman.js:
(** @preserve
* Counter block mode compatible with Dr Brian Gladman fileenc.c