1437 lines
3.1 MiB
JavaScript
Raw Normal View History

2025-01-09 14:41:22 +08:00
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
2025-03-14 16:09:40 +08:00
var s8t=Object.create;var _$=Object.defineProperty;var u8t=Object.getOwnPropertyDescriptor;var l8t=Object.getOwnPropertyNames;var c8t=Object.getPrototypeOf,d8t=Object.prototype.hasOwnProperty;var f8t=(e,t,r)=>t in e?_$(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var C=(e,t)=>()=>(e&&(t=e(e=0)),t);var b=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Kd=(e,t)=>{for(var r in t)_$(e,r,{get:t[r],enumerable:!0})},B1e=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of l8t(t))!d8t.call(e,o)&&o!==r&&_$(e,o,{get:()=>t[o],enumerable:!(n=u8t(t,o))||n.enumerable});return e};var B=(e,t,r)=>(r=e!=null?s8t(c8t(e)):{},B1e(t||!e||!e.__esModule?_$(r,"default",{value:e,enumerable:!0}):r,e)),il=e=>B1e(_$({},"__esModule",{value:!0}),e);var Nl=(e,t,r)=>f8t(e,typeof t!="symbol"?t+"":t,r);function h8t(e){U1e=e}function g6(){return U1e}function He(e,t){let r=g6(),n=y6({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===bD?void 0:bD].filter(o=>!!o)});e.common.issues.push(n)}function b6(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)}function z1e(e,t,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r}function gr(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(a,s)=>{var u,l;let{message:c}=e;return a.code==="invalid_enum_value"?{message:c??s.defaultError}:typeof s.data>"u"?{message:(u=c??n)!==null&&u!==void 0?u:s.defaultError}:a.code!=="invalid_type"?{message:s.defaultError}:{message:(l=c??r)!==null&&l!==void 0?l:s.defaultError}},description:o}}function V1e(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`),t}function R8t(e){return new RegExp(`^${V1e(e)}$`)}function W1e(e){let t=`${H1e}T${V1e(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function D8t(e,t){return!!((t==="v4"||!t)&&O8t.test(e)||(t==="v6"||!t)&&P8t.test(e))}function j8t(e,t){if(!w8t.test(e))return!1;try{let[r]=e.split("."),n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||!o.typ||!o.alg||t&&o.alg!==t)}catch{return!1}}function N8t(e,t){return!!((t==="v4"||!t)&&E8t.test(e)||(t==="v6"||!t)&&T8t.test(e))}function L8t(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,i=parseInt(e.toFixed(o).replace(".","")),a=parseInt(t.toFixed(o).replace(".",""));return i%a/Math.pow(10,o)}function gD(e){if(e instanceof Zd){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=Yd.create(gD(n))}return new Zd({...e._def,shape:()=>t})}else return e instanceof hS?new hS({...e._def,type:gD(e.element)}):e instanceof Yd?Yd.create(gD(e.unwrap())):e instanceof Qg?Qg.create(gD(e.unwrap())):e instanceof Xg?Xg.create(e.items.map(t=>gD(t))):e}function xae(e,t){let r=fS(e),n=fS(t);if(e===t)return{valid:!0,data:e};if(r===Qe.object&&n===Qe.object){let o=Sn.objectKeys(t),i=Sn.objectKeys(e).filter(s=>o.indexOf(s)!==-1),a={...e,...t};for(let s of i){let u=xae(e[s],t[s]);if(!u.valid)return{valid:!1};a[s]=u.data}return{valid:!0,data:a}}else if(r===Qe.array&&n===Qe.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let i=0;i<e.length;i++){let a=e[i],s=t[i],u=xae(a,s);if(!u.valid)return{valid:!
`])),o.push(new Blob([`Content-Disposition: form-data; name="${u.name}"\r
`,`Content-Type: ${u.payload.type}\r
\r
`])),o.push(u.payload),o.push(new Blob([`\r
`]));o.push(new Blob([`--${n}--\r
`]));let a=await new Blob(o).arrayBuffer(),s=await this.batchIngestCaller.call(wt(),`${this.apiUrl}/runs/multipart`,{method:"POST",headers:{...this.headers,"Content-Type":`multipart/form-data; boundary=${n}`},body:a,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(s,"ingest multipart runs",!0)}catch(n){console.warn(`${n.message.trim()}
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
Context: ${r}`)}}async updateRun(t,r){en(t),r.inputs&&(r.inputs=this.processInputs(r.inputs)),r.outputs&&(r.outputs=this.processOutputs(r.outputs));let n={...r,id:t};if(!this._filterForSampling([n],!0).length)return;if(this.autoBatchTracing&&n.trace_id!==void 0&&n.dotted_order!==void 0){if(r.end_time!==void 0&&n.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:n}).catch(console.error);return}else this.processRunOperation({action:"update",item:n}).catch(console.error);return}let o={...this.headers,"Content-Type":"application/json"},i=await this.caller.call(wt(),`${this.apiUrl}/runs/${t}`,{method:"PATCH",headers:o,body:ef(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(i,"update run",!0)}async readRun(t,{loadChildRuns:r}={loadChildRuns:!1}){en(t);let n=await this._get(`/runs/${t}`);return r&&n.child_run_ids&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:t,run:r,projectOpts:n}){if(r!==void 0){let o;r.session_id?o=r.session_id:n?.projectName?o=(await this.readProject({projectName:n?.projectName})).id:n?.projectId?o=n?.projectId:o=(await this.readProject({projectName:yS("PROJECT")||"default"})).id;let i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${o}/r/${r.id}?poll=true`}else if(t!==void 0){let o=await this.readRun(t);if(!o.app_path)throw new Error(`Run ${t} has no app_path`);return`${this.getHostUrl()}${o.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(t){let r=await J5t(this.listRuns({id:t.child_run_ids})),n={},o={};r.sort((i,a)=>(i?.dotted_order??"").localeCompare(a?.dotted_order??""));for(let i of r){if(i.parent_run_id===null||i.parent_run_id===void 0)throw new Error(`Child run ${i.id} has no parent`);i.parent_run_id in n||(n[i.parent_run_id]=[]),n[i.parent_run_id].push(i),o[i.id]=i}t.child_runs=n[t.id]||[];for(let i in n)i!==t.id&&(o[i].child_runs=n[i]);return t}async*listRuns(t){let{projectId:r,projectName:n,parentRunId:o,traceId:i,referenceExampleId:a,startTime:s,executionOrder:u,isRoot:l,runType:c,error:d,id:f,query:p,filter:h,traceFilter:m,treeFilter:_,limit:g,select:v}=t,S=[];if(r&&(S=Array.isArray(r)?r:[r]),n){let E=Array.isArray(n)?n:[n],M=await Promise.all(E.map(A=>this.readProject({projectName:A}).then(j=>j.id)));S.push(...M)}let x=["app_path","child_run_ids","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],O={session:S.length?S:null,run_type:c,reference_example:a,query:p,filter:h,trace_filter:m,tree_filter:_,execution_order:u,parent_run:o,start_time:s?s.toISOString():null,error:d,id:f,limit:g,trace:i,select:v||x,is_root:l},T=0;for await(let E of this._getCursorPaginatedList("/runs/query",O))if(g){if(T>=g)break;if(E.length+T>g){yield*E.slice(0,g-T);break}T+=E.length,yield*E}else yield*E}async getRunStats({id:t,trace:r,parentRun:n,runType:o,projectNames:i,projectIds:a,referenceExampleIds:s,startTime:u,endTime:l,error:c,query:d,filter:f,traceFilter:p,treeFilter:h,isRoot:m,dataSourceType:_}){let g=a||[];i&&(g=[...a||[],...await Promise.all(i.map(T=>this.readProject({projectName:T}).then(E=>E.id)))]);let S=Object.fromEntries(Object.entries({id:t,trace:r,parent_run:n,run_type:o,session:g,reference_example:s,start_time:u,end_time:l,error:c,query:d,filter:f,trace_filter:p,tree_filter:h,is_root:m,data_source_type:_}).filter(([T,E])=>E!==void 0));return await(await this.caller.call(wt(),`${this.apiUrl}/runs/stats`,{method:"POST",headers:this.headers,body:JSON.stringify(S),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json()}async shareRun(t,{shareId:r}={}){let n={run_id:t,share_token:r||dO()};en(t);let i=await(await this.caller.call(wt(),`${this.apiUrl}/runs/${t}/share`,{method:"PUT",headers:this.headers,body:JSON.stringify(
Status: ${i.status}
Message: ${a.detail.join(`
`)}`):new Error(`Failed to list shared examples: ${i.status} ${i.statusText}`);return a.map(s=>({...s,_hostUrl:this.getHostUrl()}))}async createProject({projectName:t,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:t,extra:l,description:r};a!==null&&(c.reference_dataset_id=a);let d=await this.caller.call(wt(),u,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(c),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(d,"create project"),await d.json()}async updateProject(t,{name:r=null,description:n=null,metadata:o=null,projectExtra:i=null,endTime:a=null}){let s=`${this.apiUrl}/sessions/${t}`,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(wt(),s,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(c,"update project"),await c.json()}async hasProject({projectId:t,projectName:r}){let n="/sessions",o=new URLSearchParams;if(t!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(t!==void 0)en(t),n+=`/${t}`;else if(r!==void 0)o.append("name",r);else throw new Error("Must provide projectName or projectId");let i=await this.caller.call(wt(),`${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:t,projectName:r,includeStats:n}){let o="/sessions",i=new URLSearchParams;if(t!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(t!==void 0)en(t),o+=`/${t}`;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=${t}, name=${r}] not found`);s=a[0]}else s=a;return s}async getProjectUrl({projectId:t,projectName:r}){if(t===void 0&&r===void 0)throw new Error("Must provide either projectName or projectId");let n=await this.readProject({projectId:t,projectName:r}),o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/projects/p/${n.id}`}async getDatasetUrl({datasetId:t,datasetName:r}){if(t===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");let n=await this.readDataset({datasetId:t,datasetName:r}),o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let t=new URLSearchParams({limit:"1"});for await(let r of this._getPaginated("/sessions",t))return this._tenantId=r[0].tenant_id,r[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:t,name:r,nameContains:n,referenceDatasetId:o,referenceDatasetName:i,referenceFree:a,metadata:s}={}){let u=new URLSearchParams;if(t!==void 0)for(let l of t)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:t,projectName:r}){let n;if(t===void 0&&r===void 0)throw new Error("Must provide projectName or projectId");if(t!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");t===void 0?n=(await this.readProject({projectName:r})).id:n=t,en(n);let o=await this.caller.call(wt(),`${this.apiUrl}/sessions/${n}`,{method:"DELETE",headers:this.headers,
`).map(s=>JSON.parse(s))}async*listDatasets({limit:t=100,offset:r=0,datasetIds:n,datasetName:o,datasetNameContains:i,metadata:a}={}){let s="/datasets",u=new URLSearchParams({limit:t.toString(),offset:r.toString()});if(n!==void 0)for(let l of n)u.append("id",l);o!==void 0&&u.append("name",o),i!==void 0&&u.append("name_contains",i),a!==void 0&&u.append("metadata",JSON.stringify(a));for await(let l of this._getPaginated(s,u))yield*l}async updateDataset(t){let{datasetId:r,datasetName:n,...o}=t;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let i=r??(await this.readDataset({datasetName:n})).id;en(i);let a=await this.caller.call(wt(),`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(a,"update dataset"),await a.json()}async deleteDataset({datasetId:t,datasetName:r}){let n="/datasets",o=t;if(t!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(o=(await this.readDataset({datasetName:r})).id),o!==void 0)en(o),n+=`/${o}`;else throw new Error("Must provide datasetName or datasetId");let i=await this.caller.call(wt(),this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(i,`delete ${n}`),await i.json()}async indexDataset({datasetId:t,datasetName:r,tag:n}){let o=t;if(!o&&!r)throw new Error("Must provide either datasetName or datasetId");if(o&&r)throw new Error("Must provide either datasetName or datasetId, not both");o||(o=(await this.readDataset({datasetName:r})).id),en(o);let i={tag:n},a=await this.caller.call(wt(),`${this.apiUrl}/datasets/${o}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(a,"index dataset"),await a.json()}async similarExamples(t,r,n,{filter:o}={}){let i={limit:n,inputs:t};o!==void 0&&(i.filter=o),en(r);let a=await this.caller.call(wt(),`${this.apiUrl}/datasets/${r}/search`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(a,"fetch similar examples"),(await a.json()).examples}async createExample(t,r,{datasetId:n,datasetName:o,createdAt:i,exampleId:a,metadata:s,split:u,sourceRunId:l}){let c=n;if(c===void 0&&o===void 0)throw new Error("Must provide either datasetName or datasetId");if(c!==void 0&&o!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");c===void 0&&(c=(await this.readDataset({datasetName:o})).id);let f={dataset_id:c,inputs:t,outputs:r,created_at:(i||new Date)?.toISOString(),id:a,metadata:s,split:u,source_run_id:l},p=await this.caller.call(wt(),`${this.apiUrl}/examples`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(f),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(p,"create example"),await p.json()}async createExamples(t){let{inputs:r,outputs:n,metadata:o,sourceRunIds:i,exampleIds:a,datasetId:s,datasetName:u}=t,l=s;if(l===void 0&&u===void 0)throw new Error("Must provide either datasetName or datasetId");if(l!==void 0&&u!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");l===void 0&&(l=(await this.readDataset({datasetName:u})).id);let c=r.map((p,h)=>({dataset_id:l,inputs:p,outputs:n?n[h]:void 0,metadata:o?o[h]:void 0,split:t.splits?t.splits[h]:void 0,id:a?a[h]:void 0,source_run_id:i?i[h]:void 0})),d=await this.caller.call(wt(),`${this.apiUrl}/examples/bulk`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(c),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(d,"create examples"),await d.json()}async createLLMExample(t,r,n){return this.createExample({input:t},{output:r},n)}async createChatExample(t,r,n){let
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
Current tenant: ${n.tenant_handle}
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
Requested tenant: ${r}`)}async _getLatestCommitHash(t){let r=await this.caller.call(wt(),`${this.apiUrl}/commits/${t}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),n=await r.json();if(!r.ok){let o=typeof n.detail=="string"?n.detail:JSON.stringify(n.detail),i=new Error(`Error ${r.status}: ${r.statusText}
${o}`);throw i.statusCode=r.status,i}if(n.commits.length!==0)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(t,r){let[n,o,i]=gS(t),a=await this.caller.call(wt(),`${this.apiUrl}/likes/${n}/${o}`,{method:"POST",body:JSON.stringify({like:r}),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await qr(a,`${r?"like":"unlike"} prompt`),await a.json()}async _getPromptUrl(t){let[r,n,o]=gS(t);if(await this._currentTenantIsOwner(r)){let i=await this._getSettings();return o!=="latest"?`${this.getHostUrl()}/prompts/${n}/${o.substring(0,8)}?organizationId=${i.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${i.id}`}else return o!=="latest"?`${this.getHostUrl()}/hub/${r}/${n}/${o.substring(0,8)}`:`${this.getHostUrl()}/hub/${r}/${n}`}async promptExists(t){return!!await this.getPrompt(t)}async likePrompt(t){return this._likeOrUnlikePrompt(t,!0)}async unlikePrompt(t){return this._likeOrUnlikePrompt(t,!1)}async*listCommits(t){for await(let r of this._getPaginated(`/commits/${t}/`,new URLSearchParams,n=>n.commits))yield*r}async*listPrompts(t){let r=new URLSearchParams;r.append("sort_field",t?.sortField??"updated_at"),r.append("sort_direction","desc"),r.append("is_archived",(!!t?.isArchived).toString()),t?.isPublic!==void 0&&r.append("is_public",t.isPublic.toString()),t?.query&&r.append("query",t.query);for await(let n of this._getPaginated("/repos",r,o=>o.repos))yield*n}async getPrompt(t){let[r,n,o]=gS(t),i=await this.caller.call(wt(),`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(i.status===404)return null;await qr(i,"get prompt");let a=await i.json();return a.repo?a.repo:null}async createPrompt(t,r){let n=await this._getSettings();if(r?.isPublic&&!n.tenant_handle)throw new Error(`Cannot create a public prompt without first
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
creating a LangChain Hub handle.
You can add a handle by creating a public prompt at:
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
https://smith.langchain.com/prompts`);let[o,i,a]=gS(t);if(!await this._currentTenantIsOwner(o))throw await this._ownerConflictError("create a prompt",o);let s={repo_handle:i,...r?.description&&{description:r.description},...r?.readme&&{readme:r.readme},...r?.tags&&{tags:r.tags},is_public:!!r?.isPublic},u=await this.caller.call(wt(),`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(u,"create prompt");let{repo:l}=await u.json();return l}async createCommit(t,r,n){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");let[o,i,a]=gS(t),s=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${o}/${i}`):n?.parentCommitHash,u={manifest:JSON.parse(JSON.stringify(r)),parent_commit:s},l=await this.caller.call(wt(),`${this.apiUrl}/commits/${o}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(u),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await qr(l,"create commit");let c=await l.json();return this._getPromptUrl(`${o}/${i}${c.commit_hash?`:${c.commit_hash}`:""}`)}async updateExamplesMultipart(t,r=[]){if(!await this._getMultiPartSupport())throw new Error("Your LangSmith version does not allow using the multipart examples endpoint, please update to the latest version.");let n=new FormData;for(let a of r){let s=a.id,u={...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split}},l=ef(u),c=new Blob([l],{type:"application/json"});if(n.append(s,c),a.inputs){let d=ef(a.inputs),f=new Blob([d],{type:"application/json"});n.append(`${s}.inputs`,f)}if(a.outputs){let d=ef(a.outputs),f=new Blob([d],{type:"application/json"});n.append(`${s}.outputs`,f)}if(a.attachments)for(let[d,f]of Object.entries(a.attachments)){let p,h;Array.isArray(f)?[p,h]=f:(p=f.mimeType,h=f.data);let m=new Blob([h],{type:`${p}; length=${h.byteLength}`});n.append(`${s}.attachment.${d}`,m)}if(a.attachments_operations){let d=ef(a.attachments_operations),f=new Blob([d],{type:"application/json"});n.append(`${s}.attachments_operations`,f)}}return await(await this.caller.call(wt(),`${this.apiUrl}/v1/platform/datasets/${t}/examples`,{method:"PATCH",headers:this.headers,body:n})).json()}async uploadExamplesMultipart(t,r=[]){if(!await this._getMultiPartSupport())throw new Error("Your LangSmith version does not allow using the multipart examples endpoint, please update to the latest version.");let n=new FormData;for(let a of r){let s=(a.id??dO()).toString(),u={created_at:a.created_at,...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split}},l=ef(u),c=new Blob([l],{type:"application/json"});n.append(s,c);let d=ef(a.inputs),f=new Blob([d],{type:"application/json"});if(n.append(`${s}.inputs`,f),a.outputs){let p=ef(a.outputs),h=new Blob([p],{type:"application/json"});n.append(`${s}.outputs`,h)}if(a.attachments)for(let[p,h]of Object.entries(a.attachments)){let m,_;Array.isArray(h)?[m,_]=h:(m=h.mimeType,_=h.data);let g=new Blob([_],{type:`${m}; length=${_.byteLength}`});n.append(`${s}.attachment.${p}`,g)}}return await(await this.caller.call(wt(),`${this.apiUrl}/v1/platform/datasets/${t}/examples`,{method:"POST",headers:this.headers,body:n})).json()}async updatePrompt(t,r){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");let[n,o]=gS(t);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);let i={};if(r?.description!==void 0&&(i.description=r.description),r?.readme!==void 0&&(i.readme=r.readme),r?.tags!==void 0&&(i.tags=r.tags),r?.isPublic!==void 0&&(i.is_public=r.isPublic),r?.isArchived!==void 0&&(i.is_archived=r.isArchived),Object.keys(i).length===0)throw new Error("No valid update options provided");let a=await this.caller.call(wt(),`${this.apiUrl}/repos/${n}/${o}`,{method:"PATCH",body:JSON.stringify(i),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.t
`));return e},Qyn=Symbol.for("langsmith:traceable:root")});var hse=C(()=>{kNe()});function iV(e,t){return c9t.call(e,t)}function aV(e){if(Array.isArray(e)){let r=new Array(e.length);for(let n=0;n<r.length;n++)r[n]=""+n;return r}if(Object.keys)return Object.keys(e);let t=[];for(let r in e)iV(e,r)&&t.push(r);return t}function Dc(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function sV(e){let t=0,r=e.length,n;for(;t<r;){if(n=e.charCodeAt(t),n>=48&&n<=57){t++;continue}return!1}return!0}function ty(e){return e.indexOf("/")===-1&&e.indexOf("~")===-1?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function N$(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function oV(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(let r=0,n=e.length;r<n;r++)if(oV(e[r]))return!0}else if(typeof e=="object"){let r=aV(e),n=r.length;for(var t=0;t<n;t++)if(oV(e[r[t]]))return!0}}return!1}function BNe(e,t){let r=[e];for(let n in t){let o=typeof t[n]=="object"?JSON.stringify(t[n],null,2):t[n];typeof o<"u"&&r.push(`${n}: ${o}`)}return r.join(`
`)}var c9t,DM,L$=C(()=>{c9t=Object.prototype.hasOwnProperty;DM=class extends Error{constructor(t,r,n,o,i){super(BNe(t,{name:r,index:n,operation:o,tree:i})),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:o}),Object.defineProperty(this,"tree",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.setPrototypeOf(this,new.target.prototype),this.message=BNe(t,{name:r,index:n,operation:o,tree:i})}}});var mse={};Kd(mse,{JsonPatchError:()=>Pa,_areEquals:()=>F$,applyOperation:()=>jM,applyPatch:()=>fO,applyReducer:()=>p9t,deepClone:()=>d9t,getValueByPointer:()=>uV,validate:()=>$Ne,validator:()=>lV});function uV(e,t){if(t=="")return e;var r={op:"_get",path:t};return jM(e,r),r.value}function jM(e,t,r=!1,n=!0,o=!0,i=0){if(r&&(typeof r=="function"?r(t,0,e,t.path):lV(t,0)),t.path===""){let a={newDocument:e};if(t.op==="add")return a.newDocument=t.value,a;if(t.op==="replace")return a.newDocument=t.value,a.removed=e,a;if(t.op==="move"||t.op==="copy")return a.newDocument=uV(e,t.from),t.op==="move"&&(a.removed=e),a;if(t.op==="test"){if(a.test=F$(e,t.value),a.test===!1)throw new Pa("Test operation failed","TEST_OPERATION_FAILED",i,t,e);return a.newDocument=e,a}else{if(t.op==="remove")return a.removed=e,a.newDocument=null,a;if(t.op==="_get")return t.value=e,a;if(r)throw new Pa("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,t,e);return a}}else{n||(e=Dc(e));let s=(t.path||"").split("/"),u=e,l=1,c=s.length,d,f,p;for(typeof r=="function"?p=r:p=lV;;){if(f=s[l],f&&f.indexOf("~")!=-1&&(f=N$(f)),o&&(f=="__proto__"||f=="prototype"&&l>0&&s[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&d===void 0&&(u[f]===void 0?d=s.slice(0,l).join("/"):l==c-1&&(d=t.path),d!==void 0&&p(t,0,e,d)),l++,Array.isArray(u)){if(f==="-")f=u.length;else{if(r&&!sV(f))throw new Pa("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,t,e);sV(f)&&(f=~~f)}if(l>=c){if(r&&t.op==="add"&&f>u.length)throw new Pa("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,t,e);let h=f9t[t.op].call(t,u,f,e);if(h.test===!1)throw new Pa("Test operation failed","TEST_OPERATION_FAILED",i,t,e);return h}}else if(l>=c){let h=TD[t.op].call(t,u,f,e);if(h.test===!1)throw new Pa("Test operation failed","TEST_OPERATION_FAILED",i,t,e);return h}if(u=u[f],r&&l<c&&(!u||typeof u!="object"))throw new Pa("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,t,e)}}}function fO(e,t,r,n=!0,o=!0){if(r&&!Array.isArray(t))throw new Pa("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(e=Dc(e));let i=new Array(t.length);for(let a=0,s=t.length;a<s;a++)i[a]=jM(e,t[a],r,!0,o,a),e=i[a].newDocument;return i.newDocument=e,i}function p9t(e,t,r){let n=jM(e,t);if(n.test===!1)throw new Pa("Test operation failed","TEST_OPERATION_FAILED",r,t,e);return n.newDocument}function lV(e,t,r,n){if(typeof e!="object"||e===null||Array.isArray(e))throw new Pa("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,r);if(TD[e.op]){if(typeof e.path!="string")throw new Pa("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,r);if(e.path.indexOf("/")!==0&&e.path.length>0)throw new Pa('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,r);if((e.op==="move"||e.op==="copy")&&typeof e.from!="string")throw new Pa("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,r);if((e.op==="add"||e.op==="replace"||e.op==="test")&&e.value===void 0)t
${t.stack}`:""):typeof t=="string"?t:`${t}`}_addChildRun(t,r){t.child_runs.push(r)}_addRunToRunMap(t){let r=T9t(t.start_time,t.id,t.execution_order),n={...t};if(n.parent_run_id!==void 0){let o=this.runMap.get(n.parent_run_id);o&&(this._addChildRun(o,n),o.child_execution_order=Math.max(o.child_execution_order,n.child_execution_order),n.trace_id=o.trace_id,o.dotted_order!==void 0&&(n.dotted_order=[o.dotted_order,r].join(".")))}else n.trace_id=n.id,n.dotted_order=r;return this.runMap.set(n.id,n),n}async _endTrace(t){let r=t.parent_run_id!==void 0&&this.runMap.get(t.parent_run_id);r?r.child_execution_order=Math.max(r.child_execution_order,t.child_execution_order):await this.persistRun(t),this.runMap.delete(t.id),await this.onRunUpdate?.(t)}_getExecutionOrder(t){let r=t!==void 0&&this.runMap.get(t);return r?r.child_execution_order+1:1}_createRunForLLMStart(t,r,n,o,i,a,s,u){let l=this._getExecutionOrder(o),c=Date.now(),d=s?{...i,metadata:s}:i,f={id:n,name:u??t.id[t.id.length-1],parent_run_id:o,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{prompts:r},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:a||[]};return this._addRunToRunMap(f)}async handleLLMStart(t,r,n,o,i,a,s,u){let l=this.runMap.get(n)??this._createRunForLLMStart(t,r,n,o,i,a,s,u);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}_createRunForChatModelStart(t,r,n,o,i,a,s,u){let l=this._getExecutionOrder(o),c=Date.now(),d=s?{...i,metadata:s}:i,f={id:n,name:u??t.id[t.id.length-1],parent_run_id:o,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{messages:r},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:a||[]};return this._addRunToRunMap(f)}async handleChatModelStart(t,r,n,o,i,a,s,u){let l=this.runMap.get(n)??this._createRunForChatModelStart(t,r,n,o,i,a,s,u);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}async handleLLMEnd(t,r,n,o,i){let a=this.runMap.get(r);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.outputs=t,a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...i},await this.onLLMEnd?.(a),await this._endTrace(a),a}async handleLLMError(t,r,n,o,i){let a=this.runMap.get(r);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(t),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...i},await this.onLLMError?.(a),await this._endTrace(a),a}_createRunForChainStart(t,r,n,o,i,a,s,u){let l=this._getExecutionOrder(o),c=Date.now(),d={id:n,name:u??t.id[t.id.length-1],parent_run_id:o,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:r,execution_order:l,child_execution_order:l,run_type:s??"chain",child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(d)}async handleChainStart(t,r,n,o,i,a,s,u){let l=this.runMap.get(n)??this._createRunForChainStart(t,r,n,o,i,a,s,u);return await this.onRunCreate?.(l),await this.onChainStart?.(l),l}async handleChainEnd(t,r,n,o,i){let a=this.runMap.get(r);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.outputs=xse(t,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=xse(i.inputs,"input")),await this.onChainEnd?.(a),await this._endTrace(a),a}async handleChainError(t,r,n,o,i){let a=this.runMap.get(r);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(t),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=xse(i.inputs,"input")),await this.onChainError?.(a),await this._endTrace(a),a}_createRunForToolStart(t,r,n,o,i,a,s){let u=this._getExecutionOrder(o),l=Date.now(),c={id:n,name:s??t.id[t.id.length-1],parent_run_id:o,start_time:l,serialized:t,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{input:r},execution_order:u,ch
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${t}/
`,e}var $$=C(()=>{});function AD(e){return!!(e&&typeof e=="object"&&"type"in e&&e.type==="tool_call")}var ID,fV=C(()=>{ID=class extends Error{constructor(t,r){super(t),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.output=r}}});function Ose(e,t=RD){e=e.trim();let r=/```(json)?(.*)```/s.exec(e);return t(r?r[2]:e)}function RD(e){if(typeof e>"u")return null;try{return JSON.parse(e)}catch{}let t="",r=[],n=!1,o=!1;for(let i of e){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;t+=i}n&&(t+='"');for(let i=r.length-1;i>=0;i-=1)t+=r[i];try{return JSON.parse(t)}catch{return null}}var Ese=C(()=>{});function eh(e,t){return typeof e=="string"?typeof t=="string"?e+t:[{type:"text",text:e},...t]:Array.isArray(t)?q$(e,t)??[...e,...t]:[...e,{type:"text",text:t}]}function dLe(e,t){return e==="error"||t==="error"?"error":"success"}function I9t(e,t){function r(n,o){if(typeof n!="object"||n===null||n===void 0)return n;if(o>=t)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(e,0),null,2)}function qa(e,t){let r={...e};for(let[n,o]of Object.entries(t))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]=qa(r[n],o);else if(Array.isArray(r[n]))r[n]=q$(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 q$(e,t){if(!(e===void 0&&t===void 0)){if(e===void 0||t===void 0)return e||t;{let r=[...e];for(let n of t)if(typeof n=="object"&&"index"in n&&typeof n.index=="number"){let o=r.findIndex(i=>i.index===n.index);o!==-1?r[o]=qa(r[o],n):r.push(n)}else{if(typeof n=="object"&&"text"in n&&n.text==="")continue;r.push(n)}return r}}}function fLe(e,t){if(!e&&!t)throw new Error("Cannot merge two undefined objects.");if(!e||!t)return e||t;if(typeof e!=typeof t)throw new Error(`Cannot merge objects of different types.
Left ${typeof e}
Right ${typeof t}`);if(typeof e=="string"&&typeof t=="string")return e+t;if(Array.isArray(e)&&Array.isArray(t))return q$(e,t);if(typeof e=="object"&&typeof t=="object")return qa(e,t);if(e===t)return e;throw new Error(`Can not merge objects of different types.
Left ${e}
Right ${t}`)}function pLe(e){return typeof e.role=="string"}function th(e){return typeof e?._getType=="function"}function Pse(e){return th(e)&&typeof e.concat=="function"}var Lu,nf,rh=C(()=>{NM();Lu=class extends tf{get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}get text(){return typeof this.content=="string"?this.content:""}getType(){return this._getType()}constructor(t,r){typeof t=="string"&&(t={content:t,additional_kwargs:r,response_metadata:{}}),t.additional_kwargs||(t.additional_kwargs={}),t.response_metadata||(t.response_metadata={}),super(t),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","messages"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"content",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"additional_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=t.name,this.content=t.content,this.additional_kwargs=t.additional_kwargs,this.response_metadata=t.response_metadata,this.id=t.id}toDict(){return{type:this._getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}_updateId(t){this.id=t,this.lc_kwargs.id=t}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](t){if(t===null)return this;let r=I9t(this._printableFields,Math.max(4,t));return`${this.constructor.lc_name()} ${r}`}};nf=class extends Lu{}});function hLe(e){return e!=null&&typeof e=="object"&&"lc_direct_tool_output"in e&&e.lc_direct_tool_output===!0}function mLe(e){let t=[],r=[];for(let n of e)if(n.function){let o=n.function.name;try{let i=JSON.parse(n.function.arguments),a={name:o||"",args:i||{},id:n.id};t.push(a)}catch{r.push({name:o,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[t,r]}var vS,mO,DD=C(()=>{rh();vS=class extends Lu{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}constructor(t,r,n){typeof t=="string"&&(t={content:t,name:n,tool_call_id:r}),super(t),Object.defineProperty(this,"lc_direct_tool_output",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=t.tool_call_id,this.artifact=t.artifact,this.status=t.status}_getType(){return"tool"}static isInstance(t){return t._getType()==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},mO=class e extends nf{constructor(t){super(t),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=t.tool_call_id,this.artifact=t.artifact,this.status=t.status}static lc_name(){return"ToolMessageChunk"}_getType(){return"tool"}concat(t){return new e({content:eh(this.content,t.content),additional_kwargs:qa(this.additional_kwargs,t.additional_kwargs),response_metadata:qa(this.response_metadata,t.response_metadata),artifact:fLe(this.artifact,t.artifact),tool_call_id:this.tool_call_id,id:this.id??t.id,status:dLe(this.status,t.status)})}get _printableFields(){retu
Please upgrade your packages to versions that set`,"message tool calls. e.g., `yarn add @langchain/anthropic`,","yarn add @langchain/openai`, etc."].join(" "));try{if(o!=null&&i===void 0){let[a,s]=mLe(o);n.tool_calls=a??[],n.invalid_tool_calls=s??[]}else n.tool_calls=n.tool_calls??[],n.invalid_tool_calls=n.invalid_tool_calls??[]}catch{n.tool_calls=[],n.invalid_tool_calls=[]}}super(n),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof n!="string"&&(this.tool_calls=n.tool_calls??this.tool_calls,this.invalid_tool_calls=n.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=n.usage_metadata}static lc_name(){return"AIMessage"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}};Jr=class e extends nf{constructor(t){let r;if(typeof t=="string")r={content:t,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(t.tool_call_chunks===void 0)r={...t,tool_calls:t.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:t.usage_metadata!==void 0?t.usage_metadata:void 0};else{let n=[],o=[];for(let i of t.tool_call_chunks){let a={};try{if(a=RD(i.args||"{}"),a===null||typeof a!="object"||Array.isArray(a))throw new Error("Malformed tool call chunk args.");n.push({name:i.name??"",args:a,id:i.id,type:"tool_call"})}catch{o.push({name:i.name,args:i.args,id:i.id,error:"Malformed args.",type:"invalid_tool_call"})}}r={...t,tool_calls:n,invalid_tool_calls:o,usage_metadata:t.usage_metadata!==void 0?t.usage_metadata:void 0}}super(r),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tool_call_chunks",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_chunks=r.tool_call_chunks??this.tool_call_chunks,this.tool_calls=r.tool_calls??this.tool_calls,this.invalid_tool_calls=r.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=r.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks"}}static lc_name(){return"AIMessageChunk"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(t){let r={content:eh(this.content,t.content),additional_kwargs:qa(this.additional_kwargs,t.additional_kwargs),response_metadata:qa(this.response_metadata,t.response_metadata),tool_call_chunks:[],id:this.id??t.id};if(this.tool_call_chunks!==void 0||t.tool_call_chunks!==void 0){let n=q$(this.tool_call_chunks,t.tool_call_chunks);n!==void 0&&n.length>0&&(r.tool_call_chunks=n)}if(this.usage_metadata!==void 0||t.usage_metadata!==void 0){let n={...(this.usage_metadata?.input_token_details?.audio!==void 0||t.usage_metadata?.input_token_details?.audio!==void 0)&&{audio:(this.usage_metadata?.input_token_details?.audio??0)+(t.usage_metadata?.input_token_details?.audio??0)},...(this.usage_metadata?.input_token_details?.cache_read!==void 0||t.usage_metadata?.input_token_details?.cache_read!==void 0)&&{cache_read:(this.usage_metadata?.input_token_details?.cache_read??0)+(t.usage_metadata?.input_token_details?.cache_read??0)},...(this.usage_metadata?.input_token_details?.cache_creation!==void 0||t.usage_metadata?.input_token_details?.cache_creation!==void 0)&&{cache_creation:(this.usage_metadata?.input_token_details?.cache_creation??0)+(t.usage_metadata?.input_token_details?.cache_creation??0)}},o={...(this
Received: ${JSON.stringify(e,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Nm(e){if(typeof e=="string")return new Ua(e);if(th(e))return e;if(Array.isArray(e)){let[t,r]=e;return Mse({type:t,content:r})}else if(pLe(e)){let{role:t,...r}=e;return Mse({...r,type:t})}else return Mse(e)}function of(e,t="Human",r="AI"){let n=[];for(let o of e){let i;if(o._getType()==="human")i=t;else if(o._getType()==="ai")i=r;else if(o._getType()==="system")i="System";else if(o._getType()==="function")i="Function";else if(o._getType()==="tool")i="Tool";else if(o._getType()==="generic")i=o.role;else throw new Error(`Got unsupported message type: ${o._getType()}`);let a=o.name?`${o.name}, `:"",s=typeof o.content=="string"?o.content:JSON.stringify(o.content,null,2);n.push(`${i}: ${a}${s}`)}return n.join(`
`)}function Ise(e){let t=e._getType();if(t==="human")return new jm({...e});if(t==="ai"){let r={...e};return"tool_calls"in r&&(r={...r,tool_call_chunks:r.tool_calls?.map(n=>({...n,type:"tool_call_chunk",index:void 0,args:JSON.stringify(n.args)}))}),new Jr({...r})}else{if(t==="system")return new ry({...e});if(t==="function")return new wS({...e});if(xd.isInstance(e))return new Dm({...e});throw new Error("Unknown message type.")}}var gO=C(()=>{$$();fV();BM();rh();pV();hV();U$();mV();DD()});var Ase=C(()=>{Q6()});var Rse=C(()=>{Y6()});var Dse,gLe,yLe=C(()=>{Rse();LM();gLe=()=>{if(Dse===void 0){let e=Jt("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};Dse=new RM(e)}return Dse}});var jD,bLe=C(()=>{Ase();hse();LM();kM();yLe();jD=class e extends Xp{constructor(t={}){super(t),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"langchain_tracer"}),Object.defineProperty(this,"projectName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let{exampleId:r,projectName:n,client:o}=t;this.projectName=n??Jt("LANGCHAIN_PROJECT")??Jt("LANGCHAIN_SESSION"),this.exampleId=r,this.client=o??gLe();let i=e.getTraceableRunTree();i&&this.updateFromRunTree(i)}async _convertToCreate(t,r=void 0){return{...t,extra:{...t.extra,runtime:await nLe()},child_runs:void 0,session_name:this.projectName,reference_example_id:t.parent_run_id?void 0:r}}async persistRun(t){}async onRunCreate(t){let r=await this._convertToCreate(t,this.exampleId);await this.client.createRun(r)}async onRunUpdate(t){let r={end_time:t.end_time,error:t.error,outputs:t.outputs,events:t.events,inputs:t.inputs,trace_id:t.trace_id,dotted_order:t.dotted_order,parent_run_id:t.parent_run_id,extra:t.extra};await this.client.updateRun(t.id,r)}getRun(t){return this.runMap.get(t)}updateFromRunTree(t){let r=t,n=new Set;for(;r.parent_run&&!(n.has(r.id)||(n.add(r.id),!r.parent_run));)r=r.parent_run;n.clear();let o=[r];for(;o.length>0;){let i=o.shift();!i||n.has(i.id)||(n.add(i.id),this.runMap.set(i.id,i),i.child_runs&&o.push(...i.child_runs))}this.client=t.client??this.client,this.projectName=t.project_name??this.projectName,this.exampleId=t.reference_example_id??this.exampleId}convertToRunTree(t){let r={},n=[];for(let[o,i]of this.runMap){let a=new bS({...i,child_runs:[],parent_run:void 0,client:this.client,project_name:this.projectName,reference_example_id:this.exampleId,tracingEnabled:!0});r[o]=a,n.push([o,i.dotted_order])}n.sort((o,i)=>!o[1]||!i[1]?0:o[1].localeCompare(i[1]));for(let[o]of n){let i=this.runMap.get(o),a=r[o];if(!(!i||!a)&&i.parent_run_id){let s=r[i.parent_run_id];s&&(s.child_runs.push(a),a.parent_run=s)}}return r[t]}static getTraceableRunTree(){try{return FNe()}catch{return}}}});var _Le,$M,vLe,yO,z$=C(()=>{_Le=Symbol.for("ls:tracing_async_local_storage"),$M=Symbol.for("lc:context_variables"),vLe=e=>{globalThis[_Le]=e},yO=()=>globalThis[_Le]});function j9t(){let e="default"in gV.default?gV.default.default:gV.default;return new e({autoStart:!0,concurrency:1})}function N9t(){return typeof H$>"u"&&(H$=j9t()),H$}async function za(e,t){if(t===!0){let r=yO();r!==void 0?await r.run(void 0,async()=>e()):await e()}else H$=N9t(),H$.add(async()=>{let r=yO();r!==void 0?await r.run(void 0,async()=>e()):await e()})}var gV,H$,wLe=C(()=>{gV=B(j6(),1);z$()});var SLe=C(()=>{wLe()});var xLe,CLe=C(()=>{LM();xLe=e=>e!==void 0?e:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(r=>Jt(r)==="true")});function jse(e){let t=yO();return t===void 0?void 0:t.getStore()?.[$M]?.[e]}var L9t,OLe,ELe=C(()=>{Ase();z$();L9t=Symbol("lc:configure_hooks"),OLe=()=>jse(L9t)||[]});function qM(e){return e?Array.isArray(e)||"name"in e?{callbacks:e}:e:{}}function V$(e){return"name"in e?e:FM.fromMethods(e)}var Nse,ND,Lse,yV,Fse,kse,ns,bO=C(()=>{O$();k$();cLe();gO();LM();bLe();SLe();CLe();kM();ELe();Nse=class{setHandler(t){return t
]))`;continue}else if(n[u]==="$"){o+=`($|(?=[\r
]))`;continue}}if(r.s&&n[u]==="."){o+=a?`${n[u]}\r
`:`[${n[u]}\r
]`;continue}o+=n[u],n[u]==="\\"?i=!0:a&&n[u]==="]"?a=!1:!a&&n[u]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return o}var nue,Fm,H9t,MV=C(()=>{_O();Fm={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(nue===void 0&&(nue=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),nue),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};H9t=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function IV(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===re.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:Lt(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:Lt(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??{}};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===re.ZodString&&e.keyType._def.checks?.length){let{type:n,...o}=TV(e.keyType._def,t);return{...r,propertyNames:o}}else{if(e.keyType?._def.typeName===re.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===re.ZodBranded&&e.keyType._def.type._def.typeName===re.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...o}=EV(e.keyType._def,t);return{...r,propertyNames:o}}}return r}var AV=C(()=>{bd();os();MV();PV()});function QLe(e,t){if(t.mapStrategy==="record")return IV(e,t);let r=Lt(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},n=Lt(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var iue=C(()=>{os();AV()});function eFe(e){let t=e.values,n=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var aue=C(()=>{});function tFe(){return{not:{}}}var sue
`;return t}function gFe(e,t,r){let{firstNode:n,lastNode:o,nodeColors:i,withStyles:a=!0,curveStyle:s="linear",wrapLabelNWords:u=9}=r??{},l=a?`%%{init: {'flowchart': {'curve': '${s}'}}}%%
graph TD;
`:`graph TD;
`;if(a){let p="default",h={[p]:"{0}({1})"};n!==void 0&&(h[n]="{0}([{1}]):::first"),o!==void 0&&(h[o]="{0}([{1}]):::last");for(let[m,_]of Object.entries(e)){let g=_.name.split(":").pop()??"",S=Z9t.some(O=>g.startsWith(O)&&g.endsWith(O))?`<p>${g}</p>`:g;Object.keys(_.metadata??{}).length&&(S+=`<hr/><small><em>${Object.entries(_.metadata??{}).map(([O,T])=>`${O} = ${T}`).join(`
`)}</em></small>`);let x=(h[m]??h[p]).replace("{0}",wue(m)).replace("{1}",S);l+=` ${x}
`}}let c={};for(let p of t){let h=p.source.split(":"),m=p.target.split(":"),_=h.filter((g,v)=>g===m[v]).join(":");c[_]||(c[_]=[]),c[_].push(p)}let d=new Set;function f(p,h){let m=p.length===1&&p[0].source===p[0].target;if(h&&!m){let _=h.split(":").pop();if(d.has(_))throw new Error(`Found duplicate subgraph '${_}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(_),l+=` subgraph ${_}
`}for(let _ of p){let{source:g,target:v,data:S,conditional:x}=_,O="";if(S!==void 0){let T=S,E=T.split(" ");E.length>u&&(T=Array.from({length:Math.ceil(E.length/u)},(M,A)=>E.slice(A*u,(A+1)*u).join(" ")).join("&nbsp;<br>&nbsp;")),O=x?` -. &nbsp;${T}&nbsp; .-> `:` -- &nbsp;${T}&nbsp; --> `}else O=x?" -.-> ":" --> ";l+=` ${wue(g)}${O}${wue(v)};
`}for(let _ in c)_.startsWith(`${h}:`)&&_!==h&&f(c[_],_);h&&!m&&(l+=` end
`)}f(c[""]??[],"");for(let p in c)!p.includes(":")&&p!==""&&f(c[p],p);return a&&(l+=X9t(i??{})),l}async function yFe(e,t){let{backgroundColor:r="white"}=t??{},n=btoa(e);r!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));let o=`https://mermaid.ink/img/${n}?bgColor=${r}`,i=await fetch(o);if(!i.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${i.status}`,`Status text: ${i.statusText}`].join(`
`));return await i.blob()}var Z9t,bFe=C(()=>{Z9t=["*","_","`"]});function Q9t(e,t){if(e!==void 0&&!CD(e))return e;if(Y$(t))try{let r=t.getName();return r=r.startsWith("Runnable")?r.slice(8):r,r}catch{return t.getName()}else return t.name??"UnknownSchema"}function eWt(e){return Y$(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...Li(e.data.schema),title:e.data.name}}}function _Fe(e,t=[]){let r=new Set(e.edges.filter(o=>!t.includes(o.source)).map(o=>o.target)),n=[];for(let o of Object.values(e.nodes))!t.includes(o.id)&&!r.has(o.id)&&n.push(o);return n.length===1?n[0]:void 0}function vFe(e,t=[]){let r=new Set(e.edges.filter(o=>!t.includes(o.target)).map(o=>o.source)),n=[];for(let o of Object.values(e.nodes))!t.includes(o.id)&&!r.has(o.id)&&n.push(o);return n.length===1?n[0]:void 0}var X$,wFe=C(()=>{oh();O$();Use();bFe();X$=class e{constructor(t){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.nodes=t?.nodes??this.nodes,this.edges=t?.edges??this.edges}toJSON(){let t={};return Object.values(this.nodes).forEach((r,n)=>{t[r.id]=CD(r.id)?n:r.id}),{nodes:Object.values(this.nodes).map(r=>({id:t[r.id],...eWt(r)})),edges:this.edges.map(r=>{let n={source:t[r.source],target:t[r.target]};return typeof r.data<"u"&&(n.data=r.data),typeof r.conditional<"u"&&(n.conditional=r.conditional),n})}}addNode(t,r,n){if(r!==void 0&&this.nodes[r]!==void 0)throw new Error(`Node with id ${r} already exists`);let o=r??Xd(),i={id:o,data:t,name:Q9t(r,t),metadata:n};return this.nodes[o]=i,i}removeNode(t){delete this.nodes[t.id],this.edges=this.edges.filter(r=>r.source!==t.id&&r.target!==t.id)}addEdge(t,r,n,o){if(this.nodes[t.id]===void 0)throw new Error(`Source node ${t.id} not in graph`);if(this.nodes[r.id]===void 0)throw new Error(`Target node ${r.id} not in graph`);let i={source:t.id,target:r.id,data:n,conditional:o};return this.edges.push(i),i}firstNode(){return _Fe(this)}lastNode(){return vFe(this)}extend(t,r=""){let n=r;Object.values(t.nodes).map(l=>l.id).every(CD)&&(n="");let i=l=>n?`${n}:${l}`:l;Object.entries(t.nodes).forEach(([l,c])=>{this.nodes[i(l)]={...c,id:i(l)}});let a=t.edges.map(l=>({...l,source:i(l.source),target:i(l.target)}));this.edges=[...this.edges,...a];let s=t.firstNode(),u=t.lastNode();return[s?{id:i(s.id),data:s.data}:void 0,u?{id:i(u.id),data:u.data}:void 0]}trimFirstNode(){let t=this.firstNode();t&&_Fe(this,[t.id])&&this.removeNode(t)}trimLastNode(){let t=this.lastNode();t&&vFe(this,[t.id])&&this.removeNode(t)}reid(){let t=Object.fromEntries(Object.values(this.nodes).map(o=>[o.id,o.name])),r=new Map;Object.values(t).forEach(o=>{r.set(o,(r.get(o)||0)+1)});let n=o=>{let i=t[o];return CD(o)&&r.get(i)===1?i:o};return new e({nodes:Object.fromEntries(Object.entries(this.nodes).map(([o,i])=>[n(o),{...i,id:n(o)}])),edges:this.edges.map(o=>({...o,source:n(o.source),target:n(o.target)}))})}drawMermaid(t){let{withStyles:r,curveStyle:n,nodeColors:o={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:i}=t??{},a=this.reid(),s=a.firstNode(),u=a.lastNode();return gFe(a.nodes,a.edges,{firstNode:s?.id,lastNode:u?.id,withStyles:r,curveStyle:n,nodeColors:o,wrapLabelNWords:i})}async drawMermaidPng(t){let r=this.drawMermaid(t);return yFe(r,{backgroundColor:t?.backgroundColor})}}});function SFe(e){let t=new TextEncoder,r=new ReadableStream({async start(n){for await(let o of e)n.enqueue(t.encode(`event: data
data: ${JSON.stringify(o)}
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
`));n.enqueue(t.encode(`event: end
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
`)),n.close()}});return Nc.fromReadableStream(r)}var xFe=C(()=>{iy()});function Sue(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.iterator]=="function"&&typeof e.next=="function"}function DV(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.asyncIterator]=="function"}function*xue(e,t){for(;;){let{value:r,done:n}=jc.runWithConfig(Xf(e),t.next.bind(t),!0);if(n)break;yield r}}async function*jV(e,t){let r=t[Symbol.asyncIterator]();for(;;){let{value:n,done:o}=await jc.runWithConfig(Xf(e),r.next.bind(t),!0);if(o)break;yield n}}var CFe,OFe=C(()=>{LD();ny();CFe=e=>e!=null&&typeof e=="object"&&"next"in e&&typeof e.next=="function"});function ku(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e=="object"?e:{[t]:e}}function tWt(e){if(nV(e))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}function CS(e){if(typeof e=="function")return new ES({func:e});if(nn.isRunnable(e))return e;if(!Array.isArray(e)&&typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))t[r]=CS(n);return new vO({steps:t})}else throw new Error(`Expected a Runnable, function or object.
Instead got an unsupported type.`)}function rWt(e,t){let r=t.name??e.getName(),n=t.description??t.schema?.description;return t.schema.constructor===Er.ZodString?new Q$({name:r,description:n,schema:Er.object({input:Er.string()}).transform(o=>o.input),bound:e}):new Q$({name:r,description:n,schema:t.schema,bound:e})}var Cue,nn,OS,NV,LV,Ha,vO,Oue,ES,FV,BD,kV,Q$,sf=C(()=>{bd();Cue=B(C6(),1);O$();hse();DLe();NLe();NM();iy();$se();ny();kD();FLe();Use();LD();wFe();xFe();OFe();fV();nn=class extends tf{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(t){let r=this.name??this.constructor.lc_name()??this.constructor.name;return t?`${r}${t}`:r}bind(t){return new OS({bound:this,kwargs:t,config:{}})}map(){return new NV({bound:this})}withRetry(t){return new LV({bound:this,kwargs:{},config:{},maxAttemptNumber:t?.stopAfterAttempt,...t})}withConfig(t){return new OS({bound:this,config:t,kwargs:{}})}withFallbacks(t){let r=Array.isArray(t)?t:t.fallbacks;return new FV({runnable:this,fallbacks:r})}_getOptionsList(t,r=0){if(Array.isArray(t)&&t.length!==r)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${t.length} options for ${r} inputs`);if(Array.isArray(t))return t.map(Rr);if(r>1&&!Array.isArray(t)&&t.runId){console.warn("Provided runId will be used only for the first element of the batch.");let n=Object.fromEntries(Object.entries(t).filter(([o])=>o!=="runId"));return Array.from({length:r},(o,i)=>Rr(i===0?t:n))}return Array.from({length:r},()=>Rr(t))}async batch(t,r,n){let o=this._getOptionsList(r??{},t.length),i=o[0]?.maxConcurrency??n?.maxConcurrency,a=new Qf({maxConcurrency:i,onFailedAttempt:u=>{throw u}}),s=t.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(t,r){yield this.invoke(t,r)}async stream(t,r){let n=Rr(r),o=new xS({generator:this._streamIterator(t,n),config:n});return await o.setup,Nc.fromAsyncGenerator(o)}_separateRunnableConfigFromCallOptions(t){let r;t===void 0?r=Rr(t):r=Rr({callbacks:t.callbacks,tags:t.tags,metadata:t.metadata,runName:t.runName,configurable:t.configurable,recursionLimit:t.recursionLimit,maxConcurrency:t.maxConcurrency,runId:t.runId,timeout:t.timeout,signal:t.signal});let n={...t};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(t,r,n){let o=Rr(n),a=await(await af(o))?.handleChainStart(this.toJSON(),ku(r,"input"),o.runId,o?.runType,void 0,void 0,o?.runName??this.getName());delete o.runId;let s;try{let u=t.call(this,r,o,a);s=await oy(u,n?.signal)}catch(u){throw await a?.handleChainError(u),u}return await a?.handleChainEnd(ku(s,"output")),s}async _batchWithConfig(t,r,n,o){let i=this._getOptionsList(n??{},r.length),a=await Promise.all(i.map(af)),s=await Promise.all(a.map(async(l,c)=>{let d=await l?.handleChainStart(this.toJSON(),ku(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=t.call(this,r,i,s,o);u=await oy(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(ku(u,"output")))),u}async*_transformStreamWithConfig(t,r,n){let o,i=!0,a,s=!0,u=Rr(n),l=await af(u);async function*c(){for await(let f of t){if(i)if(o===void 0)o=f;else try{o=al(o,f)}catch{o=void 0,i=!1}yield f}}let d;try{let f=await MLe(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(jLe),h=f.output;p!==void 0&&d!==void 0&&(h=p.tapOutputIterable(d.runId,h));let m=d?.handlers.find(RLe);m!==void 0&&d!==void 0&&(h=m.tapOutputIterable(d.runId,h));for await(
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}}}
would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
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!
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
\`\`\`json
${JSON.stringify(Li(this.schema))}
\`\`\`
`}async parse(t){try{let n=(t.includes("```")?t.trim().split(/```(?:json)?/)[1]:t.trim()).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(o,i)=>`"${i.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await this.schema.parseAsync(JSON.parse(n))}catch(r){throw new ep(`Failed to parse. Text: "${t}". Error: ${r}`,t)}}}});var Rue=C(()=>{gse()});var TS,Due=C(()=>{wO();Rue();Ese();TS=class extends WM{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}static lc_name(){return"JsonOutputParser"}_diff(t,r){if(r)return t?dV(t,r):[{op:"replace",path:"",value:r}]}async parsePartialResult(t){return Ose(t[0].text)}async parse(t){return Ose(t,JSON.parse)}getFormatInstructions(){return""}}});var $Fe=C(()=>{});var qFe=C(()=>{wO();Rue();$Fe()});var UFe=C(()=>{$D();LFe();FFe();kFe();BFe();wO();Due();qFe()});var SO=C(()=>{UFe()});var tq,qD,UD,zV,rq=C(()=>{NM();U$();gO();tq=class extends tf{},qD=class extends tq{static lc_name(){return"StringPromptValue"}constructor(t){super({value:t}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.value=t}toString(){return this.value}toChatMessages(){return[new Ua(this.value)]}},UD=class extends tq{static lc_name(){return"ChatPromptValue"}constructor(t){Array.isArray(t)&&(t={messages:t}),super(t),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.messages=t.messages}toString(){return of(this.messages)}toChatMessages(){return this.messages}},zV=class extends tq{static lc_name(){return"ImagePromptValue"}constructor(t){"imageUrl"in t||(t={imageUrl:t}),super(t),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"imageUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.imageUrl=t.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new Ua({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}}});var MS,nq=C(()=>{rq();zD();MS=class extends ay{async formatPromptValue(t){let r=await this.format(t);return new qD(r)}}});function Nue(e){return typeof e=="function"}function NWt(e){return VD(e)?"array":typeof e}function jue(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function zFe(e,t){return e!=null&&typeof e=="object"&&t in e}function LWt(e,t){return e!=null&&typeof e!="object"&&e.hasOwnProperty&&e.hasOwnProperty(t)}function kWt(e,t){return FWt.call(e,t)}function $Wt(e){return!kWt(BWt,e)}function UWt(e){return String(e).replace(/[&<>"'`=\/]/g,function(r){return qWt[r]})}function JWt(e,t){if(!e)return[];var r=!1,n=[],o=[],i=[],a=!1,s=!1,u="",l=0;function c(){if(a&&!s)for(;i.length;)delete o[i.pop()];else i=[];a=!1,s=!1}var d,f,p;function h(M){if(typeof M=="string"&&(M=M.split(HWt,2)),!VD(M)||M.length!==2)throw new Error("Invalid tags: "+M);d=new RegExp(jue(M[0])+"\\s*"),f=new RegExp("\\s*"+jue(M[1])),p=new RegExp("\\s*"+jue("}"+M[1]))}h(t||ih.tags);for(var m=new iq(e),_,g,v,S,x,O;!m.eos();){if(_=m.pos,v=m.scanUntil(d),v)for(var T=0,E=v.length;T<E;++T)S=v.charAt(T),$Wt(S)?(i.push(o.length),u+=S):(s=!0,r=!0,u+=" "),o.push(["text",S,_,_+1]),_+=1,S===`
`&&(c(),u="",l=0,r=!1);if(!m.scan(d))break;if(a=!0,g=m.scan(WWt)||"name",m.scan(zWt),g==="="?(v=m.scanUntil(HFe),m.scan(HFe),m.scanUntil(f)):g==="{"?(v=m.scanUntil(p),m.scan(VWt),m.scanUntil(f),g="&"):v=m.scanUntil(f),!m.scan(f))throw new Error("Unclosed tag at "+m.pos);if(g==">"?x=[g,v,_,m.pos,u,l,r]:x=[g,v,_,m.pos],l++,o.push(x),g==="#"||g==="^")n.push(x);else if(g==="/"){if(O=n.pop(),!O)throw new Error('Unopened section "'+v+'" at '+_);if(O[1]!==v)throw new Error('Unclosed section "'+O[1]+'" at '+_)}else g==="name"||g==="{"||g==="&"?s=!0:g==="="&&h(v)}if(c(),O=n.pop(),O)throw new Error('Unclosed section "'+O[1]+'" at '+m.pos);return KWt(GWt(o))}function GWt(e){for(var t=[],r,n,o=0,i=e.length;o<i;++o)r=e[o],r&&(r[0]==="text"&&n&&n[0]==="text"?(n[1]+=r[1],n[3]=r[3]):(t.push(r),n=r));return t}function KWt(e){for(var t=[],r=t,n=[],o,i,a=0,s=e.length;a<s;++a)switch(o=e[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]:t;break;default:r.push(o)}return t}function iq(e){this.string=e,this.tail=e,this.pos=0}function HD(e,t){this.view=e,this.cache={".":this.view},this.parent=t}function Od(){this.templateCache={_cache:{},set:function(t,r){this._cache[t]=r},get:function(t){return this._cache[t]},clear:function(){this._cache={}}}}var jWt,VD,FWt,BWt,qWt,zWt,HWt,HFe,VWt,WWt,ih,oq,HV,VFe=C(()=>{jWt=Object.prototype.toString,VD=Array.isArray||function(t){return jWt.call(t)==="[object Array]"};FWt=RegExp.prototype.test;BWt=/\S/;qWt={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};zWt=/\s*/,HWt=/\s+/,HFe=/\s*=/,VWt=/\s*\}/,WWt=/#|\^|\/|>|\{|&|=|!/;iq.prototype.eos=function(){return this.tail===""};iq.prototype.scan=function(t){var r=this.tail.match(t);if(!r||r.index!==0)return"";var n=r[0];return this.tail=this.tail.substring(n.length),this.pos+=n.length,n};iq.prototype.scanUntil=function(t){var r=this.tail.search(t),n;switch(r){case-1:n=this.tail,this.tail="";break;case 0:n="";break;default:n=this.tail.substring(0,r),this.tail=this.tail.substring(r)}return this.pos+=n.length,n};HD.prototype.push=function(t){return new HD(t,this)};HD.prototype.lookup=function(t){var r=this.cache,n;if(r.hasOwnProperty(t))n=r[t];else{for(var o=this,i,a,s,u=!1;o;){if(t.indexOf(".")>0)for(i=o.view,a=t.split("."),s=0;i!=null&&s<a.length;)s===a.length-1&&(u=zFe(i,a[s])||LWt(i,a[s])),i=i[a[s++]];else i=o.view[t],u=zFe(o.view,t);if(u){n=i;break}o=o.parent}r[t]=n}return Nue(n)&&(n=n.call(this.view)),n};Od.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};Od.prototype.parse=function(t,r){var n=this.templateCache,o=t+":"+(r||ih.tags).join(":"),i=typeof n<"u",a=i?n.get(o):void 0;return a==null&&(a=JWt(t,r),i&&n.set(o,a)),a};Od.prototype.render=function(t,r,n,o){var i=this.getConfigTags(o),a=this.parse(t,i),s=r instanceof HD?r:new HD(r,void 0);return this.renderTokens(a,s,n,t,o)};Od.prototype.renderTokens=function(t,r,n,o,i){for(var a="",s,u,l,c=0,d=t.length;c<d;++c)l=void 0,s=t[c],u=s[0],u==="#"?l=this.renderSection(s,r,n,o,i):u==="^"?l=this.renderInverted(s,r,n,o,i):u===">"?l=this.renderPartial(s,r,n,i):u==="&"?l=this.unescapedValue(s,r):u==="name"?l=this.escapedValue(s,r,i):u==="text"&&(l=this.rawValue(s)),l!==void 0&&(a+=l);return a};Od.prototype.renderSection=function(t,r,n,o,i){var a=this,s="",u=r.lookup(t[1]);function l(f){return a.render(f,r,n,i)}if(u){if(VD(u))for(var c=0,d=u.length;c<d;++c)s+=this.renderTokens(t[4],r.push(u[c]),n,o,i);else if(typeof u=="object"||typeof u=="string"||typeof u=="number")s+=this.renderTokens(t[4],r.push(u),n,o,i);else if(Nue(u)){if(typeof o!="string")throw new Error("Cannot use higher-order sections without the original template");u=u.call(r.view,o.slice(t[3],t[5]),l),u!=null&&(s+=u)}else s+=this.renderTokens(t[4],r,n,o,i);return s}};Od.prototype.renderInverted=function(t,r,n,o,i){var a=r.lookup(t[1]);if(!a||VD(a)&&a.length===0)return this.renderTokens(t[4],r,n,o,i)};Od.prototype.indentPartial=function(t,r,n){for(var o=r.replace(/[^ \t]/g,""),i=t.split(`
`),a=0;a<i.length;a++)i[a].length&&(a>0||!n)&&(i[a]=o+i[a]);return i.join(`
`)};Od.prototype.renderPartial=function(t,r,n,o){if(n){var i=this.getConfigTags(o),a=Nue(n)?n(t[1]):n[t[1]];if(a!=null){var s=t[6],u=t[5],l=t[4],c=a;u==0&&l&&(c=this.indentPartial(a,l,s));var d=this.parse(c,i);return this.renderTokens(d,r,n,c,o)}}};Od.prototype.unescapedValue=function(t,r){var n=r.lookup(t[1]);if(n!=null)return n};Od.prototype.escapedValue=function(t,r,n){var o=this.getConfigEscape(n)||ih.escape,i=r.lookup(t[1]);if(i!=null)return typeof i=="number"&&o===ih.escape?String(i):o(i)};Od.prototype.rawValue=function(t){return t[1]};Od.prototype.getConfigTags=function(t){return VD(t)?t:t&&typeof t=="object"?t.tags:void 0};Od.prototype.getConfigEscape=function(t){if(t&&typeof t=="object"&&!VD(t))return t.escape};ih={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(e){oq.templateCache=e},get templateCache(){return oq.templateCache}},oq=new Od;ih.clearCache=function(){return oq.clearCache()};ih.parse=function(t,r){return oq.parse(t,r)};ih.render=function(t,r,n,o){if(typeof t!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+NWt(t)+'" was given as the first argument for mustache#render(template, view, partials)');return oq.render(t,r,n,o)};ih.escape=UWt;ih.Scanner=iq;ih.Context=HD;ih.Writer=Od;HV=ih});function WFe(){HV.escape=e=>e}var aq,YWt,VV,ZWt,XWt,Lue,QWt,Bm,JFe,JM,WD=C(()=>{VFe();$$();aq=e=>{let t=e.split(""),r=[],n=(i,a)=>{for(let s=a;s<t.length;s+=1)if(i.includes(t[s]))return s;return-1},o=0;for(;o<t.length;)if(t[o]==="{"&&o+1<t.length&&t[o+1]==="{")r.push({type:"literal",text:"{"}),o+=2;else if(t[o]==="}"&&o+1<t.length&&t[o+1]==="}")r.push({type:"literal",text:"}"}),o+=2;else if(t[o]==="{"){let i=n("}",o);if(i<0)throw new Error("Unclosed '{' in template.");r.push({type:"variable",name:t.slice(o+1,i).join("")}),o=i+1}else{if(t[o]==="}")throw new Error("Single '}' in template.");{let i=n("{}",o),a=(i<0?t.slice(o):t.slice(o,i)).join("");r.push({type:"literal",text:a}),o=i<0?t.length:i}}return r},YWt=e=>e.map(t=>t[0]==="name"?{type:"variable",name:t[1].includes(".")?t[1].split(".")[0]:t[1]}:["#","&","^",">"].includes(t[0])?{type:"variable",name:t[1]}:{type:"literal",text:t[1]}),VV=e=>{WFe();let t=HV.parse(e);return YWt(t)},ZWt=(e,t)=>aq(e).reduce((r,n)=>{if(n.type==="variable"){if(n.name in t){let o=typeof t[n.name]=="string"?t[n.name]:JSON.stringify(t[n.name]);return r+o}throw new Error(`(f-string) Missing value for input ${n.name}`)}return r+n.text},""),XWt=(e,t)=>(WFe(),HV.render(e,t)),Lue={"f-string":ZWt,mustache:XWt},QWt={"f-string":aq,mustache:VV},Bm=(e,t,r)=>{try{return Lue[t](e,r)}catch(n){throw hO(n,"INVALID_PROMPT_INPUT")}},JFe=(e,t)=>QWt[t](e),JM=(e,t,r)=>{if(!(t in Lue)){let n=Object.keys(Lue);throw new Error(`Invalid template format. Got \`${t}\`;
should be one of ${n}`)}try{let n=r.reduce((o,i)=>(o[i]="foo",o),{});Array.isArray(e)?e.forEach(o=>{if(o.type==="text")Bm(o.text,t,n);else if(o.type==="image_url")if(typeof o.image_url=="string")Bm(o.image_url,t,n);else{let i=o.image_url.url;Bm(i,t,n)}else throw new Error(`Invalid message template received. ${JSON.stringify(o,null,2)}`)}):Bm(e,t,n)}catch(n){throw new Error(`Invalid prompt schema: ${n.message}`)}}});var Fue={};Kd(Fue,{PromptTemplate:()=>Ed});var Ed,JD=C(()=>{nq();WD();Ed=class e extends MS{static lc_name(){return"PromptTemplate"}constructor(t){if(super(t),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"additionalContentFields",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),t.templateFormat==="mustache"&&t.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,t),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),JM(this.template,this.templateFormat,r)}}_getPromptType(){return"prompt"}async format(t){let r=await this.mergePartialAndUserVariables(t);return Bm(this.template,this.templateFormat,r)}static fromExamples(t,r,n,o=`
`,i=""){let a=[i,...t,r].join(o);return new e({inputVariables:n,template:a})}static fromTemplate(t,r){let{templateFormat:n="f-string",...o}=r??{},i=new Set;return JFe(t,n).forEach(a=>{a.type==="variable"&&i.add(a.name)}),new e({inputVariables:[...i],templateFormat:n,template:t,...o})}async partial(t){let r=this.inputVariables.filter(i=>!(i in t)),n={...this.partialVariables??{},...t},o={...this,inputVariables:r,partialVariables:n};return new e(o)}serialize(){if(this.outputParser!==void 0)throw new Error("Cannot serialize a prompt template with an output parser");return{_type:this._getPromptType(),input_variables:this.inputVariables,template:this.template,template_format:this.templateFormat}}static async deserialize(t){if(!t.template)throw new Error("Prompt template must have a template");return new e({inputVariables:t.input_variables,template:t.template,templateFormat:t.template_format})}}});var GD,kue=C(()=>{rq();zD();WD();GD=class e extends ay{static lc_name(){return"ImagePromptTemplate"}constructor(t){if(super(t),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","image"]}),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"additionalContentFields",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.template=t.template,this.templateFormat=t.templateFormat??this.templateFormat,this.validateTemplate=t.validateTemplate??this.validateTemplate,this.additionalContentFields=t.additionalContentFields,this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),JM([{type:"image_url",image_url:this.template}],this.templateFormat,r)}}_getPromptType(){return"prompt"}async partial(t){let r=this.inputVariables.filter(i=>!(i in t)),n={...this.partialVariables??{},...t},o={...this,inputVariables:r,partialVariables:n};return new e(o)}async format(t){let r={};for(let[a,s]of Object.entries(this.template))typeof s=="string"?r[a]=Bm(s,this.templateFormat,t):r[a]=s;let n=t.url||r.url,o=t.detail||r.detail;if(!n)throw new Error("Must provide either an image URL.");if(typeof n!="string")throw new Error("url must be a string.");let i={url:n};return o&&(i.detail=o),i}async formatPromptValue(t){let r=await this.format(t);return new zV(r)}}});function eJt(e){return typeof e.formatMessages=="function"}function tJt(e,t){if(eJt(e)||th(e))return e;if(Array.isArray(e)&&e[0]==="placeholder"){let o=e[1];if(t?.templateFormat==="mustache"&&typeof o=="string"&&o.slice(0,2)==="{{"&&o.slice(-2)==="}}"){let i=o.slice(2,-2);return new xO({variableName:i,optional:!0})}else if(typeof o=="string"&&o[0]==="{"&&o[o.length-1]==="}"){let i=o.slice(1,-1);return new xO({variableName:i,optional:!0})}throw new Error(`Invalid placeholder template for format ${t?.templateFormat??'"f-string"'}: "${e[1]}". Expected a variable name surrounded by ${t?.templateFormat==="mustache"?"double":"single"} curly braces.`)}let r=Nm(e),n;if(typeof r.content=="string"?n=r.content:n=r.content.map(o=>"text"in o?{...o,text:o.text}:"image_url"in o?{...o,image_url:o.image_url}:o),r._getType()==="human")return CO.fromTemplate(n,t);if(r._getType()==="ai")return que.fromTemplate(n,t);if(r._getType()==="system")return KD.fromTemplate(n,t);if(xd.isInstance(r))return $ue.fromTemplate(r.content,r.role,t);throw new Error(`Could not coerce message prompt template from input. Received message type: "${r._getType()}".`)}function rJt(e){return e.constructor.lc_name()==="MessagesPlaceholder"}var sq,xO,Bue,uq,$ue,lq,CO,que,KD,ah,cq=C(()=>{UM();rq();sf();nq();zD();JD();kue();WD();$$();sq=class extends nn{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","chat"]}),Object.defineProperty(this,"lc_se
`));throw a.name="InputFormatError",a.lc_error_code=o.lc_error_code,a}return n}},Bue=class extends sq{constructor(t){"prompt"in t||(t={prompt:t}),super(t),Object.defineProperty(this,"prompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.prompt=t.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(t){return[await this.format(t)]}},uq=class extends ay{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){let r=await this.formatMessages(t);return new UD(r)}},$ue=class extends Bue{static lc_name(){return"ChatMessagePromptTemplate"}constructor(t,r){"prompt"in t||(t={prompt:t,role:r}),super(t),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=t.role}async format(t){return new xd(await this.prompt.format(t),this.role)}static fromTemplate(t,r,n){return new this(Ed.fromTemplate(t,{templateFormat:n?.templateFormat}),r)}},lq=class extends sq{static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}constructor(t,r){if("prompt"in t||(t={prompt:t}),super(t),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","chat"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"additionalOptions",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"prompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"messageClass",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chatMessageClass",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.prompt=t.prompt,Array.isArray(this.prompt)){let n=[];this.prompt.forEach(o=>{"inputVariables"in o&&(n=n.concat(o.inputVariables))}),this.inputVariables=n}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=r??this.additionalOptions}createMessage(t){let r=this.constructor;if(r._messageClass()){let n=r._messageClass();return new n({content:t})}else if(r.chatMessageClass){let n=r.chatMessageClass();return new n({content:t,role:this.getRoleFromMessageClass(n.lc_name())})}else throw new Error("No message class defined")}getRoleFromMessageClass(t){switch(t){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw new Error("Invalid message class name")}}static fromTemplate(t,r){if(typeof t=="string")return new this(Ed.fromTemplate(t,r));let n=[];for(let o of t)if(typeof o=="string"||typeof o=="object"&&"text"in o){let i="";typeof o=="string"?i=o:typeof o.text=="string"&&(i=o.text??"");let a={...r,...typeof o!="string"?{additionalContentFields:o}:{}};n.push(Ed.fromTemplate(i,a))}else if(typeof o=="object"&&"image_url"in o){let i=o.image_url??"",a,s=[];if(typeof i=="string"){let u;r?.templateFormat==="mustache"?u=VV(i):u=aq(i);let l=u.flatMap(c=>c.type==="variable"?[c.name]:[]);if((l?.length??0)>0){if(l.length>1)throw new Error(`Only one format variable allowed per image template.
Got: ${l}
From: ${i}`);s=[l[0]]}else s=[];i={url:i},a=new GD({template:i,inputVariables:s,templateFormat:r?.templateFormat,additionalContentFields:o})}else if(typeof i=="object"){if("url"in i){let u;r?.templateFormat==="mustache"?u=VV(i.url):u=aq(i.url),s=u.flatMap(l=>l.type==="variable"?[l.name]:[])}else s=[];a=new GD({template:i,inputVariables:s,templateFormat:r?.templateFormat,additionalContentFields:o})}else throw new Error("Invalid image template");n.push(a)}return new this({prompt:n,additionalOptions:r})}async format(t){if(this.prompt instanceof MS){let r=await this.prompt.format(t);return this.createMessage(r)}else{let r=[];for(let n of this.prompt){let o={};if(!("inputVariables"in n))throw new Error(`Prompt ${n} does not have inputVariables defined.`);for(let i of n.inputVariables)o||(o={[i]:t[i]}),o={...o,[i]:t[i]};if(n instanceof MS){let i=await n.format(o),a;"additionalContentFields"in n&&(a=n.additionalContentFields),r.push({...a,type:"text",text:i})}else if(n instanceof GD){let i=await n.format(o),a;"additionalContentFields"in n&&(a=n.additionalContentFields),r.push({...a,type:"image_url",image_url:i})}}return this.createMessage(r)}}async formatMessages(t){return[await this.format(t)]}},CO=class extends lq{static _messageClass(){return Ua}static lc_name(){return"HumanMessagePromptTemplate"}},que=class extends lq{static _messageClass(){return Po}static lc_name(){return"AIMessagePromptTemplate"}},KD=class extends lq{static _messageClass(){return SS}static lc_name(){return"SystemMessagePromptTemplate"}};ah=class e extends uq{static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}constructor(t){if(super(t),Object.defineProperty(this,"promptMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),t.templateFormat==="mustache"&&t.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,t),this.validateTemplate){let r=new Set;for(let s of this.promptMessages)if(!(s instanceof Lu))for(let u of s.inputVariables)r.add(u);let n=this.inputVariables,o=new Set(this.partialVariables?n.concat(Object.keys(this.partialVariables)):n),i=new Set([...o].filter(s=>!r.has(s)));if(i.size>0)throw new Error(`Input variables \`${[...i]}\` are not used in any of the prompt messages.`);let a=new Set([...r].filter(s=>!o.has(s)));if(a.size>0)throw new Error(`Input variables \`${[...a]}\` are used in prompt messages but not in the prompt template.`)}}_getPromptType(){return"chat"}async _parseImagePrompts(t,r){if(typeof t.content=="string")return t;let n=await Promise.all(t.content.map(async o=>{if(o.type!=="image_url")return o;let i="";typeof o.image_url=="string"?i=o.image_url:i=o.image_url.url;let s=await Ed.fromTemplate(i,{templateFormat:this.templateFormat}).format(r);return typeof o.image_url!="string"&&"url"in o.image_url?o.image_url.url=s:o.image_url=s,o}));return t.content=n,t}async formatMessages(t){let r=await this.mergePartialAndUserVariables(t),n=[];for(let o of this.promptMessages)if(o instanceof Lu)n.push(await this._parseImagePrompts(o,r));else{let i=o.inputVariables.reduce((s,u)=>{if(!(u in r)&&!(rJt(o)&&o.optional))throw hO(new Error(`Missing value for input variable \`${u.toString()}\``),"INVALID_PROMPT_INPUT");return s[u]=r[u],s},{}),a=await o.formatMessages(i);n=n.concat(a)}return n}async partial(t){let r=this.inputVariables.filter(i=>!(i in t)),n={...this.partialVariables??{},...t},o={...this,inputVariables:r,partialVariables:n};return new e(o)}static fromTemplate(t,r){let n=Ed.fromTemplate(t,r),o=new CO({prompt:n});return this.fromMessages([o])}static fromMessages(t,r){let n=t.reduce((a,s)=>a.concat(s instanceof e?s.promptMessages:[tJt(s,r)]),[]),o=t.reduce((a,s)=>s instanceof e?Object.assign(a,s.partialVariables):a,Object.create(null)),i=new Set;for(let a of n)if(!(a instanceof Lu))for(let s of a.inputVariables)s in o||i.add(s);return new this({...r,inputVari
`}),Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.assign(this,t),this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),JM(this.prefix+this.suffix,this.templateFormat,r)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(t){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(t);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(t){let r=this.inputVariables.filter(i=>!(i in t)),n={...this.partialVariables??{},...t},o={...this,inputVariables:r,partialVariables:n};return new e(o)}async format(t){let r=await this.mergePartialAndUserVariables(t),n=await this.getExamples(r),o=await Promise.all(n.map(a=>this.examplePrompt.format(a))),i=[this.prefix,...o,this.suffix].join(this.exampleSeparator);return Bm(i,this.templateFormat,r)}serialize(){if(this.exampleSelector||!this.examples)throw new Error("Serializing an example selector is not currently supported");if(this.outputParser!==void 0)throw new Error("Serializing an output parser is not currently supported");return{_type:this._getPromptType(),input_variables:this.inputVariables,example_prompt:this.examplePrompt.serialize(),example_separator:this.exampleSeparator,suffix:this.suffix,prefix:this.prefix,template_format:this.templateFormat,examples:this.examples}}static async deserialize(t){let{example_prompt:r}=t;if(!r)throw new Error("Missing example prompt");let n=await Ed.deserialize(r),o;if(Array.isArray(t.examples))o=t.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new e({inputVariables:t.input_variables,examplePrompt:n,examples:o,exampleSeparator:t.example_separator,prefix:t.prefix,suffix:t.suffix,templateFormat:t.template_format})}},zue=class e extends uq{_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}constructor(t){if(super(t),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"examples",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleSelector",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"examplePrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"suffix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"exampleSeparator",{enumerable:!0,configurable:!0,writable:!0,value:`
`}),Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.examples=t.examples,this.examplePrompt=t.examplePrompt,this.exampleSeparator=t.exampleSeparator??`
`,this.exampleSelector=t.exampleSelector,this.prefix=t.prefix??"",this.suffix=t.suffix??"",this.templateFormat=t.templateFormat??"f-string",this.validateTemplate=t.validateTemplate??!0,this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),JM(this.prefix+this.suffix,this.templateFormat,r)}}async getExamples(t){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(t);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(t){let r=await this.mergePartialAndUserVariables(t),n=await this.getExamples(r);n=n.map(i=>{let a={};return this.examplePrompt.inputVariables.forEach(s=>{a[s]=i[s]}),a});let o=[];for(let i of n){let a=await this.examplePrompt.formatMessages(i);o.push(...a)}return o}async format(t){let r=await this.mergePartialAndUserVariables(t),n=await this.getExamples(r),i=(await Promise.all(n.map(s=>this.examplePrompt.formatMessages(s)))).flat().map(s=>s.content),a=[this.prefix,...i,this.suffix].join(this.exampleSeparator);return Bm(a,this.templateFormat,r)}async partial(t){let r=this.inputVariables.filter(i=>!(i in t)),n={...this.partialVariables??{},...t},o={...this,inputVariables:r,partialVariables:n};return new e(o)}}});var ay,zD=C(()=>{sf();ay=class extends nn{get lc_attributes(){return{partialVariables:void 0}}constructor(t){super(t),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts",this._getPromptType()]}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputParser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"partialVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let{inputVariables:r}=t;if(r.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,t)}async mergePartialAndUserVariables(t){let r=this.partialVariables??{},n={};for(let[i,a]of Object.entries(r))typeof a=="string"?n[i]=a:n[i]=await a();return{...n,...t}}async invoke(t,r){let n={...this.metadata,...r?.metadata},o=[...this.tags??[],...r?.tags??[]];return this._callWithConfig(i=>this.formatPromptValue(i),t,{...r,tags:o,metadata:n,runType:"prompt"})}serialize(){throw new Error("Use .toJSON() instead")}static async deserialize(t){switch(t._type){case"prompt":{let{PromptTemplate:r}=await Promise.resolve().then(()=>(JD(),Fue));return r.deserialize(t)}case void 0:{let{PromptTemplate:r}=await Promise.resolve().then(()=>(JD(),Fue));return r.deserialize({...t,_type:"prompt"})}case"few_shot":{let{FewShotPromptTemplate:r}=await Promise.resolve().then(()=>(Hue(),GFe));return r.deserialize(t)}default:throw new Error(`Invalid prompt type in config: ${t._type}`)}}}});var KFe=C(()=>{zD();cq()});var YFe=C(()=>{});var ZFe=C(()=>{cq()});var XFe=C(()=>{zD();cq();Hue();KFe();JD();YFe();nq();WD();kue();ZFe()});var GM=C(()=>{XFe()});var IS=C(()=>{Pue()});var gke=b(on=>{"use strict";var fq=Symbol.for("react.element"),cJt=Symbol.for("react.portal"),dJt=Symbol.for("react.fragment"),fJt=Symbol.for("react.strict_mode"),pJt=Symbol.for("react.profiler"),hJt=Symbol.for("react.provider"),mJt=Symbol.for("react.context"),gJt=Symbol.for("react.forward_ref"),yJt=Symbol.for("react.suspense"),bJt=Symbol.for("react.memo"),_Jt=Symbol.for("react.lazy"),ake=Symbol.iterato
[`+H+"] ";for(ae in arguments[0])i(arguments[0],ae)&&(R+=ae+": "+arguments[0][ae]+", ");R=R.slice(0,-2)}else R=arguments[H];I.push(R)}E(y+`
Arguments: `+Array.prototype.slice.call(I).join("")+`
`+new Error().stack),P=!1}return w.apply(this,arguments)},w)}var A={};function j(y,w){t.deprecationHandler!=null&&t.deprecationHandler(y,w),A[y]||(E(w),A[y]=!0)}t.suppressDeprecationWarnings=!1,t.deprecationHandler=null;function N(y){return typeof Function<"u"&&y instanceof Function||Object.prototype.toString.call(y)==="[object Function]"}function F(y){var w,P;for(P in y)i(y,P)&&(w=y[P],N(w)?this[P]=w:this["_"+P]=w);this._config=y,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)}function k(y,w){var P=d({},y),I;for(I in w)i(w,I)&&(o(y[I])&&o(w[I])?(P[I]={},d(P[I],y[I]),d(P[I],w[I])):w[I]!=null?P[I]=w[I]:delete P[I]);for(I in y)i(y,I)&&!i(w,I)&&o(y[I])&&(P[I]=d({},P[I]));return P}function L(y){y!=null&&this.set(y)}var q;Object.keys?q=Object.keys:q=function(y){var w,P=[];for(w in y)i(y,w)&&P.push(w);return P};var U={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"};function G(y,w,P){var I=this._calendar[y]||this._calendar.sameElse;return N(I)?I.call(w,P):I}function V(y,w,P){var I=""+Math.abs(y),R=w-I.length,H=y>=0;return(H?P?"+":"":"-")+Math.pow(10,Math.max(0,R)).toString().substr(1)+I}var D=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,z=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,W={},J={};function te(y,w,P,I){var R=I;typeof I=="string"&&(R=function(){return this[I]()}),y&&(J[y]=R),w&&(J[w[0]]=function(){return V(R.apply(this,arguments),w[1],w[2])}),P&&(J[P]=function(){return this.localeData().ordinal(R.apply(this,arguments),y)})}function Ae(y){return y.match(/\[[\s\S]/)?y.replace(/^\[|\]$/g,""):y.replace(/\\/g,"")}function Z(y){var w=y.match(D),P,I;for(P=0,I=w.length;P<I;P++)J[w[P]]?w[P]=J[w[P]]:w[P]=Ae(w[P]);return function(R){var H="",ae;for(ae=0;ae<I;ae++)H+=N(w[ae])?w[ae].call(R,y):w[ae];return H}}function Q(y,w){return y.isValid()?(w=ue(w,y.localeData()),W[w]=W[w]||Z(w),W[w](y)):y.localeData().invalidDate()}function ue(y,w){var P=5;function I(R){return w.longDateFormat(R)||R}for(z.lastIndex=0;P>=0&&z.test(y);)y=y.replace(z,I),z.lastIndex=0,P-=1;return y}var Me={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"};function ht(y){var w=this._longDateFormat[y],P=this._longDateFormat[y.toUpperCase()];return w||!P?w:(this._longDateFormat[y]=P.match(D).map(function(I){return I==="MMMM"||I==="MM"||I==="DD"||I==="dddd"?I.slice(1):I}).join(""),this._longDateFormat[y])}var we="Invalid date";function ie(){return this._invalidDate}var ee="%d",ge=/\d{1,2}/;function Ue(y){return this._ordinal.replace("%d",y)}var ct={future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",w:"a week",ww:"%d weeks",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function Je(y,w,P,I){var R=this._relativeTime[P];return N(R)?R(y,w,P,I):R.replace(/%d/i,y)}function sr(y,w){var P=this._relativeTime[y>0?"future":"past"];return N(P)?P(w):P.replace(/%s/i,w)}var Xr={};function ur(y,w){var P=y.toLowerCase();Xr[P]=Xr[P+"s"]=Xr[w]=y}function Bt(y){return typeof y=="string"?Xr[y]||Xr[y.toLowerCase()]:void 0}function Bo(y){var w={},P,I;for(I in y)i(y,I)&&(P=Bt(I),P&&(w[P]=y[I]));return w}var Xi={};function jo(y,w){Xi[y]=w}function Ie(y){var w=[],P;for(P in y)i(y,P)&&w.push({unit:P,priority:Xi[P]});return w.sort(function(I,R){return I.priority-R.priority}),w}function Ze(y){return y%4===0&&y%100!==0||y%400===0}function lr(y){return y<0?Math.ceil(y)||0:Math.floor(y)}function Xe(y){var w=+y,P=0;return w!==0&&isFinite(w)&&(P=lr(w)),P}function Bn(y,w){return function(P){return P!=null?(ol(this,y,P),t.updateOffset(this,w),this):Qi(this,y)}}function Qi(y,w){return y.isValid()?y._d["get"+(y._isUTC?"UTC":"")+w]():NaN}function ol(y,w,P){y.isValid()&&!isNaN(P)&&(w==="FullYear"&&Ze(y.year
`+Jle+e}var Gle=!1;function Kle(e,t){if(!e||Gle)return"";Gle=!0;var r=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(t)if(t=function(){throw Error()},Object.defineProperty(t.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(t,[])}catch(l){var n=l}Reflect.construct(e,[],t)}else{try{t.call()}catch(l){n=l}e.call(t.prototype)}else{try{throw Error()}catch(l){n=l}e()}}catch(l){if(l&&n&&typeof l.stack=="string"){for(var o=l.stack.split(`
`),i=n.stack.split(`
`),a=o.length-1,s=i.length-1;1<=a&&0<=s&&o[a]!==i[s];)s--;for(;1<=a&&0<=s;a--,s--)if(o[a]!==i[s]){if(a!==1||s!==1)do if(a--,s--,0>s||o[a]!==i[s]){var u=`
`+o[a].replace(" at new "," at ");return e.displayName&&u.includes("<anonymous>")&&(u=u.replace("<anonymous>",e.displayName)),u}while(1<=a&&0<=s);break}}}finally{Gle=!1,Error.prepareStackTrace=r}return(e=e?e.displayName||e.name:"")?Iq(e):""}function _Gt(e){switch(e.tag){case 5:return Iq(e.type);case 16:return Iq("Lazy");case 13:return Iq("Suspense");case 19:return Iq("SuspenseList");case 0:case 2:case 15:return e=Kle(e.type,!1),e;case 11:return e=Kle(e.type.render,!1),e;case 1:return e=Kle(e.type,!0),e;default:return""}}function _ce(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case hj:return"Fragment";case pj:return"Portal";case gce:return"Profiler";case cde:return"StrictMode";case yce:return"Suspense";case bce:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case L$e:return(e.displayName||"Context")+".Consumer";case N$e:return(e._context.displayName||"Context")+".Provider";case dde:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case fde:return t=e.displayName||null,t!==null?t:_ce(e.type)||"Memo";case NO:t=e._payload,e=e._init;try{return _ce(e(t))}catch{}}return null}function vGt(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return _ce(t);case 8:return t===cde?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function KO(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function k$e(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function wGt(e){var t=k$e(e)?"checked":"value",r=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),n=""+e[t];if(!e.hasOwnProperty(t)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var o=r.get,i=r.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(a){n=""+a,i.call(this,a)}}),Object.defineProperty(e,t,{enumerable:r.enumerable}),{getValue:function(){return n},setValue:function(a){n=""+a},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function S5(e){e._valueTracker||(e._valueTracker=wGt(e))}function B$e(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var r=t.getValue(),n="";return e&&(n=k$e(e)?e.checked?"true":"false":e.value),e=n,e!==r?(t.setValue(e),!0):!1}function Y5(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function vce(e,t){var r=t.checked;return na({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??e._wrapperState.initialChecked})}function IBe(e,t){var r=t.defaultValue==null?"":t.defaultValue,n=t.checked!=null?t.checked:t.defaultChecked;r=KO(t.value!=null?t.value:r),e._wrapperState={initialChecked:n,initialValue:r,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function $$e(e,t){t=t.checked,t!=null&&lde(e,"checked",t,!1)}function wce(e,t){$$e(e,t);var r=KO(t.value),n=t.type;if(r!=null)n==="number"?(r===0&&e.value===""||e.value!=r)&&(e.value=""+r):e.value!==""+r&&(e.value=""+r);else if(n==="submit"||n==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Sce(e,t.type,r):t.hasOwnProperty("defaultValue")&&Sce(e,t.type,KO(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function A
`).replace(MKt,"")}function j5(e,t,r){if(t=t$e(t),t$e(e)!==t&&r)throw Error(Ce(425))}function o9(){}var Lce=null,Fce=null;function kce(e,t){return e==="textarea"||e==="noscript"||typeof t.children=="string"||typeof t.children=="number"||typeof t.dangerouslySetInnerHTML=="object"&&t.dangerouslySetInnerHTML!==null&&t.dangerouslySetInnerHTML.__html!=null}var Bce=typeof setTimeout=="function"?setTimeout:void 0,IKt=typeof clearTimeout=="function"?clearTimeout:void 0,r$e=typeof Promise=="function"?Promise:void 0,AKt=typeof queueMicrotask=="function"?queueMicrotask:typeof r$e<"u"?function(e){return r$e.resolve(null).then(e).catch(RKt)}:Bce;function RKt(e){setTimeout(function(){throw e})}function ice(e,t){var r=t,n=0;do{var o=r.nextSibling;if(e.removeChild(r),o&&o.nodeType===8)if(r=o.data,r==="/$"){if(n===0){e.removeChild(o),Gq(t);return}n--}else r!=="$"&&r!=="$?"&&r!=="$!"||n++;r=o}while(r);Gq(t)}function HO(e){for(;e!=null;e=e.nextSibling){var t=e.nodeType;if(t===1||t===3)break;if(t===8){if(t=e.data,t==="$"||t==="$!"||t==="$?")break;if(t==="/$")return null}}return e}function n$e(e){e=e.previousSibling;for(var t=0;e;){if(e.nodeType===8){var r=e.data;if(r==="$"||r==="$!"||r==="$?"){if(t===0)return e;t--}else r==="/$"&&t++}e=e.previousSibling}return null}var Bj=Math.random().toString(36).slice(2),my="__reactFiber$"+Bj,Qq="__reactProps$"+Bj,US="__reactContainer$"+Bj,$ce="__reactEvents$"+Bj,DKt="__reactListeners$"+Bj,jKt="__reactHandles$"+Bj;function sI(e){var t=e[my];if(t)return t;for(var r=e.parentNode;r;){if(t=r[US]||r[my]){if(r=t.alternate,t.child!==null||r!==null&&r.child!==null)for(e=n$e(e);e!==null;){if(r=e[my])return r;e=n$e(e)}return t}e=r,r=e.parentNode}return null}function uU(e){return e=e[my]||e[US],!e||e.tag!==5&&e.tag!==6&&e.tag!==13&&e.tag!==3?null:e}function bj(e){if(e.tag===5||e.tag===6)return e.stateNode;throw Error(Ce(33))}function C9(e){return e[Qq]||null}var qce=[],_j=-1;function XO(e){return{current:e}}function vi(e){0>_j||(e.current=qce[_j],qce[_j]=null,_j--)}function ai(e,t){_j++,qce[_j]=e.current,e.current=t}var YO={},qc=XO(YO),pf=XO(!1),fI=YO;function Rj(e,t){var r=e.type.contextTypes;if(!r)return YO;var n=e.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===t)return n.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in r)o[i]=t[i];return n&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function hf(e){return e=e.childContextTypes,e!=null}function i9(){vi(pf),vi(qc)}function o$e(e,t,r){if(qc.current!==YO)throw Error(Ce(168));ai(qc,t),ai(pf,r)}function Tqe(e,t,r){var n=e.stateNode;if(t=t.childContextTypes,typeof n.getChildContext!="function")return r;n=n.getChildContext();for(var o in n)if(!(o in t))throw Error(Ce(108,vGt(e)||"Unknown",o));return na({},r,n)}function a9(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||YO,fI=qc.current,ai(qc,e),ai(pf,pf.current),!0}function i$e(e,t,r){var n=e.stateNode;if(!n)throw Error(Ce(169));r?(e=Tqe(e,t,fI),n.__reactInternalMemoizedMergedChildContext=e,vi(pf),vi(qc),ai(qc,e)):vi(pf),ai(pf,r)}var FS=null,O9=!1,ace=!1;function Mqe(e){FS===null?FS=[e]:FS.push(e)}function NKt(e){O9=!0,Mqe(e)}function QO(){if(!ace&&FS!==null){ace=!0;var e=0,t=No;try{var r=FS;for(No=1;e<r.length;e++){var n=r[e];do n=n(!0);while(n!==null)}FS=null,O9=!1}catch(o){throw FS!==null&&(FS=FS.slice(e+1)),eqe(hde,QO),o}finally{No=t,ace=!1}}return null}var vj=[],wj=0,s9=null,u9=0,ch=[],dh=0,pI=null,kS=1,BS="";function iI(e,t){vj[wj++]=u9,vj[wj++]=s9,s9=e,u9=t}function Iqe(e,t,r){ch[dh++]=kS,ch[dh++]=BS,ch[dh++]=pI,pI=e;var n=kS;e=BS;var o=32-Jm(n)-1;n&=~(1<<o),r+=1;var i=32-Jm(t)+o;if(30<i){var a=o-o%5;i=(n&(1<<a)-1).toString(32),n>>=a,o-=a,kS=1<<32-Jm(t)+o|r<<o|n,BS=i+e}else kS=1<<i|r<<o|n,BS=e}function xde(e){e.return!==null&&(iI(e,1),Iqe(e,1,0))}function Cde(e){for(;e===s9;)s9=vj[--wj],vj[wj]=null,u9=vj[--wj],vj[wj]=null;for(;e===pI;)pI=ch[--dh],ch[dh]=null,BS=ch[--dh],ch[dh]=null,kS=ch[--dh],ch[dh]=null}var ip=null,op=null,Bi=!1,Wm=null;function Aqe(e,t){var r=fh(5,null,null,0);r.elementT
Error generating stack: `+i.message+`
`+i.stack}return{value:e,source:t,stack:o,digest:null}}function dce(e,t,r){return{value:e,source:null,stack:r??null,digest:t??null}}function Jce(e,t){try{console.error(t.value)}catch(r){setTimeout(function(){throw r})}}var HKt=typeof WeakMap=="function"?WeakMap:Map;function iUe(e,t,r){r=$S(-1,r),r.tag=3,r.payload={element:null};var n=t.value;return r.callback=function(){g9||(g9=!0,nde=n),Jce(e,t)},r}function aUe(e,t,r){r=$S(-1,r),r.tag=3;var n=e.type.getDerivedStateFromError;if(typeof n=="function"){var o=t.value;r.payload=function(){return n(o)},r.callback=function(){Jce(e,t)}}var i=e.stateNode;return i!==null&&typeof i.componentDidCatch=="function"&&(r.callback=function(){Jce(e,t),typeof n!="function"&&(WO===null?WO=new Set([this]):WO.add(this));var a=t.stack;this.componentDidCatch(t.value,{componentStack:a!==null?a:""})}),r}function m$e(e,t,r){var n=e.pingCache;if(n===null){n=e.pingCache=new HKt;var o=new Set;n.set(t,o)}else o=n.get(t),o===void 0&&(o=new Set,n.set(t,o));o.has(r)||(o.add(r),e=o7t.bind(null,e,t,r),t.then(e,e))}function g$e(e){do{var t;if((t=e.tag===13)&&(t=e.memoizedState,t=t!==null?t.dehydrated!==null:!0),t)return e;e=e.return}while(e!==null);return null}function y$e(e,t,r,n,o){return(e.mode&1)===0?(e===t?e.flags|=65536:(e.flags|=128,r.flags|=131072,r.flags&=-52805,r.tag===1&&(r.alternate===null?r.tag=17:(t=$S(-1,1),t.tag=2,VO(r,t,1))),r.lanes|=1),e):(e.flags|=65536,e.lanes=o,e)}var VKt=VS.ReactCurrentOwner,ff=!1;function Md(e,t,r,n){t.child=e===null?kqe(t,null,r,n):jj(t,e.child,r,n)}function b$e(e,t,r,n,o){r=r.render;var i=t.ref;return Mj(t,o),n=Nde(e,t,r,n,i,o),r=Lde(),e!==null&&!ff?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~o,HS(e,t,o)):(Bi&&r&&xde(t),t.flags|=1,Md(e,t,n,o),t.child)}function _$e(e,t,r,n,o){if(e===null){var i=r.type;return typeof i=="function"&&!Wde(i)&&i.defaultProps===void 0&&r.compare===null&&r.defaultProps===void 0?(t.tag=15,t.type=i,sUe(e,t,i,n,o)):(e=K5(r.type,null,n,t,t.mode,o),e.ref=t.ref,e.return=t,t.child=e)}if(i=e.child,(e.lanes&o)===0){var a=i.memoizedProps;if(r=r.compare,r=r!==null?r:Yq,r(a,n)&&e.ref===t.ref)return HS(e,t,o)}return t.flags|=1,e=GO(i,n),e.ref=t.ref,e.return=t,t.child=e}function sUe(e,t,r,n,o){if(e!==null){var i=e.memoizedProps;if(Yq(i,n)&&e.ref===t.ref)if(ff=!1,t.pendingProps=n=i,(e.lanes&o)!==0)(e.flags&131072)!==0&&(ff=!0);else return t.lanes=e.lanes,HS(e,t,o)}return Gce(e,t,r,n,o)}function uUe(e,t,r){var n=t.pendingProps,o=n.children,i=e!==null?e.memoizedState:null;if(n.mode==="hidden")if((t.mode&1)===0)t.memoizedState={baseLanes:0,cachePool:null,transitions:null},ai(Cj,np),np|=r;else{if((r&1073741824)===0)return e=i!==null?i.baseLanes|r:r,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,ai(Cj,np),np|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},n=i!==null?i.baseLanes:r,ai(Cj,np),np|=n}else i!==null?(n=i.baseLanes|r,t.memoizedState=null):n=r,ai(Cj,np),np|=n;return Md(e,t,o,r),t.child}function lUe(e,t){var r=t.ref;(e===null&&r!==null||e!==null&&e.ref!==r)&&(t.flags|=512,t.flags|=2097152)}function Gce(e,t,r,n,o){var i=hf(r)?fI:qc.current;return i=Rj(t,i),Mj(t,o),r=Nde(e,t,r,n,i,o),n=Lde(),e!==null&&!ff?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~o,HS(e,t,o)):(Bi&&n&&xde(t),t.flags|=1,Md(e,t,r,o),t.child)}function v$e(e,t,r,n,o){if(hf(r)){var i=!0;a9(t)}else i=!1;if(Mj(t,o),t.stateNode===null)W5(e,t),Lqe(t,r,n),Wce(t,r,n,o),n=!0;else if(e===null){var a=t.stateNode,s=t.memoizedProps;a.props=s;var u=a.context,l=r.contextType;typeof l=="object"&&l!==null?l=hh(l):(l=hf(r)?fI:qc.current,l=Rj(t,l));var c=r.getDerivedStateFromProps,d=typeof c=="function"||typeof a.getSnapshotBeforeUpdate=="function";d||typeof a.UNSAFE_componentWillReceiveProps!="function"&&typeof a.componentWillReceiveProps!="function"||(s!==n||u!==l)&&d$e(t,a,n,l),LO=!1;var f=t.memoizedState;a.state=f,d9(t,n,a,o),u=t.memoizedState,s!==n||f!==u||pf.current||LO?(typeof c=="function"&&(Vce(t,r,c,n),u=t.memoizedState),(s=LO||c$e(t,r,s,n,f,u,l))?(d||typeof a.UNSAFE_componentWillMount!="funct
`)}});var NVe=b(SW=>{"use strict";Object.defineProperty(SW,"__esModule",{value:!0});SW.CohereTimeoutError=void 0;var mfe=class e extends Error{constructor(){super("Timeout"),Object.setPrototypeOf(this,e.prototype)}};SW.CohereTimeoutError=mfe});var Wa=b(Kj=>{"use strict";Object.defineProperty(Kj,"__esModule",{value:!0});Kj.CohereTimeoutError=Kj.CohereError=void 0;var $Yt=jVe();Object.defineProperty(Kj,"CohereError",{enumerable:!0,get:function(){return $Yt.CohereError}});var qYt=NVe();Object.defineProperty(Kj,"CohereTimeoutError",{enumerable:!0,get:function(){return qYt.CohereTimeoutError}})});var LVe=b(wy=>{"use strict";var UYt=wy&&wy.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),zYt=wy&&wy.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),HYt=wy&&wy.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&UYt(t,e,r);return zYt(t,e),t};Object.defineProperty(wy,"__esModule",{value:!0});wy.BadRequestError=void 0;var VYt=HYt(Wa()),gfe=class e extends VYt.CohereError{constructor(t){super({message:"BadRequestError",statusCode:400,body:t}),Object.setPrototypeOf(this,e.prototype)}};wy.BadRequestError=gfe});var FVe=b(Sy=>{"use strict";var WYt=Sy&&Sy.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),JYt=Sy&&Sy.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),GYt=Sy&&Sy.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&WYt(t,e,r);return JYt(t,e),t};Object.defineProperty(Sy,"__esModule",{value:!0});Sy.UnauthorizedError=void 0;var KYt=GYt(Wa()),yfe=class e extends KYt.CohereError{constructor(t){super({message:"UnauthorizedError",statusCode:401,body:t}),Object.setPrototypeOf(this,e.prototype)}};Sy.UnauthorizedError=yfe});var kVe=b(xy=>{"use strict";var YYt=xy&&xy.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),ZYt=xy&&xy.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),XYt=xy&&xy.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&YYt(t,e,r);return ZYt(t,e),t};Object.defineProperty(xy,"__esModule",{value:!0});xy.ForbiddenError=void 0;var QYt=XYt(Wa()),bfe=class e extends QYt.CohereError{constructor(t){super({message:"ForbiddenError",statusCode:403,body:t}),Object.setPrototypeOf(this,e.prototype)}};xy.ForbiddenError=bfe});var BVe=b(Cy=>{"use strict";var eZt=Cy&&Cy.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),tZt=Cy&&Cy.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),rZt=Cy&&Cy.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&eZt(t,e,r);r
`));return r(o)}});var fGe,KXt,YXt,ZXt,XXt,QXt,pGe=C(()=>{fGe=async e=>{let t=e?.Bucket||"";if(typeof e.Bucket=="string"&&(e.Bucket=t.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),QXt(t)){if(e.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!XXt(t)||t.indexOf(".")!==-1&&!String(e.Endpoint).startsWith("http:")||t.toLowerCase()!==t||t.length<3)&&(e.ForcePathStyle=!0);return e.DisableMultiRegionAccessPoints&&(e.disableMultiRegionAccessPoints=!0,e.DisableMRAP=!0),e},KXt=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,YXt=/(\d+\.){3}\d+/,ZXt=/\.\./,XXt=e=>KXt.test(e)&&!YXt.test(e)&&!ZXt.test(e),QXt=e=>{let[t,r,n,,,o]=e.split(":"),i=t==="arn"&&e.split(":").length>=6,a=!!(i&&r&&n&&o);if(i&&!a)throw new Error(`Invalid ARN: ${e} was an invalid ARN.`);return a}});var hGe=C(()=>{pGe()});var mGe,gGe=C(()=>{mGe=(e,t,r)=>{let n=async()=>{let o=r[e]??r[t];return typeof o=="function"?o():o};return e==="credentialScope"||t==="CredentialScope"?async()=>{let o=typeof r.credentials=="function"?await r.credentials():r.credentials;return o?.credentialScope??o?.CredentialScope}:e==="accountId"||t==="AccountId"?async()=>{let o=typeof r.credentials=="function"?await r.credentials():r.credentials;return o?.accountId??o?.AccountId}:e==="endpoint"||t==="endpoint"?async()=>{let o=await n();if(o&&typeof o=="object"){if("url"in o)return o.url.href;if("hostname"in o){let{protocol:i,hostname:a,port:s,path:u}=o;return`${i}//${a}${s?":"+s:""}${u}`}}return o}:n}});var yGe,bGe=C(()=>{yGe=async e=>{}});function _Ge(e){let t={};if(e=e.replace(/^\?/,""),e)for(let r of e.split("&")){let[n,o=null]=r.split("=");n=decodeURIComponent(n),o&&(o=decodeURIComponent(o)),n in t?Array.isArray(t[n])?t[n].push(o):t[n]=[t[n],o]:t[n]=o}return t}var vGe=C(()=>{});var fE,cJ=C(()=>{vGe();fE=e=>{if(typeof e=="string")return fE(new URL(e));let{hostname:t,pathname:r,port:n,protocol:o,search:i}=e,a;return i&&(a=_Ge(i)),{hostname:t,port:n?parseInt(n):void 0,protocol:o,path:r,query:a}}});var dJ,fJ=C(()=>{cJ();dJ=e=>typeof e=="object"?"url"in e?fE(e.url):e:fE(e)});var wGe,eQt,cpe=C(()=>{hGe();gGe();bGe();fJ();wGe=async(e,t,r,n)=>{if(!r.endpoint){let a=await yGe(r.serviceId||"");a&&(r.endpoint=()=>Promise.resolve(dJ(a)))}let o=await eQt(e,t,r);if(typeof r.endpointProvider!="function")throw new Error("config.endpointProvider is not set.");return r.endpointProvider(o,n)},eQt=async(e,t,r)=>{let n={},o=t?.getEndpointParameterInstructions?.()||{};for(let[i,a]of Object.entries(o))switch(a.type){case"staticContextParams":n[i]=a.value;break;case"contextParams":n[i]=e[a.name];break;case"clientContextParams":case"builtInParams":n[i]=await mGe(a.name,i,r)();break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(a))}return Object.keys(o).length===0&&Object.assign(n,r),String(r.serviceId).toLowerCase()==="s3"&&await fGe(n),n}});var SGe=C(()=>{cpe();fJ()});var xGe,dpe=C(()=>{eg();cpe();xGe=({config:e,instructions:t})=>(r,n)=>async o=>{let i=await wGe(o.input,{getEndpointParameterInstructions(){return t}},{...e},n);n.endpointV2=i,n.authSchemes=i.properties?.authSchemes;let a=n.authSchemes?.[0];if(a){n.signing_region=a.signingRegion,n.signing_service=a.signingName;let u=jy(n)?.selectedHttpAuthScheme?.httpAuthOption;u&&(u.signingProperties=Object.assign(u.signingProperties||{},{signing_region:a.signingRegion,signingRegion:a.signingRegion,signing_service:a.signingName,signingName:a.signingName,signingRegionSet:a.signingRegionSet},a.properties))}return r({...o})}});var CGe,fpe=C(()=>{CGe=(e,t)=>r=>async n=>{let{response:o}=await r(n);try{let i=await t(o,e);return{response:o,output:i}}catch(i){if(Object.defineProperty(i,"$response",{value:o}),!("$metadata"in i)){let a="Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";i.message+=`
`+a,typeof i.$responseBodyText<"u"&&i.$response&&(i.$response.body=i.$responseBodyText)}throw i}}});var OGe,ppe=C(()=>{OGe=(e,t)=>(r,n)=>async o=>{let i=n.endpointV2?.url&&e.urlParser?async()=>e.urlParser(n.endpointV2.url):e.endpoint;if(!i)throw new Error("No valid endpoint provider available.");let a=await t(o.input,{...e,endpoint:i});return r({...o,request:a})}});function dt(e,t,r){return{applyToStack:n=>{n.add(CGe(e,r),tQt),n.add(OGe(e,t),WU)}}}var tQt,WU,EGe=C(()=>{fpe();ppe();tQt={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},WU={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});var xn=C(()=>{fpe();EGe();ppe()});var hpe,ft,PGe=C(()=>{xn();dpe();hpe={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:WU.name},ft=(e,t)=>({applyToStack:r=>{r.addRelativeTo(xGe({config:e,instructions:t}),hpe)}})});var pJ,TGe=C(()=>{eg();fJ();pJ=e=>{let t=e.tls??!0,{endpoint:r}=e,n=r!=null?async()=>dJ(await zc(r)()):void 0;return{...e,endpoint:n,tls:t,isCustomEndpoint:!!r,useDualstackEndpoint:zc(e.useDualstackEndpoint??!1),useFipsEndpoint:zc(e.useFipsEndpoint??!1)}}});var MGe=C(()=>{});var gn=C(()=>{SGe();dpe();PGe();TGe();MGe()});var rQt,hJ,IGe=C(()=>{gn();lJ();rQt={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:hpe.name},hJ=(e,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:r})=>({applyToStack:n=>{n.addRelativeTo(lpe(e,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:r}),rQt)}})});var Oqn,AGe=C(()=>{xn();lJ();Oqn={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:WU.name}});var RGe=C(()=>{lJ();IGe();AGe()});var DGe=C(()=>{});var jGe=C(()=>{DGe()});var NGe=C(()=>{us()});var LGe=C(()=>{});var FGe=C(()=>{});function nQt(e){return Object.keys(e).reduce((t,r)=>{let n=e[r];return{...t,[r]:Array.isArray(n)?[...n]:n}},{})}var $I,kGe=C(()=>{$I=class e{constructor(t){this.method=t.method||"GET",this.hostname=t.hostname||"localhost",this.port=t.port,this.query=t.query||{},this.headers=t.headers||{},this.body=t.body,this.protocol=t.protocol?t.protocol.slice(-1)!==":"?`${t.protocol}:`:t.protocol:"https:",this.path=t.path?t.path.charAt(0)!=="/"?`/${t.path}`:t.path:"/",this.username=t.username,this.password=t.password,this.fragment=t.fragment}static clone(t){let r=new e({...t,headers:{...t.headers}});return r.query&&(r.query=nQt(r.query)),r}static isInstance(t){if(!t)return!1;let r=t;return"method"in r&&"protocol"in r&&"hostname"in r&&"path"in r&&typeof r.query=="object"&&typeof r.headers=="object"}clone(){return e.clone(this)}}});var BGe=C(()=>{});var $Ge=C(()=>{});var qGe=C(()=>{});var JU=C(()=>{jGe();NGe();LGe();FGe();kGe();BGe();$Ge();qGe()});var oQt,iQt,UGe,mpe=C(()=>{JU();us();eg();oQt=e=>t=>{throw t},iQt=(e,t)=>{},UGe=e=>(t,r)=>async n=>{if(!$I.isInstance(n.request))return t(n);let i=jy(r).selectedHttpAuthScheme;if(!i)throw new Error("No HttpAuthScheme was selected: unable to sign request");let{httpAuthOption:{signingProperties:a={}},identity:s,signer:u}=i,l=await t({...n,request:await u.sign(n.request,s,a)}).catch((u.errorHandler||oQt)(a));return(u.successHandler||iQt)(l.response,a),l}});var tg,Ny,GU,mJ=C(()=>{(function(e){e.STANDARD="standard",e.ADAPTIVE="adaptive"})(tg||(tg={}));Ny=3,GU=tg.STANDARD});var zGe,HGe,VGe,WGe,JGe=C(()=>{zGe=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],HGe=["TimeoutError","RequestTimeout","RequestTimeoutException"],VGe=[500,502,503,504],WGe=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"]});var aQt,tN,gJ,GGe,KU=C(()=>{JGe();aQt=e=>e.$metadata?.clockSkewCorrected,tN=e=>e.$metadata?.httpStatusCo
If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body`);return o.stream()};return Object.assign(e,{transformToByteArray:r,transformToString:async o=>{let i=await r();if(o==="base64")return yE(i);if(o==="hex")return i7e(i);if(o===void 0||o==="utf8"||o==="utf-8")return OJ(i);if(typeof TextDecoder=="function")return new TextDecoder(o).decode(i);throw new Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(t)throw new Error(s7e);if(t=!0,u7e(e))return n(e);if(Fpe(e))return e;throw new Error(`Cannot transform payload to web stream, got ${e}`)}})},u7e=e=>typeof Blob=="function"&&e instanceof Blob});var d7e=C(()=>{});var f7e=C(()=>{});var Bpe=C(()=>{jpe();$Ke();c7e();d7e();f7e();kpe()});var _E,p7e=C(()=>{Bpe();_E=async(e=new Uint8Array,t)=>{if(e instanceof Uint8Array)return ox.mutate(e);if(!e)return ox.mutate(new Uint8Array);let r=t.streamCollector(e);return ox.mutate(await r)}});var ot,$pe,h7e=C(()=>{Ppe();us();ot=class{constructor(){this.middlewareStack=iN()}static classBuilder(){return new $pe}resolveMiddlewareWithContext(t,r,n,{middlewareFn:o,clientName:i,commandName:a,inputFilterSensitiveLog:s,outputFilterSensitiveLog:u,smithyContext:l,additionalContext:c,CommandCtor:d}){for(let _ of o.bind(this)(d,t,r,n))this.middlewareStack.use(_);let f=t.concat(this.middlewareStack),{logger:p}=r,h={logger:p,clientName:i,commandName:a,inputFilterSensitiveLog:s,outputFilterSensitiveLog:u,[Qj]:{commandInstance:this,...l},...c},{requestHandler:m}=r;return f.resolve(_=>m.handle(_.request,n||{}),h)}},$pe=class{constructor(){this._init=()=>{},this._ep={},this._middlewareFn=()=>[],this._commandName="",this._clientName="",this._additionalContext={},this._smithyContext={},this._inputFilterSensitiveLog=t=>t,this._outputFilterSensitiveLog=t=>t,this._serializer=null,this._deserializer=null}init(t){this._init=t}ep(t){return this._ep=t,this}m(t){return this._middlewareFn=t,this}s(t,r,n={}){return this._smithyContext={service:t,operation:r,...n},this}c(t={}){return this._additionalContext=t,this}n(t,r){return this._clientName=t,this._commandName=r,this}f(t=n=>n,r=n=>n){return this._inputFilterSensitiveLog=t,this._outputFilterSensitiveLog=r,this}ser(t){return this._serializer=t,this}de(t){return this._deserializer=t,this}build(){let t=this,r;return r=class extends ot{static getEndpointParameterInstructions(){return t._ep}constructor(...[n]){super(),this.serialize=t._serializer,this.deserialize=t._deserializer,this.input=n??{},t._init(this)}resolveMiddleware(n,o,i){return this.resolveMiddlewareWithContext(n,o,i,{CommandCtor:r,middlewareFn:t._middlewareFn,clientName:t._clientName,commandName:t._commandName,inputFilterSensitiveLog:t._inputFilterSensitiveLog,outputFilterSensitiveLog:t._outputFilterSensitiveLog,smithyContext:t._smithyContext,additionalContext:t._additionalContext})}}}}});var PJ,m7e=C(()=>{PJ="***SensitiveInformation***"});var TJ,g7e=C(()=>{TJ=(e,t)=>{for(let r of Object.keys(e)){let n=e[r],o=async function(a,s,u){let l=new n(a);if(typeof s=="function")this.send(l,s);else if(typeof u=="function"){if(typeof s!="object")throw new Error(`Expected http options but got ${typeof s}`);this.send(l,s||{},u)}else return this.send(l,s)},i=(r[0].toLowerCase()+r.slice(1)).replace(/Command$/,"");t.prototype[i]=o}}});var WI,gQt,y7e,yQt,b7e,_7e,v7e,qpe,bQt,uN,jr,w7e,S7e,_Qt,ez,tz,Upe,x7e,C7e,O7e,zpe=C(()=>{WI=e=>{if(e!=null){if(typeof e=="string"){let t=parseFloat(e);if(!Number.isNaN(t))return String(t)!==String(e)&&O7e.warn(C7e(`Expected number but observed string: ${e}`)),t}if(typeof e=="number")return e;throw new TypeError(`Expected number, got ${typeof e}: ${e}`)}},gQt=Math.ceil(34028234663852886e22),y7e=e=>{let t=WI(e);if(t!==void 0&&!Number.isNaN(t)&&t!==1/0&&t!==-1/0&&Math.abs(t)>gQt)throw new TypeError(`Expected 32-bit float, got ${e}`);return t},yQt=e=>{if(e!=null){if(Number.isInteger(e)&&!Number.isNaN(e))return e;throw new TypeError(`Expected integer, got ${typeof e}: ${e}`)}},b7e=e=>qpe(e,32),_7e=e=>qpe(e,16),v
`).slice(0,5).filter(t=>!t.includes("stackTraceWarning")).join(`
`),O7e={warn:console.warn}});var vQt,wQt,E7e,SQt,P7e,T4n,M4n,I4n,MJ,T7e,A4n,xQt,CQt,OQt,JI,EQt,PQt,Hpe,M7e=C(()=>{zpe();vQt=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wQt=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),E7e=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let t=wQt.exec(e);if(!t)throw new TypeError("Invalid RFC-3339 date-time value");let[r,n,o,i,a,s,u,l]=t,c=Upe(Hpe(n)),d=JI(o,"month",1,12),f=JI(i,"day",1,31);return T7e(c,d,f,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l})},SQt=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),P7e=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let t=SQt.exec(e);if(!t)throw new TypeError("Invalid RFC-3339 date-time value");let[r,n,o,i,a,s,u,l,c]=t,d=Upe(Hpe(n)),f=JI(o,"month",1,12),p=JI(i,"day",1,31),h=T7e(d,f,p,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l});return c.toUpperCase()!="Z"&&h.setTime(h.getTime()-PQt(c)),h},T4n=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),M4n=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),I4n=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/),MJ=e=>{if(e==null)return;let t;if(typeof e=="number")t=e;else if(typeof e=="string")t=w7e(e);else if(typeof e=="object"&&e.tag===1)t=e.value;else throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(t)||t===1/0||t===-1/0)throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(t*1e3))},T7e=(e,t,r,n)=>{let o=t-1;return CQt(e,o,r),new Date(Date.UTC(e,o,r,JI(n.hours,"hour",0,23),JI(n.minutes,"minute",0,59),JI(n.seconds,"seconds",0,60),EQt(n.fractionalMilliseconds)))},A4n=50*365*24*60*60*1e3,xQt=[31,28,31,30,31,30,31,31,30,31,30,31],CQt=(e,t,r)=>{let n=xQt[t];if(t===1&&OQt(e)&&(n=29),r>n)throw new TypeError(`Invalid day for ${vQt[t]} in ${e}: ${r}`)},OQt=e=>e%4===0&&(e%100!==0||e%400===0),JI=(e,t,r,n)=>{let o=x7e(Hpe(e));if(o<r||o>n)throw new TypeError(`${t} must be between ${r} and ${n}, inclusive`);return o},EQt=e=>e==null?0:S7e("0."+e)*1e3,PQt=e=>{let t=e[0],r=1;if(t=="+")r=1;else if(t=="-")r=-1;else throw new TypeError(`Offset direction, ${t}, must be "+" or "-"`);let n=Number(e.substring(1,3)),o=Number(e.substring(4,6));return r*(n*60+o)*60*1e3},Hpe=e=>{let t=0;for(;t<e.length-1&&e.charAt(t)==="0";)t++;return t===0?e:e.slice(t)}});var lN,ia,Vpe=C(()=>{lN=class e extends Error{constructor(t){super(t.message),Object.setPrototypeOf(this,e.prototype),this.name=t.name,this.$fault=t.$fault,this.$metadata=t.$metadata}},ia=(e,t={})=>{Object.entries(t).filter(([,n])=>n!==void 0).forEach(([n,o])=>{(e[n]==null||e[n]==="")&&(e[n]=o)});let r=e.message||e.Message||"UnknownError";return e.message=r,delete e.Message,e}});var TQt,IJ,MQt,I7e=C(()=>{Vpe();TQt=({output:e,parsedBody:t,exceptionCtor:r,errorCode:n})=>{let o=MQt(e),i=o.httpStatusCode?o.httpStatusCode+"":void 0,a=new r({name:t?.code||t?.Code||n||i||"UnknownError",$fault:"client",$metadata:o});throw ia(a,t)},IJ=e=>({output:t,parsedBody:r,errorCode:n})=>{TQt({output:t,parsedBody:r,exceptionCtor:e,errorCode:n})},MQt=e=>({httpStatusCode:e.statusCode,requestId:e.headers["x-amzn-requestid"]??e.headers["x-amzn-request-id"]??e.headers["x-amz-request-id"],extendedRequestId:e.headers["x-amz-id-2"],cfId:e.headers["x-amz-cf-id"]})});var AJ,A7e=C(()=>{AJ=e=>{switch(e){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":retu
`);return this.signString(h,{signingDate:n,signingRegion:s,signingService:a})}async signMessage(t,{signingDate:r=new Date,signingRegion:n,signingService:o}){return this.signEvent({headers:this.headerFormatter.format(t.message.headers),payload:t.message.body},{signingDate:r,signingRegion:n,signingService:o,priorSignature:t.priorSignature}).then(a=>({message:t.message,signature:a}))}async signString(t,{signingDate:r=new Date,signingRegion:n,signingService:o}={}){let i=await this.credentialProvider();this.validateResolvedCredentials(i);let a=n??await this.regionProvider(),{shortDate:s}=GJ(r),u=new this.sha256(await this.getSigningKey(i,a,s,o));return u.update(SE(t)),rg(await u.digest())}async signRequest(t,{signingDate:r=new Date,signableHeaders:n,unsignableHeaders:o,signingRegion:i,signingService:a}={}){let s=await this.credentialProvider();this.validateResolvedCredentials(s);let u=i??await this.regionProvider(),l=JJ(t),{longDate:c,shortDate:d}=GJ(r),f=HJ(d,u,a??this.service);l.headers[uhe]=c,s.sessionToken&&(l.headers[QYe]=s.sessionToken);let p=await lz(l,this.sha256);!hZe(uz,l.headers)&&this.applyChecksum&&(l.headers[uz]=p);let h=VJ(l,o,n),m=await this.getSignature(c,f,this.getSigningKey(s,u,d,a),this.createCanonicalRequest(l,h,p));return l.headers[she]=`${UJ} Credential=${s.accessKeyId}/${f}, SignedHeaders=${bZe(h)}, Signature=${m}`,l}createCanonicalRequest(t,r,n){let o=Object.keys(r).sort();return`${t.method}
${this.getCanonicalPath(t)}
${phe(t)}
${o.map(i=>`${i}:${r[i]}`).join(`
`)}
${o.join(";")}
${n}`}async createStringToSign(t,r,n){let o=new this.sha256;o.update(SE(n));let i=await o.digest();return`${UJ}
${t}
${r}
${rg(i)}`}getCanonicalPath({path:t}){if(this.uriEscapePath){let r=[];for(let i of t.split("/"))i?.length!==0&&i!=="."&&(i===".."?r.pop():r.push(i));let n=`${t?.startsWith("/")?"/":""}${r.join("/")}${r.length>0&&t?.endsWith("/")?"/":""}`;return xh(n).replace(/%2F/g,"/")}return t}async getSignature(t,r,n,o){let i=await this.createStringToSign(t,r,o),a=new this.sha256(await n);return a.update(SE(i)),rg(await a.digest())}getSigningKey(t,r,n,o){return uZe(this.sha256,t,n,r,o||this.service)}validateResolvedCredentials(t){if(typeof t!="object"||typeof t.accessKeyId!="string"||typeof t.secretAccessKey!="string")throw new Error("Resolved credential object is not valid")}},GJ=e=>{let t=gZe(e).replace(/[\-:]/g,"");return{longDate:t,shortDate:t.slice(0,8)}},bZe=e=>Object.keys(e).sort().join(";")});var vZe=C(()=>{_Ze();fhe();hhe();mhe();bhe();_he();dhe()});var KJ,wZe=C(()=>{vE();vZe();KJ=e=>{let t;e.credentials&&(t=aYe(e.credentials,iYe,Ype)),t||(e.credentialDefaultProvider?t=fN(e.credentialDefaultProvider(Object.assign({},e,{parentClientConfig:e}))):t=async()=>{throw new Error("`credentials` is missing")});let{signingEscapePath:r=!0,systemClockOffset:n=e.systemClockOffset||0,sha256:o}=e,i;return e.signer?i=fN(e.signer):e.regionInfoProvider?i=()=>fN(e.region)().then(async a=>[await e.regionInfoProvider(a,{useFipsEndpoint:await e.useFipsEndpoint(),useDualstackEndpoint:await e.useDualstackEndpoint()})||{},a]).then(([a,s])=>{let{signingRegion:u,signingService:l}=a;e.signingRegion=e.signingRegion||u||s,e.signingName=e.signingName||l||e.serviceId;let c={...e,credentials:t,region:e.signingRegion,service:e.signingName,sha256:o,uriEscapePath:r},d=e.signerConstructor||cz;return new d(c)}):i=async a=>{a=Object.assign({},{name:"sigv4",signingName:e.signingName||e.defaultSigningName,signingRegion:await fN(e.region)(),properties:{}},a);let s=a.signingRegion,u=a.signingName;e.signingRegion=e.signingRegion||s,e.signingName=e.signingName||u||e.serviceId;let l={...e,credentials:t,region:e.signingRegion,service:e.signingName,sha256:o,uriEscapePath:r},c=e.signerConstructor||cz;return new c(l)},{...e,systemClockOffset:n,signingEscapePath:r,credentials:t,signer:i}}});var SZe=C(()=>{qYe();UYe();wZe()});var xZe=C(()=>{SZe()});var CZe=C(()=>{});var OZe=C(()=>{Rt()});var YJ,vhe=C(()=>{Rt();YJ=(e,t)=>_E(e,t).then(r=>t.utf8Encoder(r))});var Ja,EZe,PZe,TZe=C(()=>{vhe();Ja=(e,t)=>YJ(e,t).then(r=>{if(r.length)try{return JSON.parse(r)}catch(n){throw n?.name==="SyntaxError"&&Object.defineProperty(n,"$responseBodyText",{value:r}),n}return{}}),EZe=async(e,t)=>{let r=await Ja(e,t);return r.message=r.message??r.Message,r},PZe=(e,t)=>{let r=(i,a)=>Object.keys(i).find(s=>s.toLowerCase()===a.toLowerCase()),n=i=>{let a=i;return typeof a=="number"&&(a=a.toString()),a.indexOf(",")>=0&&(a=a.split(",")[0]),a.indexOf(":")>=0&&(a=a.split(":")[0]),a.indexOf("#")>=0&&(a=a.split("#")[1]),a},o=r(e.headers,"x-amzn-errortype");if(o!==void 0)return n(e.headers[o]);if(t.code!==void 0)return n(t.code);if(t.__type!==void 0)return n(t.__type)}});var ZJ=b(ix=>{"use strict";var MZe=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",KQt=MZe+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",IZe="["+MZe+"]["+KQt+"]*",YQt=new RegExp("^"+IZe+"$"),ZQt=function(e,t){let r=[],n=t.exec(e);for(;n;){let o=[];o.startIndex=t.lastIndex-n[0].length;let i=n.length;for(let a=0;a<i;a++)o.push(n[a]);r.push(o),n=t.exec(e)}return r},XQt=function(e){let t=YQt.exec(e);return!(t===null||typeof t>"u")};ix.isExist=function(e){return typeof e<"u"};ix.isEmptyObject=function(e){return Object.keys(e).length===0};ix.merge=function(e,t,r){if(t){let n=Object.keys(t),o=n.length;for(let i=0;i<o;i++)r==="strict"?e[n[i]]=[t[n[i]]]:e[n[i]]=t[n[i]]}};ix.getValue=function(e){return ix.isExist(e)?e:""};ix.isName=XQt;ix.getAllMatches=ZQt;ix.nameRegexp=IZe});var She=b(NZe=>{"use strict";var whe=ZJ(),QQt={allowBooleanAttributes:!1,unpairedTags:[]};NZe.validate=function(e,t){t=Object.assign({},QQt,t);let r=[],n=!1,
`&&e[i]!=="\r";i++)u+=e[i];if(u=u.trim(),u[u.length-1]==="/"&&(u=u.substring(0,u.length-1),i--),!ser(u)){let d;return u.trim().length===0?d="Invalid space after '<'.":d="Tag '"+u+"' is an invalid name.",Ga("InvalidTag",d,Rd(e,i))}let l=rer(e,i);if(l===!1)return Ga("InvalidAttr","Attributes for '"+u+"' have open quote.",Rd(e,i));let c=l.value;if(i=l.index,c[c.length-1]==="/"){let d=i-c.length;c=c.substring(0,c.length-1);let f=jZe(c,t);if(f===!0)n=!0;else return Ga(f.err.code,f.err.msg,Rd(e,d+f.err.line))}else if(s)if(l.tagClosed){if(c.trim().length>0)return Ga("InvalidTag","Closing tag '"+u+"' can't have attributes or invalid starting.",Rd(e,a));if(r.length===0)return Ga("InvalidTag","Closing tag '"+u+"' has not been opened.",Rd(e,a));{let d=r.pop();if(u!==d.tagName){let f=Rd(e,d.tagStartPos);return Ga("InvalidTag","Expected closing tag '"+d.tagName+"' (opened in line "+f.line+", col "+f.col+") instead of closing tag '"+u+"'.",Rd(e,a))}r.length==0&&(o=!0)}}else return Ga("InvalidTag","Closing tag '"+u+"' doesn't have proper closing.",Rd(e,i));else{let d=jZe(c,t);if(d!==!0)return Ga(d.err.code,d.err.msg,Rd(e,i-c.length+d.err.line));if(o===!0)return Ga("InvalidXml","Multiple possible root nodes found.",Rd(e,i));t.unpairedTags.indexOf(u)!==-1||r.push({tagName:u,tagStartPos:a}),n=!0}for(i++;i<e.length;i++)if(e[i]==="<")if(e[i+1]==="!"){i++,i=DZe(e,i);continue}else if(e[i+1]==="?"){if(i=RZe(e,++i),i.err)return i}else break;else if(e[i]==="&"){let d=ier(e,i);if(d==-1)return Ga("InvalidChar","char '&' is not expected.",Rd(e,i));i=d}else if(o===!0&&!AZe(e[i]))return Ga("InvalidXml","Extra text at the end",Rd(e,i));e[i]==="<"&&i--}}else{if(AZe(e[i]))continue;return Ga("InvalidChar","char '"+e[i]+"' is not expected.",Rd(e,i))}if(n){if(r.length==1)return Ga("InvalidTag","Unclosed tag '"+r[0].tagName+"'.",Rd(e,r[0].tagStartPos));if(r.length>0)return Ga("InvalidXml","Invalid '"+JSON.stringify(r.map(i=>i.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return Ga("InvalidXml","Start tag expected.",1);return!0};function AZe(e){return e===" "||e===" "||e===`
`||e==="\r"}function RZe(e,t){let r=t;for(;t<e.length;t++)if(e[t]=="?"||e[t]==" "){let n=e.substr(r,t-r);if(t>5&&n==="xml")return Ga("InvalidXml","XML declaration allowed only at the start of the document.",Rd(e,t));if(e[t]=="?"&&e[t+1]==">"){t++;break}else continue}return t}function DZe(e,t){if(e.length>t+5&&e[t+1]==="-"&&e[t+2]==="-"){for(t+=3;t<e.length;t++)if(e[t]==="-"&&e[t+1]==="-"&&e[t+2]===">"){t+=2;break}}else if(e.length>t+8&&e[t+1]==="D"&&e[t+2]==="O"&&e[t+3]==="C"&&e[t+4]==="T"&&e[t+5]==="Y"&&e[t+6]==="P"&&e[t+7]==="E"){let r=1;for(t+=8;t<e.length;t++)if(e[t]==="<")r++;else if(e[t]===">"&&(r--,r===0))break}else if(e.length>t+9&&e[t+1]==="["&&e[t+2]==="C"&&e[t+3]==="D"&&e[t+4]==="A"&&e[t+5]==="T"&&e[t+6]==="A"&&e[t+7]==="["){for(t+=8;t<e.length;t++)if(e[t]==="]"&&e[t+1]==="]"&&e[t+2]===">"){t+=2;break}}return t}var eer='"',ter="'";function rer(e,t){let r="",n="",o=!1;for(;t<e.length;t++){if(e[t]===eer||e[t]===ter)n===""?n=e[t]:n!==e[t]||(n="");else if(e[t]===">"&&n===""){o=!0;break}r+=e[t]}return n!==""?!1:{value:r,index:t,tagClosed:o}}var ner=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function jZe(e,t){let r=whe.getAllMatches(e,ner),n={};for(let o=0;o<r.length;o++){if(r[o][1].length===0)return Ga("InvalidAttr","Attribute '"+r[o][2]+"' has no space in starting.",dz(r[o]));if(r[o][3]!==void 0&&r[o][4]===void 0)return Ga("InvalidAttr","Attribute '"+r[o][2]+"' is without value.",dz(r[o]));if(r[o][3]===void 0&&!t.allowBooleanAttributes)return Ga("InvalidAttr","boolean attribute '"+r[o][2]+"' is not allowed.",dz(r[o]));let i=r[o][2];if(!aer(i))return Ga("InvalidAttr","Attribute '"+i+"' is an invalid name.",dz(r[o]));if(!n.hasOwnProperty(i))n[i]=1;else return Ga("InvalidAttr","Attribute '"+i+"' is repeated.",dz(r[o]))}return!0}function oer(e,t){let r=/\d/;for(e[t]==="x"&&(t++,r=/[\da-fA-F]/);t<e.length;t++){if(e[t]===";")return t;if(!e[t].match(r))break}return-1}function ier(e,t){if(t++,e[t]===";")return-1;if(e[t]==="#")return t++,oer(e,t);let r=0;for(;t<e.length;t++,r++)if(!(e[t].match(/\w/)&&r<20)){if(e[t]===";")break;return-1}return t}function Ga(e,t,r){return{err:{code:e,msg:t,line:r.line||r,col:r.col}}}function aer(e){return whe.isName(e)}function ser(e){return whe.isName(e)}function Rd(e,t){let r=e.substring(0,t).split(/\r?\n/);return{line:r.length,col:r[r.length-1].length+1}}function dz(e){return e.startIndex+e[1].length}});var FZe=b(xhe=>{var LZe={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(e,t,r){return e}},uer=function(e){return Object.assign({},LZe,e)};xhe.buildOptions=uer;xhe.defaultOptions=LZe});var BZe=b((tVn,kZe)=>{"use strict";var Che=class{constructor(t){this.tagname=t,this.child=[],this[":@"]={}}add(t,r){t==="__proto__"&&(t="#__proto__"),this.child.push({[t]:r})}addChild(t){t.tagname==="__proto__"&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child})}};kZe.exports=Che});var qZe=b((rVn,$Ze)=>{var ler=ZJ();function cer(e,t){let r={};if(e[t+3]==="O"&&e[t+4]==="C"&&e[t+5]==="T"&&e[t+6]==="Y"&&e[t+7]==="P"&&e[t+8]==="E"){t=t+9;let n=1,o=!1,i=!1,a="";for(;t<e.length;t++)if(e[t]==="<"&&!i){if(o&&per(e,t))t+=7,[entityName,val,t]=der(e,t+1),val.indexOf("&")===-1&&(r[yer(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(o&&her(e,t))t+=8;else if(o&&mer(e,t))t+=8;else if(o&&ger(e,t))t+=9;else if(fer)i=!0;else throw new Error("Invalid DOCTYPE");n++,a=""}else if(e[t]===">"){if(i?e[t-1]==="-"&&e[t-2]==="-"&&(i=!1,n--):n--,n===0)brea
`);let t=new fz("!xml"),r=t,n="",o="";for(let i=0;i<e.length;i++)if(e[i]==="<")if(e[i+1]==="/"){let s=YI(e,">",i,"Closing Tag is not closed."),u=e.substring(i+2,s).trim();if(this.options.removeNSPrefix){let d=u.indexOf(":");d!==-1&&(u=u.substr(d+1))}this.options.transformTagName&&(u=this.options.transformTagName(u)),r&&(n=this.saveTextToParentTag(n,r,o));let l=o.substring(o.lastIndexOf(".")+1);if(u&&this.options.unpairedTags.indexOf(u)!==-1)throw new Error(`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(e[i+1]==="?"){let s=Ehe(e,i,!1,"?>");if(!s)throw new Error("Pi Tag is not closed.");if(n=this.saveTextToParentTag(n,r,o),!(this.options.ignoreDeclaration&&s.tagName==="?xml"||this.options.ignorePiTags)){let u=new fz(s.tagName);u.add(this.options.textNodeName,""),s.tagName!==s.tagExp&&s.attrExpPresent&&(u[":@"]=this.buildAttributesMap(s.tagExp,o,s.tagName)),this.addChild(r,u,o)}i=s.closeIndex+1}else if(e.substr(i+1,3)==="!--"){let s=YI(e,"-->",i+4,"Comment is not closed.");if(this.options.commentPropName){let u=e.substring(i+4,s-2);n=this.saveTextToParentTag(n,r,o),r.add(this.options.commentPropName,[{[this.options.textNodeName]:u}])}i=s}else if(e.substr(i+1,2)==="!D"){let s=xer(e,i);this.docTypeEntities=s.entities,i=s.i}else if(e.substr(i+1,2)==="!["){let s=YI(e,"]]>",i,"CDATA is not closed.")-2,u=e.substring(i+9,s);n=this.saveTextToParentTag(n,r,o);let l=this.parseTextData(u,r.tagname,o,!0,!1,!0,!0);l==null&&(l=""),this.options.cdataPropName?r.add(this.options.cdataPropName,[{[this.options.textNodeName]:u}]):r.add(this.options.textNodeName,l),i=s+2}else{let s=Ehe(e,i,this.options.removeNSPrefix),u=s.tagName,l=s.rawTagName,c=s.tagExp,d=s.attrExpPresent,f=s.closeIndex;this.options.transformTagName&&(u=this.options.transformTagName(u)),r&&n&&r.tagname!=="!xml"&&(n=this.saveTextToParentTag(n,r,o,!1));let p=r;if(p&&this.options.unpairedTags.indexOf(p.tagname)!==-1&&(r=this.tagsNodeStack.pop(),o=o.substring(0,o.lastIndexOf("."))),u!==t.tagname&&(o+=o?"."+u:u),this.isItStopNode(this.options.stopNodes,o,u)){let h="";if(c.length>0&&c.lastIndexOf("/")===c.length-1)u[u.length-1]==="/"?(u=u.substr(0,u.length-1),o=o.substr(0,o.length-1),c=u):c=c.substr(0,c.length-1),i=s.closeIndex;else if(this.options.unpairedTags.indexOf(u)!==-1)i=s.closeIndex;else{let _=this.readStopNodeData(e,l,f+1);if(!_)throw new Error(`Unexpected end of ${l}`);i=_.i,h=_.tagContent}let m=new fz(u);u!==c&&d&&(m[":@"]=this.buildAttributesMap(c,o,u)),h&&(h=this.parseTextData(h,u,o,!0,d,!0,!0)),o=o.substr(0,o.lastIndexOf(".")),m.add(this.options.textNodeName,h),this.addChild(r,m,o)}else{if(c.length>0&&c.lastIndexOf("/")===c.length-1){u[u.length-1]==="/"?(u=u.substr(0,u.length-1),o=o.substr(0,o.length-1),c=u):c=c.substr(0,c.length-1),this.options.transformTagName&&(u=this.options.transformTagName(u));let h=new fz(u);u!==c&&d&&(h[":@"]=this.buildAttributesMap(c,o,u)),this.addChild(r,h,o),o=o.substr(0,o.lastIndexOf("."))}else{let h=new fz(u);this.tagsNodeStack.push(r),u!==c&&d&&(h[":@"]=this.buildAttributesMap(c,o,u)),this.addChild(r,h,o),r=h}n="",i=f}}else n+=e[i];return t.child};function Aer(e,t,r){let n=this.options.updateTag(t.tagname,r,t[":@"]);n===!1||(typeof n=="string"&&(t.tagname=n),e.addChild(t))}var Rer=function(e){if(this.options.processEntities){for(let t in this.docTypeEntities){let r=this.docTypeEntities[t];e=e.replace(r.regx,r.val)}for(let t in this.lastEntities){let r=this.lastEntities[t];e=e.replace(r.regex,r.val)}if(this.options.htmlEntities)for(let t in this.htmlEntities){let r=this.htmlEntities[t];e=e.replace(r.regex,r.val)}e=e.replace(this.ampEntity.regex,this.ampEntity.val)}return e};function Der(e,t,r,n){return e&&(n===void 0&&(n=Object.keys(t.child).length===0),e=this.parseTextData(e,t.tagname,r,!1,t[":@"]?Object.keys(t[":@"]).length!==0:!1,n),e!==void 0&&e!==""&&t.add(this.options.textNodeName,e),e=""),e}function jer(e,t,r){let n="*
`;function Wer(e,t){let r="";return t.format&&t.indentBy.length>0&&(r=Ver),QZe(e,t,"",r)}function QZe(e,t,r,n){let o="",i=!1;for(let a=0;a<e.length;a++){let s=e[a],u=Jer(s);if(u===void 0)continue;let l="";if(r.length===0?l=u:l=`${r}.${u}`,u===t.textNodeName){let h=s[u];Ger(l,t)||(h=t.tagValueProcessor(u,h),h=eXe(h,t)),i&&(o+=n),o+=h,i=!1;continue}else if(u===t.cdataPropName){i&&(o+=n),o+=`<![CDATA[${s[u][0][t.textNodeName]}]]>`,i=!1;continue}else if(u===t.commentPropName){o+=n+`<!--${s[u][0][t.textNodeName]}-->`,i=!0;continue}else if(u[0]==="?"){let h=XZe(s[":@"],t),m=u==="?xml"?"":n,_=s[u][0][t.textNodeName];_=_.length!==0?" "+_:"",o+=m+`<${u}${_}${h}?>`,i=!0;continue}let c=n;c!==""&&(c+=t.indentBy);let d=XZe(s[":@"],t),f=n+`<${u}${d}`,p=QZe(s[u],t,l,c);t.unpairedTags.indexOf(u)!==-1?t.suppressUnpairedNode?o+=f+">":o+=f+"/>":(!p||p.length===0)&&t.suppressEmptyNode?o+=f+"/>":p&&p.endsWith(">")?o+=f+`>${p}${n}</${u}>`:(o+=f+">",p&&n!==""&&(p.includes("/>")||p.includes("</"))?o+=n+t.indentBy+p+n:o+=p,o+=`</${u}>`),i=!0}return o}function Jer(e){let t=Object.keys(e);for(let r=0;r<t.length;r++){let n=t[r];if(e.hasOwnProperty(n)&&n!==":@")return n}}function XZe(e,t){let r="";if(e&&!t.ignoreAttributes)for(let n in e){if(!e.hasOwnProperty(n))continue;let o=t.attributeValueProcessor(n,e[n]);o=eXe(o,t),o===!0&&t.suppressBooleanAttributes?r+=` ${n.substr(t.attributeNamePrefix.length)}`:r+=` ${n.substr(t.attributeNamePrefix.length)}="${o}"`}return r}function Ger(e,t){e=e.substr(0,e.length-t.textNodeName.length-1);let r=e.substr(e.lastIndexOf(".")+1);for(let n in t.stopNodes)if(t.stopNodes[n]===e||t.stopNodes[n]==="*."+r)return!0;return!1}function eXe(e,t){if(e&&e.length>0&&t.processEntities)for(let r=0;r<t.entities.length;r++){let n=t.entities[r];e=e.replace(n.regex,n.val)}return e}tXe.exports=Wer});var oXe=b((uVn,nXe)=>{"use strict";var Ker=rXe(),Yer={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function xE(e){this.options=Object.assign({},Yer,e),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=Qer),this.processTextOrObjNode=Zer,this.options.format?(this.indentate=Xer,this.tagEndChar=`>
`,this.newLine=`
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}xE.prototype.build=function(e){return this.options.preserveOrder?Ker(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0).val)};xE.prototype.j2x=function(e,t){let r="",n="";for(let o in e)if(Object.prototype.hasOwnProperty.call(e,o))if(typeof e[o]>"u")this.isAttribute(o)&&(n+="");else if(e[o]===null)this.isAttribute(o)?n+="":o[0]==="?"?n+=this.indentate(t)+"<"+o+"?"+this.tagEndChar:n+=this.indentate(t)+"<"+o+"/"+this.tagEndChar;else if(e[o]instanceof Date)n+=this.buildTextValNode(e[o],o,"",t);else if(typeof e[o]!="object"){let i=this.isAttribute(o);if(i)r+=this.buildAttrPairStr(i,""+e[o]);else if(o===this.options.textNodeName){let a=this.options.tagValueProcessor(o,""+e[o]);n+=this.replaceEntitiesValue(a)}else n+=this.buildTextValNode(e[o],o,"",t)}else if(Array.isArray(e[o])){let i=e[o].length,a="",s="";for(let u=0;u<i;u++){let l=e[o][u];if(!(typeof l>"u"))if(l===null)o[0]==="?"?n+=this.indentate(t)+"<"+o+"?"+this.tagEndChar:n+=this.indentate(t)+"<"+o+"/"+this.tagEndChar;else if(typeof l=="object")if(this.options.oneListGroup){let c=this.j2x(l,t+1);a+=c.val,this.options.attributesGroupName&&l.hasOwnProperty(this.options.attributesGroupName)&&(s+=c.attrStr)}else a+=this.processTextOrObjNode(l,o,t);else if(this.options.oneListGroup){let c=this.options.tagValueProcessor(o,l);c=this.replaceEntitiesValue(c),a+=c}else a+=this.buildTextValNode(l,o,"",t)}this.options.oneListGroup&&(a=this.buildObjectNode(a,o,s,t)),n+=a}else if(this.options.attributesGroupName&&o===this.options.attributesGroupName){let i=Object.keys(e[o]),a=i.length;for(let s=0;s<a;s++)r+=this.buildAttrPairStr(i[s],""+e[o][i[s]])}else n+=this.processTextOrObjNode(e[o],o,t);return{attrStr:r,val:n}};xE.prototype.buildAttrPairStr=function(e,t){return t=this.options.attributeValueProcessor(e,""+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&t==="true"?" "+e:" "+e+'="'+t+'"'};function Zer(e,t,r){let n=this.j2x(e,r+1);return e[this.options.textNodeName]!==void 0&&Object.keys(e).length===1?this.buildTextValNode(e[this.options.textNodeName],t,n.attrStr,r):this.buildObjectNode(n.val,t,n.attrStr,r)}xE.prototype.buildObjectNode=function(e,t,r,n){if(e==="")return t[0]==="?"?this.indentate(n)+"<"+t+r+"?"+this.tagEndChar:this.indentate(n)+"<"+t+r+this.closeTag(t)+this.tagEndChar;{let o="</"+t+this.tagEndChar,i="";return t[0]==="?"&&(i="?",o=""),(r||r==="")&&e.indexOf("<")===-1?this.indentate(n)+"<"+t+r+i+">"+e+o:this.options.commentPropName!==!1&&t===this.options.commentPropName&&i.length===0?this.indentate(n)+`<!--${e}-->`+this.newLine:this.indentate(n)+"<"+t+r+i+this.tagEndChar+e+this.indentate(n)+o}};xE.prototype.closeTag=function(e){let t="";return this.options.unpairedTags.indexOf(e)!==-1?this.options.suppressUnpairedNode||(t="/"):this.options.suppressEmptyNode?t="/":t=`></${e}`,t};xE.prototype.buildTextValNode=function(e,t,r,n){if(this.options.cdataPropName!==!1&&t===this.options.cdataPropName)return this.indentate(n)+`<![CDATA[${e}]]>`+this.newLine;if(this.options.commentPropName!==!1&&t===this.options.commentPropName)return this.indentate(n)+`<!--${e}-->`+this.newLine;if(t[0]==="?")return this.indentate(n)+"<"+t+r+"?"+this.tagEndChar;{let o=this.options.tagValueProcessor(t,e);return o=this.replaceEntitiesValue(o),o===""?this.indentate(n)+"<"+t+r+this.closeTag(t)+this.tagEndChar:this.indentate(n)+"<"+t+r+">"+o+"</"+t+this.tagEndChar}};xE.prototype.replaceEntitiesValue=function(e){if(e&&e.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){let r=this.options.entities[t];e=e.replace(r.regex,r.val)}return e};function Xer(e){return this.options.indentBy.repeat(e)}function Qer(e){return e.startsWith(this.options.attributeNamePrefix)&&e!==this.options.textNodeName?e.substr(this.attrPrefixLen):!1}nXe.exports=xE});var aXe=b((lVn,iXe)=>{"use strict";var etr=She(),ttr=ZZe(),rtr=oXe();iXe.exports={XMLParser:ttr,XMLValidator:etr,XMLBuilder:rtr}});v
`)?"":void 0});n.addEntity("#xD","\r"),n.addEntity("#10",`
`);let o;try{o=n.parse(r,!0)}catch(u){throw u&&typeof u=="object"&&Object.defineProperty(u,"$responseBodyText",{value:r}),u}let i="#text",a=Object.keys(o)[0],s=o[a];return s[i]&&(s[a]=s[i],delete s[i]),Jpe(s)}return{}}),uXe=async(e,t)=>{let r=await Fy(e,t);return r.Error&&(r.Error.message=r.Error.message??r.Error.Message),r}});var cXe=C(()=>{CZe();OZe();TZe();lXe()});var ZI=C(()=>{OYe();xZe();cXe()});function ntr(e){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"cognito-identity",region:e.region},propertiesExtractor:(t,r)=>({signingProperties:{config:t,context:r}})}}function XJ(e){return{schemeId:"smithy.api#noAuth"}}var dXe,fXe,pXe,Mhe=C(()=>{ZI();eg();dXe=async(e,t,r)=>({operation:jy(t).operation,region:await zc(e.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});fXe=e=>{let t=[];switch(e.operation){case"GetCredentialsForIdentity":{t.push(XJ(e));break}case"GetId":{t.push(XJ(e));break}case"GetOpenIdToken":{t.push(XJ(e));break}case"UnlinkIdentity":{t.push(XJ(e));break}default:t.push(ntr(e))}return t},pXe=e=>({...KJ(e)})});var hXe,Kt,Si=C(()=>{hXe=e=>({...e,useDualstackEndpoint:e.useDualstackEndpoint??!1,useFipsEndpoint:e.useFipsEndpoint??!1,defaultSigningName:"cognito-identity"}),Kt={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}});var gXe,mXe=C(()=>{gXe={name:"@aws-sdk/client-cognito-identity",description:"AWS SDK for JavaScript Cognito Identity Client for Node.js, Browser and React Native",version:"3.645.0",scripts:{build:"concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'","build:cjs":"node ../../scripts/compilation/inline client-cognito-identity","build:es":"tsc -p tsconfig.es.json","build:include:deps":"lerna run --scope $npm_package_name --include-dependencies build","build:types":"tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4",clean:"rimraf ./dist-* && rimraf *.tsbuildinfo","extract:docs":"api-extractor run --local","generate:client":"node ../../scripts/generate-clients/single-service --solo cognito-identity","test:e2e":"ts-mocha test/**/*.ispec.ts && karma start karma.conf.js"},main:"./dist-cjs/index.js",types:"./dist-types/index.d.ts",module:"./dist-es/index.js",sideEffects:!1,dependencies:{"@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/client-sso-oidc":"3.645.0","@aws-sdk/client-sts":"3.645.0","@aws-sdk/core":"3.635.0","@aws-sdk/credential-provider-node":"3.645.0","@aws-sdk/middleware-host-header":"3.620.0","@aws-sdk/middleware-logger":"3.609.0","@aws-sdk/middleware-recursion-detection":"3.620.0","@aws-sdk/middleware-user-agent":"3.645.0","@aws-sdk/region-config-resolver":"3.614.0","@aws-sdk/types":"3.609.0","@aws-sdk/util-endpoints":"3.645.0","@aws-sdk/util-user-agent-browser":"3.609.0","@aws-sdk/util-user-agent-node":"3.614.0","@smithy/config-resolver":"^3.0.5","@smithy/core":"^2.4.0","@smithy/fetch-http-handler":"^3.2.4","@smithy/hash-node":"^3.0.3","@smithy/invalid-dependency":"^3.0.3","@smithy/middleware-content-length":"^3.0.5","@smithy/middleware-endpoint":"^3.1.0","@smithy/middleware-retry":"^3.0.15","@smithy/middleware-serde":"^3.0.3","@smithy/middleware-stack":"^3.0.3","@smithy/node-config-provider":"^3.1.4","@smithy/node-http-handler":"^3.1.4","@smithy/protocol-http":"^4.1.0","@smithy/smithy-client":"^3.2.0","@smithy/types":"^3.3.0","@smithy/url-parser":"^3.0.3","@smithy/util-base64":"^3.0.0","@smithy/util-body-length-browser":"^3.0.0","@smithy/util-body-length-node":"^3.0.0","@smithy/util-defaults-mode-browser":"^3.0.15","@smithy/util-defaults-mode-node":"^3.0.15","@smithy/util-endpoints":"^2.0.5","@smithy/util-middleware":"^3.0.3","@smithy/util-retry":"^3.0.3","@smithy/util-utf8":"^3.0.0",tslib:"^2.6.2"},devDependencies:{"@aws-sdk/client-iam":"3.645.0","@tsconfig/node16":"16.1.3","@types/chai":"^4.2.11","@types/mocha":"^8.0.4","@types/node":"^16.18.96",concurrently:"7.0.0","downlevel-d
- loopback CIDR 127.0.0.0/8 or [::1/128]
- ECS container host 169.254.170.2
- EKS container host 169.254.170.23 or [fd00:ec2::23]`,{logger:t})}}});var Fet=C(()=>{});var ket=C(()=>{Fet()});var Bet=C(()=>{us()});var $et=C(()=>{});var qet=C(()=>{});function qtr(e){return Object.keys(e).reduce((t,r)=>{let n=e[r];return{...t,[r]:Array.isArray(n)?[...n]:n}},{})}var HG,Uet=C(()=>{HG=class e{constructor(t){this.method=t.method||"GET",this.hostname=t.hostname||"localhost",this.port=t.port,this.query=t.query||{},this.headers=t.headers||{},this.body=t.body,this.protocol=t.protocol?t.protocol.slice(-1)!==":"?`${t.protocol}:`:t.protocol:"https:",this.path=t.path?t.path.charAt(0)!=="/"?`/${t.path}`:t.path:"/",this.username=t.username,this.password=t.password,this.fragment=t.fragment}static clone(t){let r=new e({...t,headers:{...t.headers}});return r.query&&(r.query=qtr(r.query)),r}static isInstance(t){if(!t)return!1;let r=t;return"method"in r&&"protocol"in r&&"hostname"in r&&"path"in r&&typeof r.query=="object"&&typeof r.headers=="object"}clone(){return e.clone(this)}}});var zet=C(()=>{});var Het=C(()=>{});var Vet=C(()=>{});var Wet=C(()=>{ket();Bet();$et();qet();Uet();zet();Het();Vet()});function Jet(e){return new HG({protocol:e.protocol,hostname:e.hostname,port:Number(e.port),path:e.pathname,query:Array.from(e.searchParams.entries()).reduce((t,[r,n])=>(t[r]=n,t),{}),fragment:e.hash})}async function Get(e,t){let n=await l7e(e.body).transformToString();if(e.statusCode===200){let o=JSON.parse(n);if(typeof o.AccessKeyId!="string"||typeof o.SecretAccessKey!="string"||typeof o.Token!="string"||typeof o.Expiration!="string")throw new qu("HTTP credential provider response not of the required format, an object matching: { AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }",{logger:t});return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,sessionToken:o.Token,expiration:E7e(o.Expiration)}}if(e.statusCode>=400&&e.statusCode<500){let o={};try{o=JSON.parse(n)}catch{}throw Object.assign(new qu(`Server responded with status: ${e.statusCode}`,{logger:t}),{Code:o.Code,Message:o.Message})}throw new qu(`Server responded with status: ${e.statusCode}`,{logger:t})}var Ket=C(()=>{ex();Wet();Rt();Bpe()});var Yet,Zet=C(()=>{Yet=(e,t,r)=>async()=>{for(let n=0;n<t;++n)try{return await e()}catch{await new Promise(i=>setTimeout(i,r))}return await e()}});var Cme,Xet=C(()=>{QU();ex();Let();Ket();Zet();Cme=(e={})=>{e.logger?.debug("@aws-sdk/credential-provider-http - fromHttp");let t,r=e.credentialsFullUri;if(r)t=r;else throw new qu("No HTTP credential provider host provided.",{logger:e.logger});let n=new URL(t);Net(n,e.logger);let o=new bE;return Yet(async()=>{let i=Jet(n);e.authorizationToken&&(i.headers.Authorization=e.authorizationToken);let a=await o.handle(i);return Get(a.response)},e.maxRetries??3,e.timeout??1e3)}});var Qet=C(()=>{Xet()});function Utr(e){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sts",region:e.region},propertiesExtractor:(t,r)=>({signingProperties:{config:t,context:r}})}}function ett(e){return{schemeId:"smithy.api#noAuth"}}var ttt,rtt,ztr,ntt,Ome=C(()=>{ZI();eg();gz();ttt=async(e,t,r)=>({operation:jy(t).operation,region:await zc(e.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});rtt=e=>{let t=[];switch(e.operation){case"AssumeRoleWithSAML":{t.push(ett(e));break}case"AssumeRoleWithWebIdentity":{t.push(ett(e));break}default:t.push(Utr(e))}return t},ztr=e=>({...e,stsClientCtor:Ch}),ntt=e=>{let t=ztr(e);return{...KJ(t)}}});var ott,Vc,qy=C(()=>{ott=e=>({...e,useDualstackEndpoint:e.useDualstackEndpoint??!1,useFipsEndpoint:e.useFipsEndpoint??!1,useGlobalEndpoint:e.useGlobalEndpoint??!1,defaultSigningName:"sts"}),Vc={UseGlobalEndpoint:{type:"builtInParams",name:"useGlobalEndpoint"},UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}});var att,itt=C(()=>{att={name:"@aws-sdk/client-sts",description:"AWS SDK for JavaScript Sts Client for Node.js, Browse
`);return this.signString(h,{signingDate:n,signingRegion:s,signingService:a})}async signMessage(t,{signingDate:r=new Date,signingRegion:n,signingService:o}){return this.signEvent({headers:this.headerMarshaller.format(t.message.headers),payload:t.message.body},{signingDate:r,signingRegion:n,signingService:o,priorSignature:t.priorSignature}).then(a=>({message:t.message,signature:a}))}async signString(t,{signingDate:r=new Date,signingRegion:n,signingService:o}={}){let i=await this.credentialProvider();this.validateResolvedCredentials(i);let a=n??await this.regionProvider(),{shortDate:s}=UK(r),u=new this.sha256(await this.getSigningKey(i,a,s,o));return u.update((0,$z.toUint8Array)(t)),(0,$K.toHex)(await u.digest())}async signRequest(t,{signingDate:r=new Date,signableHeaders:n,unsignableHeaders:o,signingRegion:i,signingService:a}={}){let s=await this.credentialProvider();this.validateResolvedCredentials(s);let u=i??await this.regionProvider(),l=(0,oat.prepareRequest)(t),{longDate:c,shortDate:d}=UK(r),f=(0,qK.createScope)(d,u,a??this.service);l.headers[Kl.AMZ_DATE_HEADER]=c,s.sessionToken&&(l.headers[Kl.TOKEN_HEADER]=s.sessionToken);let p=await(0,cye.getPayloadHash)(l,this.sha256);!(0,uir.hasHeader)(Kl.SHA256_HEADER,l.headers)&&this.applyChecksum&&(l.headers[Kl.SHA256_HEADER]=p);let h=(0,nat.getCanonicalHeaders)(l,o,n),m=await this.getSignature(c,f,this.getSigningKey(s,u,d,a),this.createCanonicalRequest(l,h,p));return l.headers[Kl.AUTH_HEADER]=`${Kl.ALGORITHM_IDENTIFIER} Credential=${s.accessKeyId}/${f}, SignedHeaders=${iat(h)}, Signature=${m}`,l}createCanonicalRequest(t,r,n){let o=Object.keys(r).sort();return`${t.method}
${this.getCanonicalPath(t)}
${(0,sir.getCanonicalQuery)(t)}
${o.map(i=>`${i}:${r[i]}`).join(`
`)}
${o.join(";")}
${n}`}async createStringToSign(t,r,n){let o=new this.sha256;o.update((0,$z.toUint8Array)(n));let i=await o.digest();return`${Kl.ALGORITHM_IDENTIFIER}
${t}
${r}
${(0,$K.toHex)(i)}`}getCanonicalPath({path:t}){if(this.uriEscapePath){let r=[];for(let i of t.split("/"))i?.length!==0&&i!=="."&&(i===".."?r.pop():r.push(i));let n=`${t?.startsWith("/")?"/":""}${r.join("/")}${r.length>0&&t?.endsWith("/")?"/":""}`;return encodeURIComponent(n).replace(/%2F/g,"/")}return t}async getSignature(t,r,n,o){let i=await this.createStringToSign(t,r,o),a=new this.sha256(await n);return a.update((0,$z.toUint8Array)(i)),(0,$K.toHex)(await a.digest())}getSigningKey(t,r,n,o){return(0,qK.getSigningKey)(this.sha256,t,n,r,o||this.service)}validateResolvedCredentials(t){if(typeof t!="object"||typeof t.accessKeyId!="string"||typeof t.secretAccessKey!="string")throw new Error("Resolved credential object is not valid")}};zK.SignatureV4=dye;var UK=e=>{let t=(0,cir.iso8601)(e).replace(/[\-:]/g,"");return{longDate:t,shortDate:t.slice(0,8)}},iat=e=>Object.keys(e).sort().join(";")});var uat=b(yf=>{"use strict";Object.defineProperty(yf,"__esModule",{value:!0});yf.prepareRequest=yf.moveHeadersToQuery=yf.getPayloadHash=yf.getCanonicalQuery=yf.getCanonicalHeaders=void 0;var sat=(oA(),il(nA));sat.__exportStar(aat(),yf);var dir=nye();Object.defineProperty(yf,"getCanonicalHeaders",{enumerable:!0,get:function(){return dir.getCanonicalHeaders}});var fir=iye();Object.defineProperty(yf,"getCanonicalQuery",{enumerable:!0,get:function(){return fir.getCanonicalQuery}});var pir=aye();Object.defineProperty(yf,"getPayloadHash",{enumerable:!0,get:function(){return pir.getPayloadHash}});var hir=uye();Object.defineProperty(yf,"moveHeadersToQuery",{enumerable:!0,get:function(){return hir.moveHeadersToQuery}});var mir=lye();Object.defineProperty(yf,"prepareRequest",{enumerable:!0,get:function(){return mir.prepareRequest}});sat.__exportStar(tye(),yf)});var lat=b(fye=>{"use strict";Object.defineProperty(fye,"__esModule",{value:!0});var gir=(oA(),il(nA));gir.__exportStar(uat(),fye)});var la=b((ito,cat)=>{"use strict";cat.exports={ArrayIsArray(e){return Array.isArray(e)},ArrayPrototypeIncludes(e,t){return e.includes(t)},ArrayPrototypeIndexOf(e,t){return e.indexOf(t)},ArrayPrototypeJoin(e,t){return e.join(t)},ArrayPrototypeMap(e,t){return e.map(t)},ArrayPrototypePop(e,t){return e.pop(t)},ArrayPrototypePush(e,t){return e.push(t)},ArrayPrototypeSlice(e,t,r){return e.slice(t,r)},Error,FunctionPrototypeCall(e,t,...r){return e.call(t,...r)},FunctionPrototypeSymbolHasInstance(e,t){return Function.prototype[Symbol.hasInstance].call(e,t)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(e,t){return Object.defineProperties(e,t)},ObjectDefineProperty(e,t,r){return Object.defineProperty(e,t,r)},ObjectGetOwnPropertyDescriptor(e,t){return Object.getOwnPropertyDescriptor(e,t)},ObjectKeys(e){return Object.keys(e)},ObjectSetPrototypeOf(e,t){return Object.setPrototypeOf(e,t)},Promise,PromisePrototypeCatch(e,t){return e.catch(t)},PromisePrototypeThen(e,t,r){return e.then(t,r)},PromiseReject(e){return Promise.reject(e)},PromiseResolve(e){return Promise.resolve(e)},ReflectApply:Reflect.apply,RegExpPrototypeTest(e,t){return e.test(t)},SafeSet:Set,String,StringPrototypeSlice(e,t,r){return e.slice(t,r)},StringPrototypeToLowerCase(e){return e.toLowerCase()},StringPrototypeToUpperCase(e){return e.toUpperCase()},StringPrototypeTrim(e){return e.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(e,t,r){return e.set(t,r)},Boolean,Uint8Array}});var BN=b((ato,HK)=>{"use strict";var{AbortController:dat,AbortSignal:yir}=typeof self<"u"?self:typeof window<"u"?window:void 0;HK.exports=dat;HK.exports.AbortSignal=yir;HK.exports.default=dat});var qz=b((sto,pye)=>{"use strict";var $N=typeof Reflect=="object"?Reflect:null,fat=$N&&typeof $N.apply=="function"?$N.a
`;super(r),this.name="AggregateError",this.errors=t}};mye.exports={AggregateError:hye,kEmptyObject:Object.freeze({}),once(e){let t=!1;return function(...r){t||(t=!0,e.apply(this,r))}},createDeferredPromise:function(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}},promisify(e){return new Promise((t,r)=>{e((n,...o)=>n?r(n):t(...o))})},debuglog(){return function(){}},format(e,...t){return e.replace(/%([sdifj])/g,function(...[r,n]){let o=t.shift();return n==="f"?o.toFixed(6):n==="j"?JSON.stringify(o):n==="s"&&typeof o=="object"?`${o.constructor!==Object?o.constructor.name:""} {}`.trim():o.toString()})},inspect(e){switch(typeof e){case"string":if(e.includes("'"))if(e.includes('"')){if(!e.includes("`")&&!e.includes("${"))return`\`${e}\``}else return`"${e}"`;return`'${e}'`;case"number":return isNaN(e)?"NaN":Object.is(e,-0)?String(e):e;case"bigint":return`${String(e)}n`;case"boolean":case"undefined":return String(e);case"object":return"{}"}},types:{isAsyncFunction(e){return e instanceof Mir},isArrayBufferView(e){return ArrayBuffer.isView(e)}},isBlob:Iir,deprecate(e,t){return e},addAbortListener:qz().addAbortListener||function(t,r){if(t===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",t);xat(t,"signal"),Air(r,"listener");let n;return t.aborted?queueMicrotask(()=>r()):(t.addEventListener("abort",r,{__proto__:null,once:!0,[Oir]:!0}),n=()=>{t.removeEventListener("abort",r)}),{__proto__:null,[Eir](){var o;(o=n)===null||o===void 0||o()}}},AbortSignalAny:Pir.any||function(t){if(t.length===1)return t[0];let r=new Tir,n=()=>r.abort();return t.forEach(o=>{xat(o,"signals"),o.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{t.forEach(o=>o.removeEventListener("abort",n))},{once:!0}),r.signal}};mye.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var Ld=b((lto,Eat)=>{"use strict";var{format:Rir,inspect:JK,AggregateError:Dir}=Gc(),jir=globalThis.AggregateError||Dir,Nir=Symbol("kIsNodeError"),Lir=["string","function","number","object","Function","Object","boolean","bigint","symbol"],Fir=/^([A-Z][a-z0-9]*)+$/,kir="__node_internal_",GK={};function lA(e,t){if(!e)throw new GK.ERR_INTERNAL_ASSERTION(t)}function Cat(e){let t="",r=e.length,n=e[0]==="-"?1:0;for(;r>=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function Bir(e,t,r){if(typeof t=="function")return lA(t.length<=r.length,`Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${t.length}).`),t(...r);let n=(t.match(/%[dfijoOs]/g)||[]).length;return lA(n===r.length,`Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?t:Rir(t,...r)}function Yl(e,t,r){r||(r=Error);class n extends r{constructor(...i){super(Bir(e,t,i))}toString(){return`${this.name} [${e}]: ${this.message}`}}Object.defineProperties(n.prototype,{name:{value:r.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${e}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),n.prototype.code=e,n.prototype[Nir]=!0,GK[e]=n}function Oat(e){let t=kir+e.name;return Object.defineProperty(e,"name",{value:t}),e}function $ir(e,t){if(e&&t&&e!==t){if(Array.isArray(t.errors))return t.errors.push(e),t;let r=new jir([t,e],t.message);return r.code=t.code,r}return e||t}var gye=class extends Error{constructor(t="The operation was aborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new GK.ERR_INVALID_ARG_TYPE("options","Object",r);super(t,r),this.code="ABORT_ERR",this.name="AbortError"}};Yl("ERR_ASSERTION","%s",Error);Yl("ERR_INVALID_ARG_TYPE",(e,t,r)=>{lA(typeof e=="string","'name' must be a string"),Array.isArray(t)||(t=[t]);let n="The ";e.endsWith(" argument")?n+=`${e} `:n+=`"${e}" ${e.includes(".")?"property":"argument"} `,n+="must be ";let o=[],i=[],a=[];for(let u of t)lA(typeof u=="string","All expected entries have to be of type string"),Lir.includes(u)?o.push(u.toLowerCase()):Fir.test(u)?i.push(u):(lA(u!=="object",'The value "object" should be written as "Object"'),a.push(u));if(i.length>0){let
`)>=0)return!1;return!0}function mdr(e,t){var r;if(e.indent===" ")r=" ";else if(typeof e.indent=="number"&&e.indent>0)r=Qy.call(Array(e.indent+1)," ");else return null;return{base:r,prev:Qy.call(Array(t+1),r)}}function Nbe(e,t){if(e.length===0)return"";var r=`
`+t.prev+t.base;return r+Qy.call(e,","+r)+`
`+t.prev}function C7(e,t){var r=jbe(e),n=[];if(r){n.length=e.length;for(var o=0;o<e.length;o++)n[o]=_x(e,o)?t(e[o],e):""}var i=typeof Mbe=="function"?Mbe(e):[],a;if(eL){a={};for(var s=0;s<i.length;s++)a["$"+i[s]]=i[s]}for(var u in e)_x(e,u)&&(r&&String(Number(u))===u&&u<e.length||eL&&a["$"+u]instanceof Symbol||(Rlt.call(/[^\w$]/,u)?n.push(t(u,e)+": "+t(e[u],e)):n.push(u+": "+t(e[u],e))));if(typeof Mbe=="function")for(var l=0;l<i.length;l++)Dlt.call(e,i[l])&&n.push("["+t(i[l])+"]: "+t(e[i[l]],e));return n}});var qlt=b((kto,$lt)=>{"use strict";var gdr=o2(),ydr=wA(),P7=function(e,t,r){for(var n=e,o;(o=n.next)!=null;n=o)if(o.key===t)return n.next=o.next,r||(o.next=e.next,e.next=o),o},bdr=function(e,t){if(e){var r=P7(e,t);return r&&r.value}},_dr=function(e,t,r){var n=P7(e,t);n?n.value=r:e.next={key:t,next:e.next,value:r}},vdr=function(e,t){return e?!!P7(e,t):!1},wdr=function(e,t){if(e)return P7(e,t,!0)};$lt.exports=function(){var t,r={assert:function(n){if(!r.has(n))throw new ydr("Side channel does not contain "+gdr(n))},delete:function(n){var o=t&&t.next,i=wdr(t,n);return i&&o&&o===i&&(t=void 0),!!i},get:function(n){return bdr(t,n)},has:function(n){return vdr(t,n)},set:function(n,o){t||(t={next:void 0}),_dr(t,n,o)}};return r}});var Bbe=b((Bto,Ult)=>{"use strict";Ult.exports=Object});var Hlt=b(($to,zlt)=>{"use strict";zlt.exports=Error});var Wlt=b((qto,Vlt)=>{"use strict";Vlt.exports=EvalError});var Glt=b((Uto,Jlt)=>{"use strict";Jlt.exports=RangeError});var Ylt=b((zto,Klt)=>{"use strict";Klt.exports=ReferenceError});var Xlt=b((Hto,Zlt)=>{"use strict";Zlt.exports=SyntaxError});var ect=b((Vto,Qlt)=>{"use strict";Qlt.exports=URIError});var rct=b((Wto,tct)=>{"use strict";tct.exports=Math.abs});var oct=b((Jto,nct)=>{"use strict";nct.exports=Math.floor});var act=b((Gto,ict)=>{"use strict";ict.exports=Math.max});var uct=b((Kto,sct)=>{"use strict";sct.exports=Math.min});var cct=b((Yto,lct)=>{"use strict";lct.exports=Math.pow});var fct=b((Zto,dct)=>{"use strict";dct.exports=Math.round});var hct=b((Xto,pct)=>{"use strict";pct.exports=Number.isNaN||function(t){return t!==t}});var gct=b((Qto,mct)=>{"use strict";var Sdr=hct();mct.exports=function(t){return Sdr(t)||t===0?t:t<0?-1:1}});var bct=b((ero,yct)=>{"use strict";yct.exports=Object.getOwnPropertyDescriptor});var $be=b((tro,_ct)=>{"use strict";var T7=bct();if(T7)try{T7([],"length")}catch{T7=null}_ct.exports=T7});var wct=b((rro,vct)=>{"use strict";var M7=Object.defineProperty||!1;if(M7)try{M7({},"a",{value:1})}catch{M7=!1}vct.exports=M7});var xct=b((nro,Sct)=>{"use strict";Sct.exports=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var t={},r=Symbol("test"),n=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var o=42;t[r]=o;for(var i in t)return!1;if(typeof Object.keys=="function"&&Object.keys(t).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(t).length!==0)return!1;var a=Object.getOwnPropertySymbols(t);if(a.length!==1||a[0]!==r||!Object.prototype.propertyIsEnumerable.call(t,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var s=Object.getOwnPropertyDescriptor(t,r);if(s.value!==o||s.enumerable!==!0)return!1}return!0}});var Ect=b((oro,Oct)=>{"use strict";var Cct=typeof Symbol<"u"&&Symbol,xdr=xct();Oct.exports=function(){return typeof Cct!="function"||typeof Symbol!="function"||typeof Cct("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:xdr()}});var qbe=b((iro,Pct)=>{"use strict";Pct.exports=typeof Reflect<"u"&&Reflect.getPrototypeOf||null});var Ube=b((aro,Tct)=>{"use strict";var Cdr=Bbe();Tct.exports=Cdr.getPrototypeOf||null});var Act=b((sro,Ict)=>{"use strict";var Odr="Function.prototype.bind called on incompatible ",Edr=Object.prototype.toString,Pdr=Math.max,Tdr="[object Function]",Mct=function(t,r){for(var n=[],o=0;o<t.length;o+=1)n[o]=t[o];for(var i=0;i<r.length;i+=1)n[i+t.length]=r[i];return n},Mdr=function(t,r){for(var n=[],o=r|
`,this.streamTerminator=n.streamTerminator):this.messageTerminator=n.messageTerminator,o?.addEventListener("abort",()=>this.controller.abort())}iterMessages(){return oft(this,arguments,function*(){var r,n;this.controller.signal;let o=ift(this.stream),i="",a=!1;try{for(var s=nft(o),u;u=yield ag(s.next()),!u.done;){let l=u.value;i+=this.decodeChunk(l);let c;for(;(c=i.indexOf(this.messageTerminator))>=0;){let d=i.slice(0,c+1);if(i=i.slice(c+1),d.length===0)continue;if(!a&&this.prefix!=null){let p=d.indexOf(this.prefix);if(p===-1)continue;a=!0,d=d.slice(p+this.prefix.length)}if(this.streamTerminator!=null&&d.includes(this.streamTerminator))return yield ag(void 0);let f=yield ag(this.parse(JSON.parse(d)));yield yield ag(f),a=!1}}}catch(l){r={error:l}}finally{try{u&&!u.done&&(n=s.return)&&(yield ag(n.call(s)))}finally{if(r)throw r.error}}})}[Symbol.asyncIterator](){return oft(this,arguments,function*(){var r,n;try{for(var o=nft(this.iterMessages()),i;i=yield ag(o.next()),!i.done;){let a=i.value;yield yield ag(a)}}catch(a){r={error:a}}finally{try{i&&!i.done&&(n=o.return)&&(yield ag(n.call(o)))}finally{if(r)throw r.error}}})}decodeChunk(t){let r="";if(typeof TextDecoder<"u"){let n=new TextDecoder("utf8");r+=n.decode(t)}else chr.RUNTIME.type==="node"&&typeof t<"u"&&(r+=Buffer.isBuffer(t)?t:Buffer.from(t));return r}};bf.Stream=p_e;function ift(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{next(){return rft(this,void 0,void 0,function*(){try{let r=yield t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}})},return(){return rft(this,void 0,void 0,function*(){let r=t.cancel();return t.releaseLock(),yield r,{done:!0,value:void 0}})},[Symbol.asyncIterator](){return this}}}bf.readableStreamAsyncIterable=ift});var aft=b(W7=>{"use strict";Object.defineProperty(W7,"__esModule",{value:!0});W7.Stream=void 0;var fhr=h_e();Object.defineProperty(W7,"Stream",{enumerable:!0,get:function(){return fhr.Stream}})});var lft=b((Kro,uft)=>{"use strict";var m_e=Object.defineProperty,phr=Object.getOwnPropertyDescriptor,hhr=Object.getOwnPropertyNames,mhr=Object.prototype.hasOwnProperty,ghr=(e,t)=>{for(var r in t)m_e(e,r,{get:t[r],enumerable:!0})},yhr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of hhr(t))!mhr.call(e,o)&&o!==r&&m_e(e,o,{get:()=>t[o],enumerable:!(n=phr(t,o))||n.enumerable});return e},bhr=e=>yhr(m_e({},"__esModule",{value:!0}),e),sft={};ghr(sft,{Blob:()=>whr,File:()=>Shr,FormData:()=>vhr});uft.exports=bhr(sft);var _hr=function(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:window}(),{FormData:vhr,Blob:whr,File:Shr}=_hr});var Sft=b((Yro,wft)=>{"use strict";var b_e=Object.defineProperty,xhr=Object.getOwnPropertyDescriptor,Chr=Object.getOwnPropertyNames,Ohr=Object.prototype.hasOwnProperty,Ehr=(e,t)=>{for(var r in t)b_e(e,r,{get:t[r],enumerable:!0})},Phr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Chr(t))!Ohr.call(e,o)&&o!==r&&b_e(e,o,{get:()=>t[o],enumerable:!(n=xhr(t,o))||n.enumerable});return e},Thr=e=>Phr(b_e({},"__esModule",{value:!0}),e),__e=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},Ia=(e,t,r)=>(__e(e,t,"read from private field"),r?r.call(e):t.get(e)),tb=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},f2=(e,t,r,n)=>(__e(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r),g_e=(e,t,r)=>(__e(e,t,"access private method"),r),gft={};Ehr(gft,{FormDataEncoder:()=>Lhr,isFile:()=>EA,isFormData:()=>_ft});wft.exports=Thr(gft);var wx=e=>typeof e=="function",Mhr=e=>wx(e[Symbol.asyncIterator]),cft=65536;function*yft(e){if(e.byteLength<=cft){yield e;return}let t=0;for(;t<e.byteLength;){let r=Math.min(e.byteLength-t,cft),n=e.buffer.slice(t,t+r);t+=n.byteLength,yield new Uint8Array(n)}}async function*Ihr(e){let t=e.getReader();for(;;){let{done:r,value:n}=await t.read();if(r)break;yield n}}async function*dft(e){for await(let t of e)yield*yft(t)}var Ahr=e=>{if(Mhr(e))return dft(e);if(wx(e.getReader))return dft(Ihr(e));throw new TypeError("Unsupport
`||t===`
`&&n[r-1]!=="\r"?`\r
`:t),Dhr=e=>Object.prototype.toString.call(e).slice(8,-1).toLowerCase();function pft(e){if(Dhr(e)!=="object")return!1;let t=Object.getPrototypeOf(e);return t==null?!0:(t.constructor&&t.constructor.toString())===Object.toString()}function hft(e,t){if(typeof t=="string"){for(let[r,n]of Object.entries(e))if(t.toLowerCase()===r.toLowerCase())return n}}var jhr=e=>new Proxy(e,{get:(t,r)=>hft(t,r),has:(t,r)=>hft(t,r)!==void 0}),_ft=e=>!!(e&&wx(e.constructor)&&e[Symbol.toStringTag]==="FormData"&&wx(e.append)&&wx(e.getAll)&&wx(e.entries)&&wx(e[Symbol.iterator])),mft=e=>String(e).replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/"/g,"%22"),EA=e=>!!(e&&typeof e=="object"&&wx(e.constructor)&&e[Symbol.toStringTag]==="File"&&wx(e.stream)&&e.name!=null),Nhr={enableAdditionalHeaders:!1},J7={writable:!1,configurable:!1},KE,p2,G7,h2,OA,m2,g2,K7,Y7,v_e,y_e,vft,Lhr=class{constructor(e,t,r){if(tb(this,Y7),tb(this,y_e),tb(this,KE,`\r
`),tb(this,p2,void 0),tb(this,G7,void 0),tb(this,h2,"-".repeat(2)),tb(this,OA,new TextEncoder),tb(this,m2,void 0),tb(this,g2,void 0),tb(this,K7,void 0),!_ft(e))throw new TypeError("Expected first argument to be a FormData instance.");let n;if(pft(t)?r=t:n=t,n||(n=Rhr()),typeof n!="string")throw new TypeError("Expected boundary argument to be a string.");if(r&&!pft(r))throw new TypeError("Expected options argument to be an object.");f2(this,g2,Array.from(e.entries())),f2(this,K7,{...Nhr,...r}),f2(this,p2,Ia(this,OA).encode(Ia(this,KE))),f2(this,G7,Ia(this,p2).byteLength),this.boundary=`form-data-boundary-${n}`,this.contentType=`multipart/form-data; boundary=${this.boundary}`,f2(this,m2,Ia(this,OA).encode(`${Ia(this,h2)}${this.boundary}${Ia(this,h2)}${Ia(this,KE).repeat(2)}`));let o={"Content-Type":this.contentType},i=g_e(this,y_e,vft).call(this);i&&(this.contentLength=i,o["Content-Length"]=i),this.headers=jhr(Object.freeze(o)),Object.defineProperties(this,{boundary:J7,contentType:J7,contentLength:J7,headers:J7})}*values(){for(let[e,t]of Ia(this,g2)){let r=EA(t)?t:Ia(this,OA).encode(bft(t));yield g_e(this,Y7,v_e).call(this,e,r),yield r,yield Ia(this,p2)}yield Ia(this,m2)}async*encode(){for(let e of this.values())EA(e)?yield*Ahr(e.stream()):yield*yft(e)}[Symbol.iterator](){return this.values()}[Symbol.asyncIterator](){return this.encode()}};KE=new WeakMap;p2=new WeakMap;G7=new WeakMap;h2=new WeakMap;OA=new WeakMap;m2=new WeakMap;g2=new WeakMap;K7=new WeakMap;Y7=new WeakSet;v_e=function(e,t){let r="";if(r+=`${Ia(this,h2)}${this.boundary}${Ia(this,KE)}`,r+=`Content-Disposition: form-data; name="${mft(e)}"`,EA(t)&&(r+=`; filename="${mft(t.name)}"${Ia(this,KE)}`,r+=`Content-Type: ${t.type||"application/octet-stream"}`),Ia(this,K7).enableAdditionalHeaders===!0){let n=EA(t)?t.size:t.byteLength;n!=null&&!isNaN(n)&&(r+=`${Ia(this,KE)}Content-Length: ${n}`)}return Ia(this,OA).encode(`${r}${Ia(this,KE).repeat(2)}`)};y_e=new WeakSet;vft=function(){let e=0;for(let[t,r]of Ia(this,g2)){let n=EA(r)?r:Ia(this,OA).encode(bft(r)),o=EA(n)?n.size:n.byteLength;if(o==null||isNaN(o))return;e+=g_e(this,Y7,v_e).call(this,t,n).byteLength,e+=o,e+=Ia(this,G7)}return String(e+Ia(this,m2).byteLength)}});var Cft=b((Xro,xft)=>{xft.exports=typeof self=="object"?self.FormData:window.FormData});var Oft=b(ml=>{"use strict";var Fhr=ml&&ml.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),khr=ml&&ml.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),_L=ml&&ml.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&Fhr(t,e,r);return khr(t,e),t},YE=ml&&ml.__awaiter||function(e,t,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(c){try{l(n.next(c))}catch(d){a(d)}}function u(c){try{l(n.throw(c))}catch(d){a(d)}}function l(c){c.done?i(c.value):o(c.value).then(s,u)}l((n=n.apply(e,t||[])).next())})};Object.defineProperty(ml,"__esModule",{value:!0});ml.WebFormData=ml.Node16FormData=ml.Node18FormData=ml.newFormData=void 0;var Z7=uL();function w_e(e){return typeof e=="object"&&e!=null&&"name"in e}function Bhr(){return YE(this,void 0,void 0,function*(){let e;return Z7.RUNTIME.type==="node"&&Z7.RUNTIME.parsedVersion!=null&&Z7.RUNTIME.parsedVersion>=18?e=new X7:Z7.RUNTIME.type==="node"?e=new Q7:e=new eY,yield e.setup(),e})}ml.newFormData=Bhr;var X7=class{setup(){return YE(this,void 0,void 0,function*(){this.fd=new(yield Promise.resolve().then(()=>_L(lft()))).FormData})}append(t,r){var n;(n=this.fd)===null||n===void 0||n.append(t,r)}appendFile(t,r,n){var o,i;return YE(this,void 0,void 0,function*(){n==null&&w_e(r)&&(n=r.name),r instanceof(yield Promise.resolve().then(()=>_L(e2()))).Readable
`)),{ok:!0,value:t}):n}}});var S_e=b(oY=>{"use strict";Object.defineProperty(oY,"__esModule",{value:!0});oY.stringifyValidationError=void 0;function Vhr(e){return e.path.length===0?e.message:`${e.path.join(" -> ")}: ${e.message}`}oY.stringifyValidationError=Vhr});var C_e=b(iY=>{"use strict";Object.defineProperty(iY,"__esModule",{value:!0});iY.JsonError=void 0;var Whr=S_e(),x_e=class e extends Error{constructor(t){super(t.map(Whr.stringifyValidationError).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};iY.JsonError=x_e});var E_e=b(aY=>{"use strict";Object.defineProperty(aY,"__esModule",{value:!0});aY.ParseError=void 0;var Jhr=S_e(),O_e=class e extends Error{constructor(t){super(t.map(Jhr.stringifyValidationError).join("; ")),this.errors=t,Object.setPrototypeOf(this,e.prototype)}};aY.ParseError=O_e});var Ift=b(ZE=>{"use strict";Object.defineProperty(ZE,"__esModule",{value:!0});ZE.transform=ZE.optional=ZE.getSchemaUtils=void 0;var Ghr=Zl(),Khr=C_e(),Yhr=E_e();function P_e(e){return{optional:()=>Tft(e),transform:t=>Mft(e,t),parseOrThrow:(t,r)=>{let n=e.parse(t,r);if(n.ok)return n.value;throw new Yhr.ParseError(n.errors)},jsonOrThrow:(t,r)=>{let n=e.json(t,r);if(n.ok)return n.value;throw new Khr.JsonError(n.errors)}}}ZE.getSchemaUtils=P_e;function Tft(e){let t={parse:(r,n)=>r==null?{ok:!0,value:void 0}:e.parse(r,n),json:(r,n)=>n?.omitUndefined&&r===void 0?{ok:!0,value:void 0}:r==null?{ok:!0,value:null}:e.json(r,n),getType:()=>Ghr.SchemaType.OPTIONAL};return Object.assign(Object.assign({},t),P_e(t))}ZE.optional=Tft;function Mft(e,t){let r={parse:(n,o)=>{let i=e.parse(n,o);return i.ok?{ok:!0,value:t.transform(i.value)}:i},json:(n,o)=>{let i=t.untransform(n);return e.json(i,o)},getType:()=>e.getType()};return Object.assign(Object.assign({},r),P_e(r))}ZE.transform=Mft});var fp=b(Dh=>{"use strict";Object.defineProperty(Dh,"__esModule",{value:!0});Dh.ParseError=Dh.JsonError=Dh.transform=Dh.optional=Dh.getSchemaUtils=void 0;var T_e=Ift();Object.defineProperty(Dh,"getSchemaUtils",{enumerable:!0,get:function(){return T_e.getSchemaUtils}});Object.defineProperty(Dh,"optional",{enumerable:!0,get:function(){return T_e.optional}});Object.defineProperty(Dh,"transform",{enumerable:!0,get:function(){return T_e.transform}});var Zhr=C_e();Object.defineProperty(Dh,"JsonError",{enumerable:!0,get:function(){return Zhr.JsonError}});var Xhr=E_e();Object.defineProperty(Dh,"ParseError",{enumerable:!0,get:function(){return Xhr.ParseError}})});var Aft=b(sY=>{"use strict";Object.defineProperty(sY,"__esModule",{value:!0});sY.date=void 0;var Qhr=Zl(),M_e=_f(),emr=Sx(),tmr=fp(),rmr=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function nmr(){let e={parse:(t,{breadcrumbsPrefix:r=[]}={})=>typeof t!="string"?{ok:!1,errors:[{path:r,message:(0,M_e.getErrorMessageForIncorrectType)(t,"string")}]}:rmr.test(t)?{ok:!0,value:new Date(t)}:{ok:!1,errors:[{path:r,message:(0,M_e.getErrorMessageForIncorrectType)(t,"ISO 8601 date string")}]},json:(t,{breadcrumbsPrefix:r=[]}={})=>t instanceof Date?{ok:!0,value:t.toISOString()}:{ok:!1,errors:[{path:r,message:(0,M_e.getErrorMessageForIncorrectType)(t,"Date object")}]},getType:()=>Qhr.SchemaType.DATE};return Object.assign(Object.assign({},(0,emr.maybeSkipValidation)(e)),(0,tmr.getSchemaUtils)(e))}sY.date=nmr});var Rft=b(uY=>{"use strict";Object.defineProperty(uY,"__esModule",{value:!0});uY.date=void 0;var omr=Aft();Object.defineProperty(uY,"date",{enumerable:!0,get:function(){return omr.date}})});var xx=b(lY=>{"use strict";Object.defineProperty(lY,"__esModule",{value:!0});lY.createIdentitySchemaCreator=void 0;var imr=fp(),amr=Sx();function smr(e,t){return()=>{let r={parse:t,json:t,getType:()=>e};return Object.assign(Object.assign({},(0,amr.maybeSkipValidation)(r)),(0,imr.getSchemaUtils)(r))}}lY.createIdentitySchemaCreator=smr});var jft=b(cY=>{"use strict";Object.defineProperty
`);o.enqueue(s)}catch(i){o.error(i)}})},cancel(){var o;return S2(this,void 0,void 0,function*(){yield(o=r.return)===null||o===void 0?void 0:o.call(r)})}})}};ls.StreamUtils=U_e;function Ept(e,t){return C2(this,arguments,function*(){var n,o;if(!e.body)throw t?.abort(),new TL.CohereError({message:"Attempted to iterate over a response with no body"});let i=new z_e,a=new QE,s=H_e(e.body);try{for(var u=x2(nyr(s)),l;l=yield zi(u.next()),!l.done;){let c=l.value;for(let d of a.decode(c)){let f=i.decode(d);f&&(yield yield zi(f))}}}catch(c){n={error:c}}finally{try{l&&!l.done&&(o=u.return)&&(yield zi(o.call(u)))}finally{if(n)throw n.error}}for(let c of a.flush()){let d=i.decode(c);d&&(yield yield zi(d))}})}ls._iterSSEMessages=Ept;function nyr(e){return C2(this,arguments,function*(){var r,n;let o=new Uint8Array;try{for(var i=x2(e),a;a=yield zi(i.next()),!a.done;){let s=a.value;if(s==null)continue;let u=s instanceof ArrayBuffer?new Uint8Array(s):typeof s=="string"?new TextEncoder().encode(s):s,l=new Uint8Array(o.length+u.length);l.set(o),l.set(u,o.length),o=l;let c;for(;(c=oyr(o))!==-1;)yield yield zi(o.slice(0,c)),o=o.slice(c)}}catch(s){r={error:s}}finally{try{a&&!a.done&&(n=i.return)&&(yield zi(n.call(i)))}finally{if(r)throw r.error}}o.length>0&&(yield yield zi(o))})}function oyr(e){for(let n=0;n<e.length-2;n++){if(e[n]===10&&e[n+1]===10||e[n]===13&&e[n+1]===13)return n+2;if(e[n]===13&&e[n+1]===10&&n+3<e.length&&e[n+2]===13&&e[n+3]===10)return n+4}return-1}var z_e=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(t){if(t.endsWith("\r")&&(t=t.substring(0,t.length-1)),!t){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(t),t.startsWith(":"))return null;let[r,n,o]=ayr(t,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},QE=class e{constructor(){this.buffer=[],this.trailingCR=!1}decode(t){let r=this.decodeText(t);if(this.trailingCR&&(r="\r"+r,this.trailingCR=!1),r.endsWith("\r")&&(this.trailingCR=!0,r=r.slice(0,-1)),!r)return[];let n=e.NEWLINE_CHARS.has(r[r.length-1]||""),o=r.split(e.NEWLINE_REGEXP);return n&&o.pop(),o.length===1&&!n?(this.buffer.push(o[0]),[]):(this.buffer.length>0&&(o=[this.buffer.join("")+o[0],...o.slice(1)],this.buffer=[]),n||(this.buffer=[o.pop()||""]),o)}decodeText(t){var r;if(t==null)return"";if(typeof t=="string")return t;if(typeof Buffer<"u"){if(t instanceof Buffer)return t.toString();if(t instanceof Uint8Array)return Buffer.from(t).toString();throw new TL.CohereError({message:`Unexpected: received non-Uint8Array (${t.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`})}if(typeof TextDecoder<"u"){if(t instanceof Uint8Array||t instanceof ArrayBuffer)return(r=this.textDecoder)!==null&&r!==void 0||(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(t);throw new TL.CohereError({message:`Unexpected: received non-Uint8Array/ArrayBuffer (${t.constructor.name}) in a web platform. Please report this error.`})}throw new TL.CohereError({message:"Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error."})}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let t=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,t}};ls.LineDecoder=QE;QE.NEWLINE_CHARS=new Set([`
`,"\r"]);QE.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function iyr(e){let t=new QE,r=[];for(let n of e)r.push(...t.decode(n));return r}ls._decodeChunks=iyr;function ayr(e,t){let r=e.indexOf(t);return r!==-1?[e.substring(0,r),t,e.substring(r+t.length)]:[e,"",""]}function H_e(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{next(){return S2(this,void 0,void 0,function*(){try{let r=yield t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}})},return(){return S2(this,void 0,void 0,function*(){let r=t.cancel();return t.releaseLock(),yield r,{done:!0,value:void 0}})},[Symbol.asyncIterator](){return this}}}ls.readableStreamAsyncIterable=H_e});var V_e=b(rb=>{"use strict";var syr=rb&&rb.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),uyr=rb&&rb.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),lyr=rb&&rb.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&syr(t,e,r);return uyr(t,e),t};Object.defineProperty(rb,"__esModule",{value:!0});rb.V2ChatStreamRequestCitationMode=void 0;var cyr=lyr($());rb.V2ChatStreamRequestCitationMode=cyr.serialization.enum_(["FAST","ACCURATE","OFF"])});var W_e=b(nb=>{"use strict";var dyr=nb&&nb.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),fyr=nb&&nb.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),pyr=nb&&nb.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&dyr(t,e,r);return fyr(t,e),t};Object.defineProperty(nb,"__esModule",{value:!0});nb.V2ChatRequestCitationMode=void 0;var hyr=pyr($());nb.V2ChatRequestCitationMode=hyr.serialization.enum_(["FAST","ACCURATE","OFF"])});var ML=b(ob=>{"use strict";var myr=ob&&ob.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),gyr=ob&&ob.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),yyr=ob&&ob.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&myr(t,e,r);return gyr(t,e),t};Object.defineProperty(ob,"__esModule",{value:!0});ob.TextContent=void 0;var Tpt=yyr($());ob.TextContent=Tpt.serialization.object({text:Tpt.serialization.string()})});var J_e=b(ib=>{"use strict";var byr=ib&&ib.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),_yr=ib&&ib.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),vyr=ib&&ib.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&byr(t,e,r);return _yr(t,e),t};Object.defineProperty(ib,"__esModule",{value:!0});ib.Content=void 0;var wyr=vyr($()),Syr=ML();ib.Content=wyr.serialization.union("type",{text:Syr.TextContent}).transform({
`)}}}}catch(S){a={error:S}}finally{try{m&&!m.done&&(s=h.return)&&(yield s.call(h))}finally{if(a)throw a.error}}for(let S of g.flush()){let x=(0,_o.parseAWSEvent)(S);if(x){let O=yield(0,_o.mapResponseFromBedrock)(c,u,x);v.push(JSON.stringify(O)+`
`)}}return v.end(),{ok:!0,body:v}}else{let _=yield p.body;return{ok:!0,body:yield(0,_o.mapResponseFromBedrock)(c,u,_)}}}catch(_){throw _}});_o.fetchOverride=wjr});var Mx=b(vZ=>{"use strict";Object.defineProperty(vZ,"__esModule",{value:!0});vZ.CohereEnvironment=void 0;vZ.CohereEnvironment={Production:"https://api.cohere.com"}});var cP=b((Zmt,wZ)=>{(function(e,t,r){typeof wZ<"u"&&wZ.exports?wZ.exports=r():typeof define=="function"&&define.amd?define(r):t[e]=r()})("urljoin",Zmt,function(){function e(t){var r=[];if(t.length===0)return"";if(typeof t[0]!="string")throw new TypeError("Url must be a string. Received "+t[0]);if(t[0].match(/^[^/:]+:\/*$/)&&t.length>1){var n=t.shift();t[0]=n+t[0]}t[0].match(/^file:\/\/\//)?t[0]=t[0].replace(/^([^/:]+):\/*/,"$1:///"):t[0]=t[0].replace(/^([^/:]+):\/*/,"$1://");for(var o=0;o<t.length;o++){var i=t[o];if(typeof i!="string")throw new TypeError("Url must be a string. Received "+i);i!==""&&(o>0&&(i=i.replace(/^[\/]+/,"")),o<t.length-1?i=i.replace(/[\/]+$/,""):i=i.replace(/[\/]+$/,"/"),r.push(i))}var a=r.join("/");a=a.replace(/\/(\?|&|#[^!])/g,"$1");var s=a.split("?");return a=s.shift()+(s.length>0?"?":"")+s.join("&"),a}return function(){var t;return typeof arguments[0]=="object"?t=arguments[0]:t=[].slice.call(arguments),e(t)}})});var tSe=b(xf=>{"use strict";var Sjr=xf&&xf.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),xjr=xf&&xf.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),K2=xf&&xf.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&Sjr(t,e,r);return xjr(t,e),t},SZ=xf&&xf.__awaiter||function(e,t,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(c){try{l(n.next(c))}catch(d){a(d)}}function u(c){try{l(n.throw(c))}catch(d){a(d)}}function l(c){c.done?i(c.value):o(c.value).then(s,u)}l((n=n.apply(e,t||[])).next())})},Cjr=xf&&xf.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(xf,"__esModule",{value:!0});xf.V2=void 0;var Xmt=K2(Mx()),wf=K2($()),Ra=K2(QS()),Sf=K2(Tx()),Qmt=Cjr(cP()),Ix=K2(Wa()),eSe=class{constructor(t={}){this._options=t}chatStream(t,r){var n,o;return SZ(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:wf.fetcher)({url:(0,Qmt.default)((o=yield wf.Supplier.get(this._options.environment))!==null&&o!==void 0?o:Xmt.CohereEnvironment.Production,"v2/chat"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield wf.Supplier.get(this._options.clientName))!=null?yield wf.Supplier.get(this._options.clientName):void 0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.13.0","User-Agent":"cohere-ai/7.13.0","X-Fern-Runtime":wf.RUNTIME.type,"X-Fern-Runtime-Version":wf.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},Sf.V2ChatStreamRequest.jsonOrThrow(t,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0})),{stream:!0}),responseType:"sse",timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:3e5,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(i.ok)return new wf.Stream({stream:i.body,parse:a=>SZ(this,void 0,void 0,function*(){return Sf.StreamedChatResponse2.parseOrThrow(a,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]})}),signal:r?.abortSignal,eventShape:{type:"sse",streamTerminator:"[DONE]"}});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new Ra.BadRequestError(i.error.body);case 401:throw new Ra.
`}});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new he.BadRequestError(i.error.body);case 401:throw new he.UnauthorizedError(i.error.body);case 403:throw new he.ForbiddenError(i.error.body);case 404:throw new he.NotFoundError(i.error.body);case 422:throw new he.UnprocessableEntityError(ze.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new he.TooManyRequestsError(ze.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new he.ClientClosedRequestError(ze.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 500:throw new he.InternalServerError(i.error.body);case 501:throw new he.NotImplementedError(ze.NotImplementedErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 503:throw new he.ServiceUnavailableError(i.error.body);case 504:throw new he.GatewayTimeoutError(ze.GatewayTimeoutErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));default:throw new nr.CohereError({statusCode:i.error.statusCode,body:i.error.body})}switch(i.error.reason){case"non-json":throw new nr.CohereError({statusCode:i.error.statusCode,body:i.error.rawBody});case"timeout":throw new nr.CohereTimeoutError;case"unknown":throw new nr.CohereError({message:i.error.errorMessage})}})}chat(t,r){var n,o;return Mf(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:et.fetcher)({url:(0,dg.default)((o=yield et.Supplier.get(this._options.environment))!==null&&o!==void 0?o:cg.CohereEnvironment.Production,"v1/chat"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield et.Supplier.get(this._options.clientName))!=null?yield et.Supplier.get(this._options.clientName):void 0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.13.0","User-Agent":"cohere-ai/7.13.0","X-Fern-Runtime":et.RUNTIME.type,"X-Fern-Runtime-Version":et.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},ze.ChatRequest.jsonOrThrow(t,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0})),{stream:!1}),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:3e5,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(i.ok)return ze.NonStreamedChatResponse.parseOrThrow(i.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new he.BadRequestError(i.error.body);case 401:throw new he.UnauthorizedError(i.error.body);case 403:throw new he.ForbiddenError(i.error.body);case 404:throw new he.NotFoundError(i.error.body);case 422:throw new he.UnprocessableEntityError(ze.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new he.TooManyRequestsError(ze.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new he.ClientClosedRequestError(ze.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{
`}});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new he.BadRequestError(i.error.body);case 401:throw new he.UnauthorizedError(i.error.body);case 403:throw new he.ForbiddenError(i.error.body);case 404:throw new he.NotFoundError(i.error.body);case 422:throw new he.UnprocessableEntityError(ze.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new he.TooManyRequestsError(ze.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new he.ClientClosedRequestError(ze.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 500:throw new he.InternalServerError(i.error.body);case 501:throw new he.NotImplementedError(ze.NotImplementedErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 503:throw new he.ServiceUnavailableError(i.error.body);case 504:throw new he.GatewayTimeoutError(ze.GatewayTimeoutErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));default:throw new nr.CohereError({statusCode:i.error.statusCode,body:i.error.body})}switch(i.error.reason){case"non-json":throw new nr.CohereError({statusCode:i.error.statusCode,body:i.error.rawBody});case"timeout":throw new nr.CohereTimeoutError;case"unknown":throw new nr.CohereError({message:i.error.errorMessage})}})}generate(t,r){var n,o;return Mf(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:et.fetcher)({url:(0,dg.default)((o=yield et.Supplier.get(this._options.environment))!==null&&o!==void 0?o:cg.CohereEnvironment.Production,"v1/generate"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield et.Supplier.get(this._options.clientName))!=null?yield et.Supplier.get(this._options.clientName):void 0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.13.0","User-Agent":"cohere-ai/7.13.0","X-Fern-Runtime":et.RUNTIME.type,"X-Fern-Runtime-Version":et.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},ze.GenerateRequest.jsonOrThrow(t,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0})),{stream:!1}),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:3e5,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(i.ok)return ze.Generation.parseOrThrow(i.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new he.BadRequestError(i.error.body);case 401:throw new he.UnauthorizedError(i.error.body);case 403:throw new he.ForbiddenError(i.error.body);case 404:throw new he.NotFoundError(i.error.body);case 422:throw new he.UnprocessableEntityError(ze.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new he.TooManyRequestsError(ze.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new he.ClientClosedRequestError(ze.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{u
`).filter(Boolean).reduce((n,o)=>{let[i,a,...s]=o.split(" "),u=Number.parseInt(a,10);return s.forEach((l,c)=>n[l]=u+c),n},{});for(let[n,o]of Object.entries(r)){let i=ggt.default.toByteArray(n);this.rankMap.set(i.join(","),o),this.textMap.set(o,i)}this.specialTokens={...e.special_tokens,...t},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[o,i])=>(n[i]=this.textEncoder.encode(o),n),{})}encode(e,t=[],r="all"){let n=new RegExp(this.patStr,"ug"),o=ySe.specialTokenRegex(Object.keys(this.specialTokens)),i=[],a=new Set(t==="all"?Object.keys(this.specialTokens):t),s=new Set(r==="all"?Object.keys(this.specialTokens).filter(l=>!a.has(l)):r);if(s.size>0){let l=ySe.specialTokenRegex([...s]),c=e.match(l);if(c!=null)throw new Error(`The text contains a special token that is not allowed: ${c[0]}`)}let u=0;for(;;){let l=null,c=u;for(;o.lastIndex=c,l=o.exec(e),!(l==null||a.has(l[0]));)c=l.index+1;let d=l?.index??e.length;for(let p of e.substring(u,d).matchAll(n)){let h=this.textEncoder.encode(p[0]),m=this.rankMap.get(h.join(","));if(m!=null){i.push(m);continue}i.push(...bNr(h,this.rankMap))}if(l==null)break;let f=this.specialTokens[l[0]];i.push(f),u=l.index+l[0].length}return i}decode(e){let t=[],r=0;for(let i=0;i<e.length;++i){let a=e[i],s=this.textMap.get(a)??this.inverseSpecialTokens[a];s!=null&&(t.push(s),r+=s.length)}let n=new Uint8Array(r),o=0;for(let i of t)n.set(i,o),o+=i.length;return this.textDecoder.decode(n)}},RZ=ySe;gNr(RZ,"specialTokenRegex",e=>new RegExp(e.map(t=>_Nr(t)).join("|"),"g"))});var bgt=C(()=>{ygt()});async function _gt(e){return e in DZ||(DZ[e]=vNr.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(t=>t.json()).then(t=>new RZ(t)).catch(t=>{throw delete DZ[e],t})),await DZ[e]}async function vgt(e){return _gt(bSe(e))}var DZ,vNr,_Se=C(()=>{bgt();kD();DZ={},vNr=new Qf({})});function gw(e){return typeof e!="object"||!e?!1:!!("type"in e&&e.type==="function"&&"function"in e&&typeof e.function=="object"&&e.function&&"name"in e.function&&"parameters"in e.function)}var wNr,SNr,QL,eF,a4=C(()=>{mgt();rq();gO();kD();_Se();sf();wNr=e=>e.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":e.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":e.startsWith("gpt-4-32k")?"gpt-4-32k":e.startsWith("gpt-4-")?"gpt-4":e.startsWith("gpt-4o")?"gpt-4o":e;SNr=()=>!1,QL=class extends nn{get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(t){super(t),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.verbose=t.verbose??SNr(),this.callbacks=t.callbacks,this.tags=t.tags??[],this.metadata=t.metadata??{}}},eF=class extends QL{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}constructor({callbacks:t,callbackManager:r,...n}){let{cache:o,...i}=n;super({callbacks:t??r,...i}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_encoding",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof o=="object"?this.cache=o:o?this.cache=AZ.global():this.cache=void 0,this.caller=new Qf(n??{})}async getNumTokens(t){if(typeof t!="string")return 0;let r=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await vgt("modelName"in this?wNr(this.modelName):"gpt2")}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}if(this._encoding)try{r=this._encoding.encode(t).length}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}return r}static _convertInputToPromptValue(t){return typeof t=="string"?new qD(t):Array.isArray(t)?new UD(t.map(Nm)):t}_identifyingParams(){return{}}_getSerializedCacheKeyParameters
${n}`:"";super(`${t}: Status ${o} Content-Type ${i} Body ${a}`),this.rawResponse=r,this.body=n,this.statusCode=o,this.contentType=i,this.name="SDKError"}};Ree.SDKError=NOe});var h3=b(p3=>{"use strict";Object.defineProperty(p3,"__esModule",{value:!0});p3.EventStream=void 0;p3.discardSentinel=Vzr;var d3=10,f3=13,Jwt=new Set([d3,f3]),zzr=[new Uint8Array([f3,d3,f3,d3]),new Uint8Array([f3,f3]),new Uint8Array([d3,d3])],FOe=class{constructor(t){this.stream=t.stream,this.decoder=t.decoder}async*[Symbol.asyncIterator](){let t=this.stream.getReader(),r=new Uint8Array([]),n=0;try{for(;;){let{done:o,value:i}=await t.read();if(o)break;let a=new Uint8Array(r.length+i.length);a.set(r),a.set(i,r.length),r=a;for(let s=n;s<r.length;s++){let u=Gwt(r,s);if(u==null)continue;let l=r.slice(n,s);n=s+u.length;let c=kOe(l,this.decoder);c!=null&&(yield c)}n>0&&(r=r.slice(n),n=0)}if(r.length>0){let o=kOe(r,this.decoder);o!=null&&(yield o)}}catch(o){if(o instanceof Error&&o.name==="AbortError")return;throw o}finally{t.releaseLock()}}};p3.EventStream=FOe;function Gwt(e,t){let r=e[t],n=e[t+1];if(r==null||n==null||!Jwt.has(r)||!Jwt.has(n))return null;for(let o of zzr){let i=Hzr(t,e,o);if(i!=null)return i}return null}function Hzr(e,t,r){if(r.length>t.length-e)return null;for(let n=0;n<r.length;n++)if(t[e+n]!==r[n])return null;return r}function kOe(e,t){if(!e.length)return null;let o=new TextDecoder().decode(e).split(/\r?\n|\r/g),i=!1,a={};for(let s of o){if(!s)continue;let u=s.indexOf(":");if(u===0)continue;let l=u>0?s.substring(0,u):"",c=u>0?s.substring(u+1):"";switch(c.charAt(0)===" "&&(c=c.substring(1)),l){case"event":{i=!0,a.event=c;break}case"data":{i=!0,a.data??(a.data=""),a.data+=c+`
`;break}case"id":{i=!0,a.id=c;break}case"retry":{let d=parseInt(c,10);Number.isNaN(d)||(i=!0,a.retry=d);break}}}return i?(a.data!=null&&(a.data=a.data.slice(0,-1)),t(a)):null}function Vzr(e,t){return new ReadableStream({async start(r){let n=new Uint8Array([]),o=0,i=!1,a=!1,s=e.getReader();try{for(;!i;){let u=await s.read(),l=u.value;if(i=i||u.done,a||typeof l>"u")continue;let c=new Uint8Array(n.length+l.length);c.set(n),c.set(l,n.length),n=c;for(let d=o;d<n.length;d++){let f=Gwt(n,d);if(f==null)continue;let p=o,h=n.slice(p,d);o=d+f.length,kOe(h,Wzr)?.data===t?(r.enqueue(n.slice(0,p)),a=!0):(r.enqueue(n.slice(0,o)),n=n.slice(o),o=0)}}}catch(u){r.error(u)}finally{r.close(),s.releaseLock()}}})}function Wzr(e){return e}});var qOe=b(Eg=>{"use strict";var Jzr=Eg&&Eg.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),Gzr=Eg&&Eg.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Kzr=Eg&&Eg.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&Jzr(t,e,r);return Gzr(t,e),t};Object.defineProperty(Eg,"__esModule",{value:!0});Eg.SDKValidationError=void 0;Eg.formatZodError=$Oe;var Yzr=Kzr(me()),BOe=class extends Error{constructor(t,r,n){super(`${t}: ${r}`),this.name="SDKValidationError",this.cause=r,this.rawValue=n,this.rawMessage=t}pretty(){return this.cause instanceof Yzr.ZodError?`${this.rawMessage}
${$Oe(this.cause)}`:this.toString()}};Eg.SDKValidationError=BOe;function $Oe(e,t=0){let r=" ".repeat(t);r=t>0?`\u2502${r}`:r,r+=" ".repeat(t);let n="",o=s=>n+=`
${r}${s}`,i=e.issues.length,a=i===1?`${i} issue found`:`${i} issues found`;i&&o(`\u250C ${a}:`);for(let s of e.issues){let u=s.path.join(".");switch(u=u?`<root>.${u}`:"<root>",o(`\u2502 \u2022 [${u}]: ${s.message} (${s.code})`),s.code){case"invalid_literal":case"invalid_type":{o(`\u2502 Want: ${s.expected}`),o(`\u2502 Got: ${s.received}`);break}case"unrecognized_keys":{o(`\u2502 Keys: ${s.keys.join(", ")}`);break}case"invalid_enum_value":{o(`\u2502 Allowed: ${s.options.join(", ")}`),o(`\u2502 Got: ${s.received}`);break}case"invalid_union_discriminator":{o(`\u2502 Allowed: ${s.options.join(", ")}`);break}case"invalid_union":{let l=s.unionErrors.length;o(`\u2502 \u2716\uFE0E Attemped to deserialize into one of ${l} union members:`),s.unionErrors.forEach((c,d)=>{o(`\u2502 \u2716\uFE0E Member ${d+1} of ${l}`),o(`${$Oe(c,t+1)}`)})}}}return e.issues.length&&o("\u2514\u2500*"),n.slice(1)}});var ce=b(m3=>{"use strict";Object.defineProperty(m3,"__esModule",{value:!0});m3.parse=Xzr;m3.safeParse=Qzr;m3.collectExtraKeys=e2r;var Zzr=me(),Ywt=qOe(),Kwt=Wh();function Xzr(e,t,r){try{return t(e)}catch(n){throw n instanceof Zzr.ZodError?new Ywt.SDKValidationError(r,n,e):n}}function Qzr(e,t,r){try{return(0,Kwt.OK)(t(e))}catch(n){return(0,Kwt.ERR)(new Ywt.SDKValidationError(r,n,e))}}function e2r(e,t,r){return e.transform(n=>{let o={},{shape:i}=e;for(let[a]of Object.entries(n)){if(a in i)continue;let s=n[a];typeof s>"u"||(o[a]=s,delete n[a])}return r&&Object.keys(o).length===0?n:{...n,[t]:o}})}});var wo=b(Cl=>{"use strict";Object.defineProperty(Cl,"__esModule",{value:!0});Cl.jsonErr=n2r;Cl.json=o2r;Cl.textErr=i2r;Cl.text=a2r;Cl.bytesErr=s2r;Cl.bytes=u2r;Cl.streamErr=l2r;Cl.stream=c2r;Cl.sseErr=d2r;Cl.sse=f2r;Cl.nilErr=p2r;Cl.nil=h2r;Cl.fail=m2r;Cl.match=g2r;Cl.unpackHeaders=Dee;Cl.discardResponseBody=tSt;var Zwt=LOe(),t2r=h3(),Xwt=u3(),Qwt=POe(),eSt=ce(),r2r={json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function n2r(e,t,r){return{...r,err:!0,enc:"json",codes:e,schema:t}}function o2r(e,t,r){return{...r,enc:"json",codes:e,schema:t}}function i2r(e,t,r){return{...r,err:!0,enc:"text",codes:e,schema:t}}function a2r(e,t,r){return{...r,enc:"text",codes:e,schema:t}}function s2r(e,t,r){return{...r,err:!0,enc:"bytes",codes:e,schema:t}}function u2r(e,t,r){return{...r,enc:"bytes",codes:e,schema:t}}function l2r(e,t,r){return{...r,err:!0,enc:"stream",codes:e,schema:t}}function c2r(e,t,r){return{...r,enc:"stream",codes:e,schema:t}}function d2r(e,t,r){return{...r,err:!0,enc:"sse",codes:e,schema:t}}function f2r(e,t,r){return{...r,enc:"sse",codes:e,schema:t}}function p2r(e,t,r){return{...r,err:!0,enc:"nil",codes:e,schema:t}}function h2r(e,t,r){return{...r,enc:"nil",codes:e,schema:t}}function m2r(e){return{enc:"fail",codes:e}}function g2r(...e){return async function(r,n){let o,i;for(let l of e){let{codes:c}=l,d="ctype"in l?l.ctype:r2r[l.enc];if(d&&(0,Xwt.matchResponse)(r,c,d)){i=l;break}else if(!d&&(0,Xwt.matchStatusCode)(r,c)){i=l;break}}if(!i){let l=await r.text();return[{ok:!1,error:new Zwt.SDKError("Unexpected API response status or content-type",r,l)},l]}let a=i.enc;switch(a){case"json":o=await r.json();break;case"bytes":o=new Uint8Array(await r.arrayBuffer());break;case"stream":o=r.body;break;case"text":o=await r.text();break;case"sse":o=r.body&&i.sseSentinel?(0,t2r.discardSentinel)(r.body,i.sseSentinel):r.body;break;case"nil":o=await tSt(r);break;case"fail":o=await r.text();break;default:throw new Error(`Unsupported response type: ${a}`)}if(i.enc==="fail")return[{ok:!1,error:new Zwt.SDKError("API error occurred",r,typeof o=="string"?o:"")},o];let s=i.key||n?.resultKey,u;if("err"in i?u={...n?.extraFields,...i.hdrs?{Headers:Dee(r.headers)}:null,...(0,Qwt.isPlainObject)(o)?o:null}:s?u={...n?.extraFields,...i.hdrs?{Headers:Dee(r.headers)}:null,[s]:o}:i.hdrs?u={...n?.extraFields,...i.hdrs?{Headers:Dee(r.headers)}:null,...(0,Qwt.isPlainObject)(o)?o:null}:u=o,"err"in i){let l=(0,eSt.safeParse)(u,c=>i.schema.parse(c),"Respon
]))`;continue}else if(n[u]==="$"){o+=`($|(?=[\r
]))`;continue}}if(r.s&&n[u]==="."){o+=a?`${n[u]}\r
`:`[${n[u]}\r
]`;continue}o+=n[u],n[u]==="\\"?i=!0:a&&n[u]==="]"?a=!1:!a&&n[u]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return o}});var Pre=b(Ere=>{"use strict";Object.defineProperty(Ere,"__esModule",{value:!0});Ere.parseRecordDef=void 0;var T3=me(),NMt=Pu(),$Yr=Ore(),qYr=yre();function UYr(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===T3.ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:(0,NMt.parseDef)(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:(0,NMt.parseDef)(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??{}};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===T3.ZodFirstPartyTypeKind.ZodString&&e.keyType._def.checks?.length){let{type:n,...o}=(0,$Yr.parseStringDef)(e.keyType._def,t);return{...r,propertyNames:o}}else{if(e.keyType?._def.typeName===T3.ZodFirstPartyTypeKind.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===T3.ZodFirstPartyTypeKind.ZodBranded&&e.keyType._def.type._def.typeName===T3.ZodFirstPartyTypeKind.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...o}=(0,qYr.parseBrandedDef)(e.keyType._def,t);return{...r,propertyNames:o}}}return r}Ere.parseRecordDef=UYr});var VEe=b(Tre=>{"use strict";Object.defineProperty(Tre,"__esModule",{value:!0});Tre.parseMapDef=void 0;var LMt=Pu(),zYr=Pre();function HYr(e,t){if(t.mapStrategy==="record")return(0,zYr.parseRecordDef)(e,t);let r=(0,LMt.parseDef)(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},n=(0,LMt.parseDef)(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}Tre.parseMapDef=HYr});var WEe=b(Mre=>{"use strict";Object.defineProperty(Mre,"__esModule",{value:!0});Mre.parseNativeEnumDef=void 0;function VYr(e){let t=e.values,n=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}Mre.parseNativeEnumDef=VYr});var JEe=b(Ire=>{"use strict";Object.defineProperty(Ire,"__esModule",{value:!0});Ire.parseNeverDef=void 0;function WYr(){return{not:{}}}Ire.parseNeverDef=WYr});var GEe=b(Are=>{"use strict";Object.defineProperty(Are,"__esModule",{value:!0});Are.parseNullDef=void 0;function JYr(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}Are.parseNullDef=JYr});var Rre=b(rT=>{"use strict";Object.defineProperty(rT,"__esModule",{value:!0});rT.parseUnionDef=rT.primitiveMappings=void 0;var GYr=Pu();rT.primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function KYr(e,t){if(t.target==="openApi3")return FMt(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in rT.primitiveMappings&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=rT.primitiveMappings[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((i,a,s)=>s.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(n=>n._
`);var ki={},nJt=0;function KM(e,t){let r=`atom${++nJt}`,n={toString(){return(ki.env?ki.env.MODE:void 0)!=="production"&&this.debugLabel?r+":"+this.debugLabel:r}};return typeof e=="function"?n.read=e:(n.init=e,n.read=oJt,n.write=iJt),t&&(n.write=t),n}function oJt(e){return e(this)}function iJt(e,t,r){return t(this,typeof r=="function"?r(e(this)):r)}var QFe=(e,t)=>e.unstable_is?e.unstable_is(t):t===e,Wue=e=>"init"in e,Jue=e=>!!e.write,JV=new WeakMap,Kue=e=>{var t;return Yue(e)&&!((t=JV.get(e))!=null&&t[1])},aJt=(e,t)=>{let r=JV.get(e);if(r)r[1]=!0,r[0].forEach(n=>n(t));else if((ki.env?ki.env.MODE:void 0)!=="production")throw new Error("[Bug] cancelable promise not found")},sJt=e=>{if(JV.has(e))return;let t=[new Set,!1];JV.set(e,t);let r=()=>{t[1]=!0};e.then(r,r),e.onCancel=n=>{t[0].add(n)}},Yue=e=>typeof e?.then=="function",eke=e=>"v"in e||"e"in e,WV=e=>{if("e"in e)throw e.e;if((ki.env?ki.env.MODE:void 0)!=="production"&&!("v"in e))throw new Error("[Bug] atom state is not initialized");return e.v},nke=(e,t,r)=>{r.p.has(e)||(r.p.add(e),t.then(()=>{r.p.delete(e)},()=>{r.p.delete(e)}))},tke=(e,t,r,n,o)=>{var i;if((ki.env?ki.env.MODE:void 0)!=="production"&&n===t)throw new Error("[Bug] atom cannot depend on itself");r.d.set(n,o.n),Kue(r.v)&&nke(t,r.v,o),(i=o.m)==null||i.t.add(t),e&&uJt(e,n,t)},YD=()=>[new Map,new Map,new Set],Gue=(e,t,r)=>{e[0].has(t)||e[0].set(t,new Set),e[1].set(t,r)},uJt=(e,t,r)=>{let n=e[0].get(t);n&&n.add(r)},lJt=(e,t)=>e[0].get(t),rke=(e,t)=>{e[2].add(t)},OO=e=>{let t,r=!1,n=o=>{try{o()}catch(i){r||(t=i,r=!0)}};for(;e[1].size||e[2].size;){e[0].clear();let o=new Set(e[1].values());e[1].clear();let i=new Set(e[2]);e[2].clear(),o.forEach(a=>{var s;return(s=a.m)==null?void 0:s.l.forEach(n)}),i.forEach(n)}if(r)throw t},oke=(...[e,t,r,n])=>{let o;(ki.env?ki.env.MODE:void 0)!=="production"&&(o=new Set);let i=(S,x,O)=>{let T="v"in x,E=x.v,M=Kue(x.v)?x.v:null;if(Yue(O)){sJt(O);for(let A of x.d.keys())nke(S,O,e(A));x.v=O,delete x.e}else x.v=O,delete x.e;(!T||!Object.is(E,x.v))&&(++x.n,M&&aJt(M,O))},a=(S,x,O)=>{var T;let E=e(x);if(eke(E)&&(E.m&&!O?.has(x)||Array.from(E.d).every(([k,L])=>a(S,k,O).n===L)))return E;E.d.clear();let M=!0,A=k=>{if(QFe(x,k)){let q=e(k);if(!eke(q))if(Wue(k))i(k,q,k.init);else throw new Error("no atom init");return WV(q)}let L=a(S,k,O);try{return WV(L)}finally{if(M)tke(S,x,E,k,L);else{let q=YD();tke(q,x,E,k,L),p(q,x,E),OO(q)}}},j,N,F={get signal(){return j||(j=new AbortController),j.signal},get setSelf(){return(ki.env?ki.env.MODE:void 0)!=="production"&&!Jue(x)&&console.warn("setSelf function cannot be used with read-only atom"),!N&&Jue(x)&&(N=(...k)=>{if((ki.env?ki.env.MODE:void 0)!=="production"&&M&&console.warn("setSelf function cannot be called in sync"),!M)return f(x,...k)}),N}};try{let k=t(x,A,F);if(i(x,E,k),Yue(k)){(T=k.onCancel)==null||T.call(k,()=>j?.abort());let L=()=>{if(E.m){let q=YD();p(q,x,E),OO(q)}};k.then(L,L)}return E}catch(k){return delete E.v,E.e=k,++E.n,E}finally{M=!1}},s=S=>WV(a(void 0,S)),u=(S,x,O)=>{var T,E;let M=new Map;for(let A of((T=O.m)==null?void 0:T.t)||[])M.set(A,e(A));for(let A of O.p)M.set(A,e(A));return(E=lJt(S,x))==null||E.forEach(A=>{M.set(A,e(A))}),M};function l(S,x,O){let T=[],E=new Set,M=new Set,A=[[x,O]];for(;A.length>0;){let[j,N]=A[A.length-1];if(M.has(j)){A.pop();continue}if(E.has(j)){T.push([j,N,N.n]),M.add(j),A.pop();continue}E.add(j);for(let[F,k]of u(S,j,N))j!==F&&!E.has(F)&&A.push([F,k])}return[T,M]}let c=(S,x,O)=>{let[T,E]=l(S,x,O),M=new Set([x]);for(let A=T.length-1;A>=0;--A){let[j,N,F]=T[A],k=!1;for(let L of N.d.keys())if(L!==j&&M.has(L)){k=!0;break}k&&(a(S,j,E),p(S,j,N),F!==N.n&&(Gue(S,j,N),M.add(j))),E.delete(j)}},d=(S,x,...O)=>{let T=!0,E=A=>WV(a(S,A)),M=(A,...j)=>{let N=e(A);try{if(QFe(x,A)){if(!Wue(A))throw new Error("atom not writable");let F=N.n,k=j[0];i(A,N,k),p(S,A,N),F!==N.n&&(Gue(S,A,N),c(S,A,N));return}else return d(S,A,...j)}finally{T||OO(S)}};try{return r(x,E,M,...O)}finally{T=!1}},f=(S,...x)=>{let O=YD();try{return d(O,S,...x)}finally{OO(O)}},p=(S,x,O)=>{if(O.m&&!Kue(O.v)){for(let T of O.d.keys())O.m.d.has(T)||(h(S,T,e(T)).t.
${e}`:ale}function TJt(e){return e.activeModels=wke(e.activeModels,PO),e.activeEmbeddingModels=wke(e.activeEmbeddingModels,pq),e}function Dr(e){return`${e.name}|${e.provider}`}function wke(e,t){let r=new Map;return t.filter(n=>n.core).forEach(n=>{r.set(Dr(n),{...n})}),e.forEach(n=>{let o=Dr(n),i=r.get(o);if(i){let a=t.find(s=>s.name===n.name&&s.provider===n.provider);a?r.set(o,{...a,...n,isBuiltIn:!0,believerExclusive:a.believerExclusive}):r.set(o,{...n,isBuiltIn:i.isBuiltIn})}else r.set(o,n)}),Array.from(r.values())}function br(...e){pe().debug&&console.log(...e)}function Ur(...e){pe().debug&&console.error(...e)}var Sle=B(Cke()),rp=require("obsidian"),_le=B(Td()),vle={INVALID_LICENSE_KEY_USER:"Invalid Copilot Plus license key. Please check your license key in settings.",UNKNOWN_ERROR:"An unknown error occurred",REQUEST_FAILED:e=>`Request failed, status ${e}`};function Hke(e){let t=e?.detail||{};return{status:t.status,message:t.message||e?.message,reason:t.reason}}function sGt(e){let t=Hke(e);return t.reason==="Invalid license key"||e?.message==="Invalid license key"||e?.message?.includes("status 403")||t.status===403}function Vke(e){let t=Hke(e);return sGt(e)?vle.INVALID_LICENSE_KEY_USER:t.message||(t.reason?`Error: ${t.reason}`:vle.UNKNOWN_ERROR)}var xle=(e,t)=>{let r=e.getMarkdownFiles();if(t==="/")return r;let n=t.toLowerCase().replace(/^\/|\/$/g,"");return r.filter(o=>{let a=o.path.toLowerCase().split("/"),s=n.split("/"),u=0;for(let l of s){for(;u<a.length&&a[u]!==l;)u++;if(u>=a.length)return!1}return!0})};function nj(e){return e.replace(/^#/,"").trim().toLowerCase()}function mq(e,t=!0){let r=app.metadataCache.getFileCache(e),n=r?.frontmatter?.tags,o=new Set;if(!t){let i=r?.tags?.map(a=>a.tag);i&&i.forEach(a=>o.add(nj(a)))}return n&&(Array.isArray(n)?n.forEach(i=>{typeof i=="string"&&o.add(nj(i))}):typeof n=="string"&&o.add(nj(n))),Array.from(o)}function Wke(e,t,r){if(t.length===0)return[];t=t.map(i=>nj(i));let n=r&&r.length>0?r:xle(e,"/"),o=[];for(let i of n){let a=mq(i);t.some(s=>a.includes(s))&&o.push(i)}return o}var uGt=e=>e.last.bound.modelName||e.last.bound.model,lGt=e=>e.last.bound.retriever!==void 0,Jke=e=>uGt(e)||lGt(e);var ll=(e,t="local")=>{let r=(0,Sle.default)(e);return t==="utc"&&r.utc(),{fileName:r.format("YYYYMMDD_HHmmss"),display:r.format("YYYY/MM/DD HH:mm:ss"),epoch:r.valueOf()}};function Cle(e){let t=(0,Sle.default)(e,"YYYY/MM/DD HH:mm:ss");return t.isValid()?{fileName:t.format("YYYYMMDD_HHmmss"),display:t.format("YYYY/MM/DD HH:mm:ss"),epoch:t.valueOf()}:ll(new Date)}async function oj(e,t){return e.extension!="md"?null:await t.cachedRead(e)}function r5(e){return e.basename}function Gke(e,t){return!e||!t?!1:e.includes(wle)&&t.includes(wle)||e==="small"&&t==="cohereai"||e==="cohereai"&&t==="small"?!0:e===t}function ij(e){let t=[],{history:r}=e;for(let n=0;n<r.length;n+=2){let o=r[n]?.content||"",i=r[n+1]?.content||"";t.push([o,i])}return t}function ly(e,t){let r=/\[\[(.*?)\]\]/g,n=e.match(r),o=new Map;return n&&n.forEach(i=>{let a=i.slice(2,-2),s=t.getAbstractFileByPath(a);if(s instanceof rp.TFile)o.set(s.path,s);else{let l=t.getMarkdownFiles().filter(c=>c.basename===a);l.length>0&&(Ole(a,t)?o.set(l[0].path,l[0]):console.warn(`Found multiple files with title "${a}". Expected a full path for duplicate titles.`))}}),Array.from(o.values())}function Ole(e,t){return t.getMarkdownFiles().filter(n=>n.basename===e).length===1}function Kke(e){return e=e.trim(),e.startsWith("[[")&&e.endsWith("]]")?`${e.slice(2,-2).trim()}.md`:e}function Yke(e){let t=new Set;return e.forEach(r=>{r.metadata?.title&&t.add(r.metadata?.title)}),Array.from(t)}var Zke=/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|shorts\/)|youtu\.be\/)([^\s&]+)/;function Xke(e){return Zke.test(e)}function gq(e){let t=e.match(Zke);return t?t[0]:null}var DS=class{static async isImageUrl(t){try{let r=new URL(t);if(this.IMAGE_EXTENSIONS.some(a=>r.pathname.toLowerCase().endsWith(a)))return!0;try{if((await kl(t,{method:"HEAD",headers:{}})).headers.get("content-type")?.startsWith("image/"))return!0}catch(a){console.debug("Error checking content
${e?.cause?"more message: "+e.cause.message:""}
${t?e.stack:""}`:JSON.stringify(e)}function Ele(e,t){let r={...e};return t.forEach(n=>{delete r[n]}),r}function n5(e,t){let[r,n]=e.split("|"),o=t.find(i=>i.name===r&&i.provider===n);if(!o)throw new Error(`No model configuration found for: ${e}`);return o}function eI(e){let t=i5[e];return{...t,label:t.label||e}}function uh(e,t){let r=i5[e]?.label||e;return r+(t?.believerExclusive&&r==="Copilot Plus"?"(Believer)":"")}async function yq(e,t=!1){let r=app.workspace.getMostRecentLeaf();if(!r){new rp.Notice("No active leaf found.");return}if(r.view instanceof rp.MarkdownView||(r=app.workspace.getLeaf(!1),await r.setViewState({type:"markdown",state:r.view.getState()})),!(r.view instanceof rp.MarkdownView)){new rp.Notice("Failed to open a markdown view.");return}let n=r.view.editor,o=n.getCursor("from"),i=n.getCursor("to");t?n.replaceRange(e,o,i):n.replaceRange(e,i),new rp.Notice("Message inserted into the active note.")}function Qke(e,t){let r;return(...n)=>{clearTimeout(r),r=setTimeout(()=>e(...n),t)}}function eBe(e,t){let r=e.split(".").map(Number),n=t.split(".").map(Number);for(let o=0;o<3;o++){if(r[o]>n[o])return!0;if(r[o]<n[o])return!1}return!1}async function tBe(){try{return{version:(await(0,rp.requestUrl)({url:"https://api.github.com/repos/logancyang/obsidian-copilot/releases/latest",method:"GET"})).json.tag_name.replace("v",""),error:null}}catch(e){return{version:null,error:e instanceof Error?e.message:"Failed to check for updates"}}}function tI(e){if(typeof e=="string")return e.startsWith("o1")||e.startsWith("o3");let t=e.modelName||e.model||"";return t.startsWith("o1")||t.startsWith("o3")}function rBe(e,t="system"){return tI(e)?"human":t}function Ple(){let e=["3rd party (openai-format)","ollama","lm-studio","azure openai","copilot-plus","copilot-plus-jina"];return Object.entries(i5).filter(([t])=>!e.includes(t)).map(([t])=>t)}function o5(e,t){let r=!!Ple().find(i=>i===e.provider),n=IO[e.provider],o=!e.apiKey&&!t[n];return r&&o?{hasApiKey:!1,errorNotice:`Please configure API Key for ${e.name} in settings first.
Path: Settings > copilot plugin > Basic Tab > Set Keys`}:{hasApiKey:!0}}function aj(e){return e.replace(/<think>[\s\S]*?<\/think>/g,"").trim()}var sj=class sj{static createNewLLMChain(t){let{llm:r,memory:n,prompt:o,abortController:i}=t,a=r.bind({signal:i?.signal}),s=Ha.from([{input:u=>u.input,memory:()=>n.loadMemoryVariables({})},{input:u=>u.input,history:u=>u.memory.history},o,a]);return sj.instances.set("llm_chain",s),console.log("New LLM chain created."),s}static getLLMChainFromMap(t){let r=sj.instances.get("llm_chain");return r||(r=sj.createNewLLMChain(t)),r}static createConversationalRetrievalChain(t,r,n){let{llm:o,retriever:i,systemMessage:a}=t,u=Ed.fromTemplate(`Given the following conversation and a follow up question,
summarize the conversation as context and keep the follow up question unchanged, in its original language.
If the follow up question is unrelated to its preceding messages, return this follow up question directly.
If it is related, then combine the summary and the follow up question to construct a standalone question.
Make sure to keep any [[]] wrapped note titles in the question unchanged.
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
Chat History:
{chat_history}
Follow Up Input: {question}
Standalone question:`),c=Ed.fromTemplate(`{system_message}
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
Answer the question with as detailed as possible based only on the following context:
{context}
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
Question: {question}
`),d=_=>_.map(v=>`Human: ${v[0]}
Assistant: ${v[1]}`).join(`
`),f=Ha.from([{question:_=>(n&&console.log("Input Question: ",_.question),_.question),chat_history:_=>{let g=d(_.chat_history);return n&&console.log("Formatted Chat History: ",g),g}},u,o,new UV,_=>{let g=aj(_);return n&&console.log("Standalone Question: ",g),g}]),p=async _=>(r(_),Vue(_)),h=Ha.from([{context:i.pipe(p),question:new Fi,system_message:()=>a},c,o]);return f.pipe(h)}};sj.instances=new Map;var Tle=sj,a5=Tle;var cf="{copilot-selection}",Mle=50,uj=[{name:"Fix grammar and spelling",prompt:`<instruction>Fix the grammar and spelling of the text below. Preserve all formatting, line breaks, and special characters. Do not add or remove any content. Return only the corrected text.</instruction>
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
<text>${cf}</text>`,showInContextMenu:!0},{name:"Translate to Chinese",prompt:`<instruction>Translate the text below into Chinese:
1. Preserve the meaning and tone
2. Maintain appropriate cultural context
3. Keep formatting and structure
Return only the translated text.</instruction>
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
<text>${cf}</text>`,showInContextMenu:!0},{name:"Summarize",prompt:`<instruction>Create a bullet-point summary of the text below. Each bullet point should capture a key point. Return only the bullet-point summary.</instruction>
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
<text>${cf}</text>`,showInContextMenu:!0},{name:"Simplify",prompt:`<instruction>Simplify the text below 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.</instruction>
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
<text>{copilot-selection}</text>`,showInContextMenu:!0},{name:"Emojify",prompt:`<instruction>Add relevant emojis to enhance the text below. Follow these rules:
1. Insert emojis at natural breaks in the text
2. Never place two emojis next to each other
3. Keep all original text unchanged
4. Choose emojis that match the context and tone
Return only the emojified text.</instruction>
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
<text>{copilot-selection}</text>`,showInContextMenu:!0},{name:"Make shorter",prompt:`<instruction>Reduce the text below to half its length while preserving these elements:
1. Main ideas and key points
2. Essential details
3. Original tone and style
Return only the shortened text.</instruction>
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
<text>${cf}</text>`,showInContextMenu:!0},{name:"Make longer",prompt:`<instruction>Expand the text below to twice its length by:
1. Adding relevant details and examples
2. Elaborating on key points
3. Maintaining the original tone and style
Return only the expanded text.</instruction>
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
<text>${cf}</text>`,showInContextMenu:!0},{name:"Generate table of contents",prompt:`<instruction>Generate a hierarchical table of contents for the text below. Use appropriate heading levels (H1, H2, H3, etc.). Include page numbers if present. Return only the table of contents.</instruction>
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
<text>${cf}</text>`,showInContextMenu:!1},{name:"Generate glossary",prompt:`<instruction>Create a glossary of important terms, concepts, and phrases from the text below. Format each entry as "Term: Definition". Sort entries alphabetically. Return only the glossary.</instruction>
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
<text>{copilot-selection}</text>`,showInContextMenu:!1},{name:"Remove URLs",prompt:`<instruction>Remove all URLs from the text below. Preserve all other content and formatting. URLs may be in various formats (http, https, www). Return only the text with URLs removed.</instruction>
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
<text>${cf}</text>`,showInContextMenu:!1},{name:"Rewrite as tweet",prompt:`<instruction>Rewrite the text below as a single tweet with these requirements:
1. Maximum 280 characters
2. Use concise, impactful language
3. Maintain the core message
Return only the tweet text.</instruction>
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
<text>${cf}</text>`,showInContextMenu:!1},{name:"Rewrite as tweet thread",prompt:`<instruction>Convert the text below into a Twitter thread following these rules:
1. Each tweet must be under 240 characters
2. Start with "THREAD START" on its own line
3. Separate tweets with "
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
---
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
"
4. End with "THREAD END" on its own line
5. Make content engaging and clear
Return only the formatted thread.</instruction>
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
<text>${cf}</text>`,showInContextMenu:!1},{name:"Explain like I am 5",prompt:`<instruction>Explain the text below in simple terms that a 5-year-old would understand:
1. Use basic vocabulary
2. Include simple analogies
3. Break down complex concepts
Return only the simplified explanation.</instruction>
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
<text>${cf}</text>`,showInContextMenu:!1},{name:"Rewrite as press release",prompt:`<instruction>Transform the text below into a professional press release:
1. Use formal, journalistic style
2. Include headline and dateline
3. Follow inverted pyramid structure
Return only the press release format.</instruction>
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
<text>${cf}</text>`,showInContextMenu:!1}];var nI="https://api.brevilabs.com/v1",cl="copilot-chat-view",Uo="user",cy="ai",ale=`You are Obsidian Copilot, a helpful assistant that integrates AI to Obsidian note-taking.
1. Never mention that you do not have access to something. Always rely on the user provided context.
2. Always answer to the best of your knowledge. If you are unsure about something, say so and ask the user to provide more context.
3. If the user mentions "note", it most likely means an Obsidian note in the vault, not the generic meaning of a note.
4. If the user mentions "@vault", it means the user wants you to search the Obsidian vault for information relevant to the query. The search results will be provided to you in the context along with the user query, read it carefully and answer the question based on the information provided. If there's no relevant information in the vault, just say so.
5. If the user mentions any other tool with the @ symbol, check the context for their results. If nothing is found, just ignore the @ symbol in the query.
6. Always use $'s instead of \\[ etc. for LaTeX equations.
7. When showing note titles, use [[title]] format and do not wrap them in \` \`.
8. When showing **Obsidian internal** image links, use ![[link]] format and do not wrap them in \` \`.
9. When showing **web** image links, use ![link](url) format and do not wrap them in \` \`.
10. Always respond in the language of the user's query.
11. Do NOT mention the additional context provided such as getCurrentTime and getTimeRangeMs if it's irrelevant to the user message.`,s5=`Copilot index does not exist. Please index your vault first!
1. Set a working embedding model in QA settings. If it's not a local model, don't forget to set the API key.
2. Click 'Refresh Index for Vault' and wait for indexing to complete. If you encounter the rate limiting error, please turn your request per second down in QA setting.`,nBe=6e3,Ile=.4,oBe=.4,Ale=15,Rle=448e3,jS={DEFAULT:"",READING_FILES:"Reading files",SEARCHING_WEB:"Searching the web",READING_FILE_TREE:"Reading file tree"},AO={SETTINGS:"settings",EXPIRED_MODAL:"expired_modal",CHAT_MODE_SELECT:"chat_mode_select",MODE_SELECT_TOOLTIP:"mode_select_tooltip"};var rI=(f=>(f.OPENAI="openai",f.AZURE_OPENAI="azure openai",f.ANTHROPIC="anthropic",f.COHEREAI="cohereai",f.GOOGLE="google",f.OPENROUTERAI="openrouterai",f.GROQ="groq",f.OLLAMA="ollama",f.LM_STUDIO="lm-studio",f.OPENAI_FORMAT="3rd party (openai-format)",f.COPILOT_PLUS="copilot-plus",f.MISTRAL="mistralai",f))(rI||{});var RO={reasoning:"This model supports general reasoning tasks.",vision:"This model supports image inputs.",websearch:"This model can access the internet."},PO=[{name:"copilot-plus-flash",provider:"copilot-plus",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"gpt-4o",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"gpt-4o-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"o1-mini",provider:"openai",enabled:!0,isBuiltIn:!0,capabilities:["reasoning"]},{name:"o3-mini",provider:"openai",enabled:!0,isBuiltIn:!0,capabilities:["reasoning"]},{name:"claude-3-5-sonnet-latest",provider:"anthropic",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"claude-3-5-haiku-latest",provider:"anthropic",enabled:!0,isBuiltIn:!0},{name:"command-r",provider:"cohereai",enabled:!0,isBuiltIn:!0},{name:"command-r-plus",provider:"cohereai",enabled:!0,isBuiltIn:!0},{name:"gemini-2.0-pro-exp",provider:"google",enabled:!0,isBuiltIn:!0,capabilities:["vision"]},{name:"gemini-2.0-flash",provider:"google",enabled:!0,isBuiltIn:!0,capabilities:["vision"]},{name:"azure-openai",provider:"azure openai",enabled:!0,isBuiltIn:!0}],TO=(l=>(l.OPENAI="openai",l.COHEREAI="cohereai",l.GOOGLE="google",l.AZURE_OPENAI="azure openai",l.OLLAMA="ollama",l.LM_STUDIO="lm-studio",l.OPENAI_FORMAT="3rd party (openai-format)",l.COPILOT_PLUS="copilot-plus",l.COPILOT_PLUS_JINA="copilot-plus-jina",l))(TO||{});var pq=[{name:"copilot-plus-small",provider:"copilot-plus",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0},{name:"copilot-plus-large",provider:"copilot-plus-jina",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,believerExclusive:!0,dimensions:1024},{name:"copilot-plus-multilingual",provider:"copilot-plus-jina",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,dimensions:512},{name:"text-embedding-3-small",provider:"openai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0},{name:"text-embedding-3-large",provider:"openai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"embed-multilingual-light-v3.0",provider:"cohereai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"text-embedding-004",provider:"google",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"azure-openai",provider:"azure openai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0}],wle="nomic-embed-text",i5={openai:{label:"OpenAI",host:"https://api.openai.com",keyManagementURL:"https://platform.openai.com/api-keys",testModel:"gpt-4o"},"azure openai":{label:"Azure OpenAI",host:"",keyManagementURL:"",testModel:"azure-openai"},anthropic:{label:"Anthropic",host:"https://api.anthropic.com/",keyManagementURL:"https://console.anthropic.com/settings/keys",testModel:"claude-3-5-sonnet-latest"},cohereai:{label:"Cohere",host:"https://api.cohere.com",keyManagementURL:"https://dashboard.cohere.ai/api-keys",testModel:"command-r"},google:{label:"Gemini",host:"https://generativelanguage.googleapis.com",keyManagementURL:"https://makersuite.google.com/app/apikey",testModel:"gemini-2.0-flash"},openrouterai:{label:"OpenRouter",host:"https://openrouter.ai/api/v1/",keyManagementURL:"https://openrouter.ai/keys",testModel:"openai/chatgpt-4o-latest"},groq:{label:"Groq",host:"https://api.groq.com/openai",keyManagementURL:"https://console.groq.com/keys",testModel:"llama3-
`+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&i.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function Lgt(e){var t,r,n,o;let i=[];if(!((r=(t=e.candidates)===null||t===void 0?void 0:t[0].content)===null||r===void 0)&&r.parts)for(let a of(o=(n=e.candidates)===null||n===void 0?void 0:n[0].content)===null||o===void 0?void 0:o.parts)a.functionCall&&i.push(a.functionCall);if(i.length>0)return i}var WNr=[s4.RECITATION,s4.SAFETY,s4.LANGUAGE];function $Z(e){return!!e.finishReason&&WNr.includes(e.finishReason)}function pP(e){var t,r,n;let o="";if((!e.candidates||e.candidates.length===0)&&e.promptFeedback)o+="Response was blocked",!((t=e.promptFeedback)===null||t===void 0)&&t.blockReason&&(o+=` due to ${e.promptFeedback.blockReason}`),!((r=e.promptFeedback)===null||r===void 0)&&r.blockReasonMessage&&(o+=`: ${e.promptFeedback.blockReasonMessage}`);else if(!((n=e.candidates)===null||n===void 0)&&n[0]){let i=e.candidates[0];$Z(i)&&(o+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(o+=`: ${i.finishMessage}`))}return o}function u4(e){return this instanceof u4?(this.v=e,this):new u4(e)}function JNr(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(e,t||[]),o,i=[];return o={},a("next"),a("throw"),a("return"),o[Symbol.asyncIterator]=function(){return this},o;function a(f){n[f]&&(o[f]=function(p){return new Promise(function(h,m){i.push([f,p,h,m])>1||s(f,p)})})}function s(f,p){try{u(n[f](p))}catch(h){d(i[0][3],h)}}function u(f){f.value instanceof u4?Promise.resolve(f.value.v).then(l,c):d(i[0][2],f)}function l(f){s("next",f)}function c(f){s("throw",f)}function d(f,p){f(p),i.shift(),i.length&&s(i[0][0],i[0][1])}}var Fgt=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function GNr(e){let t=e.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),r=ZNr(t),[n,o]=r.tee();return{stream:YNr(n),response:KNr(o)}}async function KNr(e){let t=[],r=e.getReader();for(;;){let{done:n,value:o}=await r.read();if(n)return OSe(XNr(t));t.push(o)}}function YNr(e){return JNr(this,arguments,function*(){let r=e.getReader();for(;;){let{value:n,done:o}=yield u4(r.read());if(o)break;yield yield u4(OSe(n))}})}function ZNr(e){let t=e.getReader();return new ReadableStream({start(n){let o="";return i();function i(){return t.read().then(({value:a,done:s})=>{if(s){if(o.trim()){n.error(new ed("Failed to parse stream"));return}n.close();return}o+=a;let u=o.match(Fgt),l;for(;u;){try{l=JSON.parse(u[1])}catch{n.error(new ed(`Error parsing JSON response: "${u[1]}"`));return}n.enqueue(l),o=o.substring(u[0].length),u=o.match(Fgt)}return i()})}}})}function XNr(e){let t=e[e.length-1],r={promptFeedback:t?.promptFeedback};for(let n of e){if(n.candidates)for(let o of n.candidates){let i=o.index;if(r.candidates||(r.candidates=[]),r.candidates[i]||(r.candidates[i]={index:o.index}),r.candidates[i].citationMetadata=o.citationMetadata,r.candidates[i].groundingMetadata=o.groundingMetadata,r.candidates[i].finishReason=o.finishReason,r.candidates[i].finishMessage=o.finishMessage,r.candidates[i].safetyRatings=o.safetyRatings,o.content&&o.content.parts){r.candidates[i].content||(r.candidates[i].content={role:o.content.role||"user",parts:[]});let a={};for(let s of o.content.parts)s.text&&(a.text=s.text),s.functionCall&&(a.functionCall=s.functionCall),s.executableCode&&(a.executableCode=s.executableCode),s.codeExecutionResult&&(a.codeExecutionResult=s.codeExecutionResult),Object.keys(a).length===0&&(a.text=""),r.candidates[i].content.parts.push(a)}}n.usageMetadata&&(r.usageMetadata=n.usageMetadata)}return r}async function qgt(e,t,r,n){let o=await c4(t,YA.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(r),n);return GNr(o)}async function Ugt(e,t,r,n){let i=await(await c4(t,YA.GENERATE_CONTENT,e,!1,JSON.stringify(r),n)).json();return{response:OSe(i)}}function zgt(e){if(e!=null){if(typeof e=="string")return{role:"system",parts:[{text:e}]};if(e.text)return{role:"system",parts:[e]};if(e.parts)return e.role?e:{role:"system",parts:e.parts}}}function l4(e){let t=[];if(typeof e=="string")t=[{
`)===0?n.substr(1,n.length):n}).forEach(function(n){var o=n.split(":"),i=o.shift().trim();if(i){var a=o.join(":").trim();try{t.append(i,a)}catch(s){console.warn("Response "+s.message)}}}),t}Xgt.call(QA.prototype);function bw(e,t){if(!(this instanceof bw))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(t||(t={}),this.type="default",this.status=t.status===void 0?200:t.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=t.statusText===void 0?"":""+t.statusText,this.headers=new Wu(t.headers),this.url=t.url||"",this._initBody(e)}Xgt.call(bw.prototype);bw.prototype.clone=function(){return new bw(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new Wu(this.headers),url:this.url})};bw.error=function(){var e=new bw(null,{status:200,statusText:""});return e.ok=!1,e.status=0,e.type="error",e};var SLr=[301,302,303,307,308];bw.redirect=function(e,t){if(SLr.indexOf(t)===-1)throw new RangeError("Invalid status code");return new bw(null,{status:t,headers:{location:e}})};var XA=rc.DOMException;try{new XA}catch{XA=function(t,r){this.message=t,this.name=r;var n=Error(t);this.stack=n.stack},XA.prototype=Object.create(Error.prototype),XA.prototype.constructor=XA}function Qgt(e,t){return new Promise(function(r,n){var o=new QA(e,t);if(o.signal&&o.signal.aborted)return n(new XA("Aborted","AbortError"));var i=new XMLHttpRequest;function a(){i.abort()}i.onload=function(){var l={statusText:i.statusText,headers:wLr(i.getAllResponseHeaders()||"")};o.url.indexOf("file://")===0&&(i.status<200||i.status>599)?l.status=200:l.status=i.status,l.url="responseURL"in i?i.responseURL:l.headers.get("X-Request-URL");var c="response"in i?i.response:i.responseText;setTimeout(function(){r(new bw(c,l))},0)},i.onerror=function(){setTimeout(function(){n(new TypeError("Network request failed"))},0)},i.ontimeout=function(){setTimeout(function(){n(new TypeError("Network request timed out"))},0)},i.onabort=function(){setTimeout(function(){n(new XA("Aborted","AbortError"))},0)};function s(l){try{return l===""&&rc.location.href?rc.location.href:l}catch{return l}}if(i.open(o.method,s(o.url),!0),o.credentials==="include"?i.withCredentials=!0:o.credentials==="omit"&&(i.withCredentials=!1),"responseType"in i&&(kd.blob?i.responseType="blob":kd.arrayBuffer&&(i.responseType="arraybuffer")),t&&typeof t.headers=="object"&&!(t.headers instanceof Wu||rc.Headers&&t.headers instanceof rc.Headers)){var u=[];Object.getOwnPropertyNames(t.headers).forEach(function(l){u.push(nF(l)),i.setRequestHeader(l,MSe(t.headers[l]))}),o.headers.forEach(function(l,c){u.indexOf(c)===-1&&i.setRequestHeader(c,l)})}else o.headers.forEach(function(l,c){i.setRequestHeader(c,l)});o.signal&&(o.signal.addEventListener("abort",a),i.onreadystatechange=function(){i.readyState===4&&o.signal.removeEventListener("abort",a)}),i.send(typeof o._bodyInit>"u"?null:o._bodyInit)})}Qgt.polyfill=!0;rc.fetch||(rc.fetch=Qgt,rc.Headers=Wu,rc.Request=QA,rc.Response=bw);var xLr="0.5.9",CLr=Object.defineProperty,OLr=(e,t,r)=>t in e?CLr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,ASe=(e,t,r)=>(OLr(e,typeof t!="symbol"?t+"":t,r),r),DSe=class e extends Error{constructor(t,r){super(t),this.error=t,this.status_code=r,this.name="ResponseError",Error.captureStackTrace&&Error.captureStackTrace(this,e)}},jSe=class{constructor(t,r,n){ASe(this,"abortController"),ASe(this,"itr"),ASe(this,"doneCallback"),this.abortController=t,this.itr=r,this.doneCallback=n}abort(){this.abortController.abort()}async*[Symbol.asyncIterator](){for await(let t of this.itr){if("error"in t)throw new Error(t.error);if(yield t,t.done||t.status==="success"){this.doneCallback();return}}throw new Error("Did not receive done or success response in stream.")}},NSe=async e=>{if(e.ok)return;let t=`Error ${e.status}: ${e.statusText}`,r=null;if(e.headers.get("content-type")?.includes("application/json"))try{r=await
`);r=a.pop()??"";for(let s of a)try{yield JSON.parse(s)}catch{console.warn("invalid json: ",s)}}for(let o of r.split(`
`).filter(i=>i!==""))try{yield JSON.parse(o)}catch{console.warn("invalid json: ",o)}},MLr=e=>{if(!e)return"http://127.0.0.1:11434";let t=e.includes("://");e.startsWith(":")&&(e=`http://127.0.0.1${e}`,t=!0),t||(e=`http://${e}`);let r=new URL(e),n=r.port;n||(t?n=r.protocol==="https:"?"443":"80":n="11434");let o=`${r.protocol}//${r.hostname}:${n}${r.pathname}`;return o.endsWith("/")&&(o=o.slice(0,-1)),o},ILr=Object.defineProperty,ALr=(e,t,r)=>t in e?ILr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,RSe=(e,t,r)=>(ALr(e,typeof t!="symbol"?t+"":t,r),r),eR=class{constructor(t){RSe(this,"config"),RSe(this,"fetch"),RSe(this,"ongoingStreamedRequests",[]),this.config={host:""},t?.proxy||(this.config.host=MLr(t?.host??"http://127.0.0.1:11434")),this.fetch=fetch,t?.fetch!=null&&(this.fetch=t.fetch)}abort(){for(let t of this.ongoingStreamedRequests)t.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(t,r){r.stream=r.stream??!1;let n=`${this.config.host}/api/${t}`;if(r.stream){let i=new AbortController,a=await oF(this.fetch,n,r,{signal:i.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");let s=TLr(a.body),u=new jSe(i,s,()=>{let l=this.ongoingStreamedRequests.indexOf(u);l>-1&&this.ongoingStreamedRequests.splice(l,1)});return this.ongoingStreamedRequests.push(u),u}return await(await oF(this.fetch,n,r,{headers:this.config.headers})).json()}async encodeImage(t){if(typeof t!="string"){let r=new Uint8Array(t),n="",o=r.byteLength;for(let i=0;i<o;i++)n+=String.fromCharCode(r[i]);return btoa(n)}return t}async generate(t){return t.images&&(t.images=await Promise.all(t.images.map(this.encodeImage.bind(this)))),this.processStreamableRequest("generate",t)}async chat(t){if(t.messages)for(let r of t.messages)r.images&&(r.images=await Promise.all(r.images.map(this.encodeImage.bind(this))));return this.processStreamableRequest("chat",t)}async create(t){return this.processStreamableRequest("create",{name:t.model,stream:t.stream,modelfile:t.modelfile,quantize:t.quantize})}async pull(t){return this.processStreamableRequest("pull",{name:t.model,stream:t.stream,insecure:t.insecure})}async push(t){return this.processStreamableRequest("push",{name:t.model,stream:t.stream,insecure:t.insecure})}async delete(t){return await PLr(this.fetch,`${this.config.host}/api/delete`,{name:t.model}),{status:"success"}}async copy(t){return await oF(this.fetch,`${this.config.host}/api/copy`,{...t}),{status:"success"}}async list(){return await(await eyt(this.fetch,`${this.config.host}/api/tags`)).json()}async show(t){return await(await oF(this.fetch,`${this.config.host}/api/show`,{...t})).json()}async embed(t){return await(await oF(this.fetch,`${this.config.host}/api/embed`,{...t})).json()}async embeddings(t){return await(await oF(this.fetch,`${this.config.host}/api/embeddings`,{...t})).json()}async ps(){return await(await eyt(this.fetch,`${this.config.host}/api/ps`)).json()}},RLr=new eR;kh();iy();var nc=[];for(WZ=0;WZ<256;++WZ)nc.push((WZ+256).toString(16).slice(1));var WZ;function tyt(e,t=0){return(nc[e[t+0]]+nc[e[t+1]]+nc[e[t+2]]+nc[e[t+3]]+"-"+nc[e[t+4]]+nc[e[t+5]]+"-"+nc[e[t+6]]+nc[e[t+7]]+"-"+nc[e[t+8]]+nc[e[t+9]]+"-"+nc[e[t+10]]+nc[e[t+11]]+nc[e[t+12]]+nc[e[t+13]]+nc[e[t+14]]+nc[e[t+15]]).toLowerCase()}var JZ,DLr=new Uint8Array(16);function FSe(){if(!JZ&&(JZ=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!JZ))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return JZ(DLr)}var jLr=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),kSe={randomUUID:jLr};function NLr(e,t,r){if(kSe.randomUUID&&!t&&!e)return kSe.randomUUID();e=e||{};var n=e.random||(e.rng||FSe)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){r=r||0;for(var o=0;o<16;++o)t[r+o]=n[o];return t}return tyt(n)}var BSe=NLr;function $Se(e,t){return new Jr({content:e.content??"",tool_call_chunks:e.tool_calls?.map(r=>({name:r.function.name,args:JSON.stringify(r.function.arguments),type:"tool_call_chunk",index:0,id:BSe()})),response_
`,"\r"]);nR.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function ZSe(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var ww=class e{constructor(t,r){this.iterator=t,this.controller=r}static fromSSEResponse(t,r){let n=!1;async function*o(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let i=!1;try{for await(let a of QLr(t,r))if(!i){if(a.data.startsWith("[DONE]")){i=!0;continue}if(a.event===null){let s;try{s=JSON.parse(a.data)}catch(u){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),u}if(s&&s.error)throw new fs(void 0,s.error,void 0,void 0);yield s}else{let s;try{s=JSON.parse(a.data)}catch(u){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),u}if(a.event=="error")throw new fs(void 0,s.error,s.message,void 0);yield{event:a.event,data:s}}}i=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{i||r.abort()}}return new e(o,r)}static fromReadableStream(t,r){let n=!1;async function*o(){let a=new nR,s=ZSe(t);for await(let u of s)for(let l of a.decode(u))yield l;for(let u of a.flush())yield u}async function*i(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{for await(let s of o())a||s&&(yield JSON.parse(s));a=!0}catch(s){if(s instanceof Error&&s.name==="AbortError")return;throw s}finally{a||r.abort()}}return new e(i,r)}[Symbol.asyncIterator](){return this.iterator()}tee(){let t=[],r=[],n=this.iterator(),o=i=>({next:()=>{if(i.length===0){let a=n.next();t.push(a),r.push(a)}return i.shift()}});return[new e(()=>o(t),this.controller),new e(()=>o(r),this.controller)]}toReadableStream(){let t=this,r,n=new TextEncoder;return new JSe({async start(){r=t[Symbol.asyncIterator]()},async pull(o){try{let{value:i,done:a}=await r.next();if(a)return o.close();let s=n.encode(JSON.stringify(i)+`
`);o.enqueue(s)}catch(i){o.error(i)}},async cancel(){await r.return?.()}})}};async function*QLr(e,t){if(!e.body)throw t.abort(),new qt("Attempted to iterate over a response with no body");let r=new XSe,n=new nR,o=ZSe(e.body);for await(let i of eFr(o))for(let a of n.decode(i)){let s=r.decode(a);s&&(yield s)}for(let i of n.flush()){let a=r.decode(i);a&&(yield a)}}async function*eFr(e){let t=new Uint8Array;for await(let r of e){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?new TextEncoder().encode(r):r,o=new Uint8Array(t.length+n.length);o.set(t),o.set(n,t.length),t=o;let i;for(;(i=tFr(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}function tFr(e){for(let n=0;n<e.length-2;n++){if(e[n]===10&&e[n+1]===10||e[n]===13&&e[n+1]===13)return n+2;if(e[n]===13&&e[n+1]===10&&n+3<e.length&&e[n+2]===13&&e[n+3]===10)return n+4}return-1}var XSe=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(t){if(t.endsWith("\r")&&(t=t.substring(0,t.length-1)),!t){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(t),t.startsWith(":"))return null;let[r,n,o]=rFr(t,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}};function rFr(e,t){let r=e.indexOf(t);return r!==-1?[e.substring(0,r),t,e.substring(r+t.length)]:[e,"",""]}var pyt=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function",hyt=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&f4(e),f4=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",nFr=e=>hyt(e)||pyt(e)||YSe(e);async function txe(e,t,r){if(e=await e,hyt(e))return e;if(pyt(e)){let o=await e.blob();t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=f4(o)?[await o.arrayBuffer()]:[o];return new XZ(i,t,r)}let n=await oFr(e);if(t||(t=aFr(e)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new XZ(n,t,r)}async function oFr(e){let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(f4(e))t.push(await e.arrayBuffer());else if(sFr(e))for await(let r of e)t.push(r);else throw new Error(`Unexpected data type: ${typeof e}; constructor: ${e?.constructor?.name}; props: ${iFr(e)}`);return t}function iFr(e){return`[${Object.getOwnPropertyNames(e).map(r=>`"${r}"`).join(", ")}]`}function aFr(e){return QSe(e.name)||QSe(e.filename)||QSe(e.path)?.split(/[\\/]/).pop()}var QSe=e=>{if(typeof e=="string")return e;if(typeof Buffer<"u"&&e instanceof Buffer)return String(e)},sFr=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function",rxe=e=>e&&typeof e=="object"&&e.body&&e[Symbol.toStringTag]==="MultipartBody";var Bh=async e=>{let t=await myt(e.body);return GSe(t,e)},myt=async e=>{let t=new WSe;return await Promise.all(Object.entries(e||{}).map(([r,n])=>exe(t,r,n))),t};var exe=async(e,t,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")e.append(t,String(r));else if(nFr(r)){let n=await txe(r);e.append(t,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>exe(e,t+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>exe(e,`${t}[${n}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var lFr=function(e,t,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r},cFr=function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},rX;async function wyt(e){let{response:t}=e;if(e.options.stream)return mF("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):ww.fromSSEResponse(t,e.controller);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let r=t.headers.get("content-type");if(r?.includes("application/json")||r?.includes("application/vnd.api+json")){let i=await t.json();return mF("response",t.status,t.url,t.headers,i),Syt(i,t)}let o=await t.text();return mF("response",t.status,t.url,t.headers,o),o}function Syt(e,t){return!e||typeof e!="object"||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}var oX=class e extends Promise{constructor(t,r=wyt){super(n=>{n(null)}
\r `.includes(e[n]);)n++};return a()},bxe=e=>TFr(e,bl.ALL^bl.NUM);var CF=function(e,t,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r},Vo=function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},Gu,Fx,OF,yP,_xe,pX,vxe,wxe,Sxe,hX,xxe,jyt,EF=class e extends xF{constructor(t){super(),Gu.add(this),Fx.set(this,void 0),OF.set(this,void 0),yP.set(this,void 0),CF(this,Fx,t,"f"),CF(this,OF,[],"f")}get currentChatCompletionSnapshot(){return Vo(this,yP,"f")}static fromReadableStream(t){let r=new e(null);return r._run(()=>r._fromReadableStream(t)),r}static createChatCompletion(t,r,n){let o=new e(r);return o._run(()=>o._runChatCompletion(t,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createChatCompletion(t,r,n){super._createChatCompletion;let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),Vo(this,Gu,"m",_xe).call(this);let i=await t.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let a of i)Vo(this,Gu,"m",vxe).call(this,a);if(i.controller.signal?.aborted)throw new Xa;return this._addChatCompletion(Vo(this,Gu,"m",hX).call(this))}async _fromReadableStream(t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),Vo(this,Gu,"m",_xe).call(this),this._connected();let o=ww.fromReadableStream(t,this.controller),i;for await(let a of o)i&&i!==a.id&&this._addChatCompletion(Vo(this,Gu,"m",hX).call(this)),Vo(this,Gu,"m",vxe).call(this,a),i=a.id;if(o.controller.signal?.aborted)throw new Xa;return this._addChatCompletion(Vo(this,Gu,"m",hX).call(this))}[(Fx=new WeakMap,OF=new WeakMap,yP=new WeakMap,Gu=new WeakSet,_xe=function(){this.ended||CF(this,yP,void 0,"f")},pX=function(r){let n=Vo(this,OF,"f")[r.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},Vo(this,OF,"f")[r.index]=n,n)},vxe=function(r){if(this.ended)return;let n=Vo(this,Gu,"m",jyt).call(this,r);this._emit("chunk",r,n);for(let o of r.choices){let i=n.choices[o.index];o.delta.content!=null&&i.message?.role==="assistant"&&i.message?.content&&(this._emit("content",o.delta.content,i.message.content),this._emit("content.delta",{delta:o.delta.content,snapshot:i.message.content,parsed:i.message.parsed})),o.delta.refusal!=null&&i.message?.role==="assistant"&&i.message?.refusal&&this._emit("refusal.delta",{delta:o.delta.refusal,snapshot:i.message.refusal}),o.logprobs?.content!=null&&i.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:o.logprobs?.content,snapshot:i.logprobs?.content??[]}),o.logprobs?.refusal!=null&&i.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:o.logprobs?.refusal,snapshot:i.logprobs?.refusal??[]});let a=Vo(this,Gu,"m",pX).call(this,i);i.finish_reason&&(Vo(this,Gu,"m",Sxe).call(this,i),a.current_tool_call_index!=null&&Vo(this,Gu,"m",wxe).call(this,i,a.current_tool_call_index));for(let s of o.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(Vo(this,Gu,"m",Sxe).call(this,i),a.current_tool_call_index!=null&&Vo(this,Gu,"m",wxe).call(this,i,a.current_tool_call_index)),a.current_tool_call_index=s.index;for(let s of o.delta.tool_calls??[]){let u=i.message.tool_calls?.[s.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:s.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,
${mX(e)}`);if(T==null)throw new qt(`missing choices[${d}].tool_calls[${x}].type
${mX(e)}`);if(j==null)throw new qt(`missing choices[${d}].tool_calls[${x}].function.name
${mX(e)}`);if(A==null)throw new qt(`missing choices[${d}].tool_calls[${x}].function.arguments
${mX(e)}`);return{...M,id:E,type:T,function:{...N,name:j,arguments:A}}})}}:{...p,message:{...g,content:h,role:v,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}),created:o,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};return Myt(u,t)}function mX(e){return JSON.stringify(e)}var S4=class e extends EF{static fromReadableStream(t){let r=new e(null);return r._run(()=>r._fromReadableStream(t)),r}static runFunctions(t,r,n){let o=new e(null),i={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return o._run(()=>o._runFunctions(t,r,i)),o}static runTools(t,r,n){let o=new e(r),i={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(t,r,i)),o}};var x4=class extends ut{parse(t,r){return Ayt(t.tools),this._client.chat.completions.create(t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap(n=>v4(n,t))}runFunctions(t,r){return t.stream?S4.runFunctions(this._client,t,r):w4.runFunctions(this._client,t,r)}runTools(t,r){return t.stream?S4.runTools(this._client,t,r):w4.runTools(this._client,t,r)}stream(t,r){return EF.createChatCompletion(this._client,t,r)}};var PF=class extends ut{constructor(){super(...arguments),this.completions=new x4(this._client)}};(function(e){e.Completions=x4})(PF||(PF={}));var TF=class extends ut{create(t,r){return this._client.post("/realtime/sessions",{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}};var uR=class extends ut{constructor(){super(...arguments),this.sessions=new TF(this._client)}};uR.Sessions=TF;var St=function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},xp=function(e,t,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r},oc,Cxe,xw,gX,bg,cR,MF,lR,_X,Cp,yX,bX,E4,C4,O4,Nyt,Lyt,Fyt,kyt,Byt,$yt,qyt,Cw=class e extends SF{constructor(){super(...arguments),oc.add(this),Cxe.set(this,[]),xw.set(this,{}),gX.set(this,{}),bg.set(this,void 0),cR.set(this,void 0),MF.set(this,void 0),lR.set(this,void 0),_X.set(this,void 0),Cp.set(this,void 0),yX.set(this,void 0),bX.set(this,void 0),E4.set(this,void 0)}[(Cxe=new WeakMap,xw=new WeakMap,gX=new WeakMap,bg=new WeakMap,cR=new WeakMap,MF=new WeakMap,lR=new WeakMap,_X=new WeakMap,Cp=new WeakMap,yX=new WeakMap,bX=new WeakMap,E4=new WeakMap,oc=new WeakSet,Symbol.asyncIterator)](){let t=[],r=[],n=!1;return this.on("event",o=>{let i=r.shift();i?i.resolve(o):t.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let i of r)i.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let i of r)i.reject(o);r.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((i,a)=>r.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(t){let r=new e;return r._run(()=>r._fromReadableStream(t)),r}async _fromReadableStream(t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();let o=ww.fromReadableStream(t,this.controller);for await(let i of o)St(this,oc,"m",C4).call(this,i);if(o.controller.signal?.aborted)throw new Xa;return this._addRun(St(this,oc,"m",O4).call(this))}toReadableStream(){return new ww(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(t,r,n,o,i){let a=new e;return a._run(()=>a._runToolAssistantStream(t,r,n,o,{...i,headers:{...i?.headers,"X-Stainless-
This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
`);super({baseURL:a.baseURL,timeout:a.timeout??6e5,httpAgent:a.httpAgent,maxRetries:a.maxRetries,fetch:a.fetch}),this.completions=new hR(this),this.chat=new hP(this),this.embeddings=new mR(this),this.files=new _P(this),this.images=new bR(this),this.audio=new Sw(this),this.moderations=new vR(this),this.models=new vP(this),this.fineTuning=new Tw(this),this.beta=new Op(this),this.batches=new mP(this),this.uploads=new wP(this),this._options=a,this.apiKey=r,this.organization=n,this.project=o}defaultQuery(){return this._options.defaultQuery}defaultHeaders(t){return{...super.defaultHeaders(t),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(t){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(t){return HSe(t,{arrayFormat:"brackets"})}};zyt=Mr;Mr.OpenAI=zyt;Mr.DEFAULT_TIMEOUT=6e5;Mr.OpenAIError=qt;Mr.APIError=fs;Mr.APIConnectionError=jx;Mr.APIConnectionTimeoutError=gg;Mr.APIUserAbortError=Xa;Mr.NotFoundError=uF;Mr.ConflictError=lF;Mr.RateLimitError=dF;Mr.BadRequestError=iF;Mr.AuthenticationError=aF;Mr.InternalServerError=fF;Mr.PermissionDeniedError=sF;Mr.UnprocessableEntityError=cF;Mr.toFile=txe;Mr.fileFromPath=QZ;Mr.Completions=hR;Mr.Chat=hP;Mr.Embeddings=mR;Mr.Files=_P;Mr.FileObjectsPage=gR;Mr.Images=bR;Mr.Audio=Sw;Mr.Moderations=vR;Mr.Models=vP;Mr.ModelsPage=_R;Mr.FineTuning=Tw;Mr.Beta=Op;Mr.Batches=mP;Mr.BatchesPage=iR;Mr.Uploads=wP;kh();Dx();IS();SO();$D();Due();wO();BM();function wR(e,t){if(e.function===void 0)return;let r;if(t?.partial)try{r=RD(e.function.arguments??"{}")}catch{return}else try{r=JSON.parse(e.function.arguments)}catch(o){throw new ep([`Function "${e.function.name}" arguments:`,"",e.function.arguments,"","are not valid JSON.",`Error: ${o.message}`].join(`
`))}let n={name:e.function.name,args:r,type:"tool_call"};return t?.returnId&&(n.id=e.id),n}function BF(e){if(e.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}}}function $F(e,t){return{name:e.function?.name,args:e.function?.arguments,id:e.id,error:t,type:"invalid_tool_call"}}var Oxe=class extends WM{static lc_name(){return"JsonOutputToolsParser"}constructor(t){super(t),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=t?.returnId??this.returnId}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(t){return await this.parsePartialResult(t,!1)}async parsePartialResult(t,r=!0){let n=t[0].message,o;if(Fu(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=>wR(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}},_g=class extends Oxe{static lc_name(){return"JsonOutputKeyToolsParser"}constructor(t){super(t),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=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){if(this.zodSchema===void 0)return t;let r=await this.zodSchema.safeParseAsync(t);if(r.success)return r.data;throw new ep(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(r.error.errors)}`,JSON.stringify(t,null,2))}async parsePartialResult(t){let n=(await super.parsePartialResult(t)).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(t){let n=(await super.parsePartialResult(t,!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}};oh();var Vyt=Symbol("Let zodToJsonSchema decide on which parser to use"),Hyt={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"},Wyt=e=>typeof e=="string"?{...Hyt,basePath:["#"],definitions:{},name:e}:{...Hyt,basePath:["#"],definitions:{},...e};var P4=e=>"_def"in e?e._def:e;function Jyt(e){if(!e)return!0;for(let t in e)return!1;return!0}var Gyt=e=>{let t=Wyt(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(t.definitions).map(([n,o])=>[P4(o),{def:P4(o),path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}};function Exe(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function bn(
]))`;continue}else if(o[l]==="$"){i+=`($|(?=[\r
]))`;continue}}if(n.s&&o[l]==="."){i+=s?`${o[l]}\r
`:`[${o[l]}\r
]`;continue}i+=o[l],o[l]==="\\"?a=!0:s&&o[l]==="]"?s=!1:!s&&o[l]==="["&&(s=!0)}try{let l=new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return i};function wX(e,t){if(t.target==="openApi3"&&e.keyType?._def.typeName===re.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:Ft(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:Ft(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??{}};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===re.ZodString&&e.keyType._def.checks?.length){let n=Object.entries(vX(e.keyType._def,t)).reduce((o,[i,a])=>i==="type"?o:{...o,[i]:a},{});return{...r,propertyNames:n}}else if(e.keyType?._def.typeName===re.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};return r}function sbt(e,t){if(t.mapStrategy==="record")return wX(e,t);let r=Ft(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},n=Ft(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function ubt(e){let t=e.values,n=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function lbt(){return{not:{}}}function cbt(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var T4={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function fbt(e,t){if(t.target==="openApi3")return dbt(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in T4&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=T4[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((i,a,s)=>s.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return dbt(e,t)}var dbt=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>Ft(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function pbt(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"||t.nullableStrategy==="property"?{type:T4[e.innerType._def.typeName],nullable:!0}:{type:[T4[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let n=Ft(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Ft(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function hbt(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",Exe(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?bn(r,"minimum",n.value,n.message,t):bn(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),bn(r,"minimum",n.value,n.message,t));break;case"max":t.t
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${t}/
`,e}function xR(e){let t;return e.constructor.name===gg.name?(t=new Error(e.message),t.name="TimeoutError"):e.constructor.name===Xa.name?(t=new Error(e.message),t.name="AbortError"):e.status===400&&e.message.includes("tool_calls")?t=M4(e,"INVALID_TOOL_RESULTS"):e.status===401?t=M4(e,"MODEL_AUTHENTICATION"):e.status===429?t=M4(e,"MODEL_RATE_LIMIT"):e.status===404?t=M4(e,"MODEL_NOT_FOUND"):t=e,t}function Tbt(e){if(e)return e==="any"||e==="required"?"required":e==="auto"?"auto":e==="none"?"none":typeof e=="string"?{type:"function",function:{name:e}}:e}function ekr(e){return e.anyOf!==void 0&&Array.isArray(e.anyOf)}function Mbt(e){let t=["namespace functions {",""];for(let r of e)r.description&&t.push(`// ${r.description}`),Object.keys(r.parameters.properties??{}).length>0?(t.push(`type ${r.name} = (_: {`),t.push(Ibt(r.parameters,0)),t.push("}) => any;")):t.push(`type ${r.name} = () => any;`),t.push("");return t.push("} // namespace functions"),t.join(`
`)}function Ibt(e,t){let r=[];for(let[n,o]of Object.entries(e.properties??{}))o.description&&t<2&&r.push(`// ${o.description}`),e.required?.includes(n)?r.push(`${n}: ${SX(o,t)},`):r.push(`${n}?: ${SX(o,t)},`);return r.map(n=>" ".repeat(t)+n).join(`
`)}function SX(e,t){if(ekr(e))return e.anyOf.map(r=>SX(r,t)).join(" | ");switch(e.type){case"string":return e.enum?e.enum.map(r=>`"${r}"`).join(" | "):"string";case"number":return e.enum?e.enum.map(r=>`${r}`).join(" | "):"number";case"integer":return e.enum?e.enum.map(r=>`${r}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",Ibt(e,t+2),"}"].join(`
`);case"array":return e.items?`${SX(e.items,t)}[]`:"any[]";default:return""}}function Abt(e,t){let r;if(hg(e)){let n=Pbt({name:e.name,parameters:e.schema,description:e.description});n.function.parameters?r={type:n.type,function:{name:n.function.name,description:n.function.description,parameters:n.function.parameters,...t?.strict!==void 0?{strict:t.strict}:{}}}:r={type:"function",function:jZ(e,t)}}else r=e;return t?.strict!==void 0&&(r.function.strict=t.strict),r}function tkr(e){return e.role!=="system"&&e.role!=="developer"&&e.role!=="assistant"&&e.role!=="user"&&e.role!=="function"&&e.role!=="tool"&&console.warn(`Unknown message role: ${e.role}`),e.role}function Dbt(e){let t=e._getType();switch(t){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":{if(!xd.isInstance(e))throw new Error("Invalid generic chat message");return tkr(e)}default:throw new Error(`Unknown message type: ${t}`)}}function Mxe(e,t){return e.flatMap(r=>{let n=Dbt(r);n==="system"&&t?.startsWith("o1")&&(n="developer");let o={role:n,content:r.content};if(r.name!=null&&(o.name=r.name),r.additional_kwargs.function_call!=null&&(o.function_call=r.additional_kwargs.function_call,o.content=null),Fu(r)&&r.tool_calls?.length?(o.tool_calls=r.tool_calls.map(BF),o.content=null):(r.additional_kwargs.tool_calls!=null&&(o.tool_calls=r.additional_kwargs.tool_calls),r.tool_call_id!=null&&(o.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio){let i={role:"assistant",audio:{id:r.additional_kwargs.audio.id}};return[o,i]}return o})}function Rbt(e,t){return gw(e)?t?.strict!==void 0?{...e,function:{...e.function,strict:t.strict}}:e:Abt(e,t)}var Mw=class extends Qc{static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning_effort"]}get lc_secrets(){return{openAIApiKey:"OPENAI_API_KEY",apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{modelName:"model",openAIApiKey:"openai_api_key",apiKey:"openai_api_key"}}constructor(t){super(t??{}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"frequencyPenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"presencePenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"n",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"logitBias",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"modelName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"gpt-3.5-turbo"}),Object.defineProperty(this,"modelKwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stop",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stopSequences",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"streamUsage",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logprobs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topLogprobs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object
Details: ${p.message}`),new ID(h,JSON.stringify(t))}let i=qM(r),s=await ns.configure(i.callbacks,this.callbacks,i.tags||n,this.tags,i.metadata,this.metadata,{verbose:this.verbose})?.handleToolStart(this.toJSON(),typeof o=="string"?o:JSON.stringify(o),i.runId,void 0,void 0,void 0,i.runName);delete i.runId;let u;try{u=await this._call(o,s,i)}catch(p){throw await s?.handleToolError(p),p}let l,c;if(this.responseFormat==="content_and_artifact")if(Array.isArray(u)&&u.length===2)[l,c]=u;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
Result: ${JSON.stringify(u)}`);else l=u;let d;i&&"configurable"in i&&(d=i.configurable.tool_call_id);let f=nkr({content:l,artifact:c,toolCallId:d,name:this.name});return await s?.handleToolEnd(f),f}},I4=class extends CX{constructor(t){super(t),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:Er.object({input:Er.string().optional()}).transform(r=>r.input)})}call(t,r){return super.call(typeof t=="string"||!t?{input:t}:t,r)}},Ixe=class extends I4{static lc_name(){return"DynamicTool"}constructor(t){super(t),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=t.name,this.description=t.description,this.func=t.func,this.returnDirect=t.returnDirect??this.returnDirect}async call(t,r){let n=qM(r);return n.runName===void 0&&(n.runName=this.name),super.call(t,n)}async _call(t,r,n){return this.func(t,r,n)}},Axe=class extends CX{static lc_name(){return"DynamicStructuredTool"}constructor(t){super(t),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=t.name,this.description=t.description,this.func=t.func,this.returnDirect=t.returnDirect??this.returnDirect,this.schema=Af(t.schema)?t.schema:Er.object({}).passthrough()}async call(t,r,n){let o=qM(r);return o.runName===void 0&&(o.runName=this.name),super.call(t,o,n)}_call(t,r,n){return this.func(t,r,n)}};function Ep(e,t){if(!t.schema||Af(t.schema)&&(!("shape"in t.schema)||!t.schema.shape))return new Ixe({...t,description:t.description??t.schema?.description??`${t.name} tool`,func:async(n,o,i)=>new Promise((a,s)=>{let u=Ta(i,{callbacks:o?.getChild()});jc.runWithConfig(Xf(u),async()=>{try{a(e(n,u))}catch(l){s(l)}})})});let r=t.description??t.schema.description??`${t.name} tool`;return new Axe({...t,description:r,schema:t.schema,func:async(n,o,i)=>new Promise((a,s)=>{let u=Ta(i,{callbacks:o?.getChild()});jc.runWithConfig(Xf(u),async()=>{try{a(e(n,u))}catch(l){s(l)}})})})}function nkr(e){let{content:t,artifact:r,toolCallId:n}=e;return n&&!hLe(t)?typeof t=="string"||Array.isArray(t)&&t.every(o=>typeof o=="object")?new vS({content:t,artifact:r,tool_call_id:n,name:e.name}):new vS({content:okr(t),artifact:r,tool_call_id:n,name:e.name}):t}function okr(e){try{return JSON.stringify(e,null,2)}catch{return`${e}`}}var Rxe=class extends I4{static lc_name(){return"DallEAPIWrapper"}constructor(t){t?.responseFormat!==void 0&&["url","b64_json"].includes(t.responseFormat)&&(t.dallEResponseFormat=t.responseFormat,t.responseFormat="content"),super(t),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"dalle_api_wrapper"}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:"A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description."}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"dall-e-3"}),Object.defineProperty(this,"style",{enumerable:!0,configurable:!0,writable:!0,value:"vivid"}),Object.defineProperty(this,"quality",{enumerable:!0,configurable:!0,writable:!0,value:"standard"}),Object.defineProperty(this,"n",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:"1024x1024"}),Object.defineProperty(this,"dallEResponseFormat",{enumerable:!0,configurable:!0,writable:!0,value:"url"}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,wri
without CORS Error: `+bi(n)+`
with CORS Error: `+bi(o);throw new Error(i)}}}};var $4=require("obsidian");var Nbt={arabic:"ar",armenian:"am",bulgarian:"bg",danish:"dk",dutch:"nl",english:"en",finnish:"fi",french:"fr",german:"de",greek:"gr",hungarian:"hu",indian:"in",indonesian:"id",irish:"ie",italian:"it",lithuanian:"lt",nepali:"np",norwegian:"no",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"rs",slovenian:"ru",spanish:"es",swedish:"se",tamil:"ta",turkish:"tr",ukrainian:"uk",sanskrit:"sk"},Lbt={dutch:/[^A-Za-zàèéìòóù0-9_'-]+/gim,english:/[^A-Za-zàèéìòóù0-9_'-]+/gim,french:/[^a-z0-9äâàéèëêïîöôùüûœç-]+/gim,italian:/[^A-Za-zàèéìòóù0-9_'-]+/gim,norwegian:/[^a-z0-9_æøåÆØÅäÄöÖüÜ]+/gim,portuguese:/[^a-z0-9à-úÀ-Ú]/gim,russian:/[^a-z0-9а-яА-ЯёЁ]+/gim,spanish:/[^a-z0-9A-Zá-úÁ-ÚñÑüÜ]+/gim,swedish:/[^a-z0-9_åÅäÄöÖüÜ-]+/gim,german:/[^a-z0-9A-ZäöüÄÖÜß]+/gim,finnish:/[^a-z0-9äöÄÖ]+/gim,danish:/[^a-z0-9æøåÆØÅ]+/gim,hungarian:/[^a-z0-9áéíóöőúüűÁÉÍÓÖŐÚÜŰ]+/gim,romanian:/[^a-z0-9ăâîșțĂÂÎȘȚ]+/gim,serbian:/[^a-z0-9čćžšđČĆŽŠĐ]+/gim,turkish:/[^a-z0-9çÇğĞıİöÖşŞüÜ]+/gim,lithuanian:/[^a-z0-9ąčęėįšųūžĄČĘĖĮŠŲŪŽ]+/gim,arabic:/[^a-z0-9أ-ي]+/gim,nepali:/[^a-z0-9अ-ह]+/gim,irish:/[^a-z0-9áéíóúÁÉÍÓÚ]+/gim,indian:/[^a-z0-9अ-ह]+/gim,armenian:/[^a-z0-9ա-ֆ]+/gim,greek:/[^a-z0-9α-ωά-ώ]+/gim,indonesian:/[^a-z0-9]+/gim,ukrainian:/[^a-z0-9а-яА-ЯіїєІЇЄ]+/gim,slovenian:/[^a-z0-9螚ȎŠ]+/gim,bulgarian:/[^a-z0-9а-яА-Я]+/gim,tamil:/[^a-z0-9அ-ஹ]+/gim,sanskrit:/[^a-z0-9A-Zāīūṛḷṃṁḥśṣṭḍṇṅñḻḹṝ]+/gim},A4=Object.keys(Nbt);function Fbt(e){return e!==void 0&&A4.includes(e)?Nbt[e]:void 0}var akr=Date.now().toString().slice(5),skr=0;var kbt=BigInt(1e3),Bbt=BigInt(1e6),$bt=BigInt(1e9);var Dxe=65535;function Qo(e,t){if(t.length<Dxe)Array.prototype.push.apply(e,t);else{let r=t.length;for(let n=0;n<r;n+=Dxe)Array.prototype.push.apply(e,t.slice(n,n+Dxe))}}function Ubt(e,...t){return e.replace(/%(?:(?<position>\d+)\$)?(?<width>-?\d*\.?\d*)(?<type>[dfs])/g,function(...r){let n=r[r.length-1],{width:o,type:i,position:a}=n,s=a?t[Number.parseInt(a)-1]:t.shift(),u=o===""?0:Number.parseInt(o);switch(i){case"d":return s.toString().padStart(u,"0");case"f":{let l=s,[c,d]=o.split(".").map(f=>Number.parseFloat(f));return typeof d=="number"&&d>=0&&(l=l.toFixed(d)),typeof c=="number"&&c>=0?l.toString().padStart(u,"0"):l.toString()}case"s":return u<0?s.toString().padEnd(-u," "):s.toString().padStart(u," ");default:return s}})}function ukr(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function lkr(){return typeof process<"u"&&process.release&&process.release.name==="node"}function qbt(){return BigInt(Math.floor(performance.now()*1e6))}function CR(e){return typeof e=="number"&&(e=BigInt(e)),e<kbt?`${e}ns`:e<Bbt?`${e/kbt}\u03BCs`:e<$bt?`${e/Bbt}ms`:`${e/$bt}s`}function Sg(){return ukr()?qbt():lkr()||typeof process<"u"&&typeof process?.hrtime?.bigint=="function"?process.hrtime.bigint():typeof performance<"u"?qbt():BigInt(0)}function R4(){return`${akr}-${skr++}`}function qF(e,t){return Object.hasOwn===void 0?Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0:Object.hasOwn(e,t)?e[t]:void 0}function zbt(e,t){return t[1]===e[1]?e[0]-t[0]:t[1]-e[1]}function UF(e){if(e.length===0)return[];if(e.length===1)return e[0];for(let r=1;r<e.length;r++)if(e[r].length<e[0].length){let n=e[0];e[0]=e[r],e[r]=n}let t=new Map;for(let r of e[0])t.set(r,1);for(let r=1;r<e.length;r++){let n=0;for(let o of e[r]){let i=t.get(o);i===r&&(t.set(o,i+1),n++)}if(n===0)return[]}return e[0].filter(r=>{let n=t.get(r);return n!==void 0&&t.set(r,0),n===e.length})}function PX(e,t){let r={},n=t.length;for(let o=0;o<n;o++){let i=t[o],a=i.split("."),s=e,u=a.length;for(let l=0;l<u;l++)if(s=s[a[l]],typeof s=="object"){if(s!==null&&"lat"in s&&"lon"in s&&typeof s.lat=="number"&&typeof s.lon=="number"){s=r[i]=s;break}else if(!Array.isArray(s)&&s!==null&&l===u-1){s=void 0;break}}else if((s===null||typeof s
- `),fkr={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported.
Supported languages are:
- ${dkr}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmer property must be a function.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.oramasearch.com/open-source/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Custom stop words array must only contain strings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boost value must be a number greater than, or less than 0.",INVALID_FILTER_OPERATION:"You can only use one operation per filter, you requested %d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sort is disabled. Please read the documentation at https://docs.oramasearch for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead.
Input vectors must be of the size declared in the schema, as calculating similarity between vectors of different sizes can lead to unexpected results.`,WRONG_SEARCH_PROPERTY_TYPE:'Property "%s" is not searchable. Only "string" properties are searchable.',FACET_NOT_SUPPORTED:`Facet doens't support the type "%s".`,INVALID_DISTANCE_SUFFIX:'Invalid distance suffix "%s". Valid suffixes are: cm, m, km, mi, yd, ft.',INVALID_SEARCH_MODE:'Invalid search mode "%s". Valid modes are: "fulltext", "vector", "hybrid".',MISSING_VECTOR_AND_SECURE_PROXY:"No vector was provided and no secure proxy was configured. Please provide a vector or configure an Orama Secure Proxy to perform hybrid search.",MISSING_TERM:'"term" is a required parameter when performing hybrid search. Please provide a search term.',INVALID_VECTOR_INPUT:'Invalid "vector" property. Expected an object with "value" and "property" properties, but got "%s" instead.',PLUGIN_CRASHED:"A plugin crashed during initialization. Please check the error message for more information:",PLUGIN_SECURE_PROXY_NOT_FOUND:`Could not find '@orama/secure-proxy-plugin' installed in your Orama instance.
Please install it before proceeding with creating an answer session.
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL:`Could not find a chat model defined in the secure proxy plugin configuration.
Please provide a chat model before proceeding with creating an answer session.
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages."};function bt(e,...t){let r=new Error(Ubt(fkr[e]??`Unsupported Orama Error code: ${e}`,...t));return r.code=e,"captureStackTrace"in Error.prototype&&Error.captureStackTrace(r),r}function Hbt(e){return{raw:Number(e),formatted:CR(e)}}function Vbt(e){if(e.id){if(typeof e.id!="string")throw bt("DOCUMENT_ID_MUST_BE_STRING",typeof e.id);return e.id}return R4()}function Nxe(e,t){for(let[r,n]of Object.entries(t)){let o=e[r];if(!(typeof o>"u")&&!(n==="geopoint"&&typeof o=="object"&&typeof o.lon=="number"&&typeof o.lat=="number")&&!(n==="enum"&&(typeof o=="string"||typeof o=="number"))){if(n==="enum[]"&&Array.isArray(o)){let i=o.length;for(let a=0;a<i;a++)if(typeof o[a]!="string"&&typeof o[a]!="number")return r+"."+a;continue}if($x(n)){let i=Fxe(n);if(!Array.isArray(o)||o.length!==i)throw bt("INVALID_INPUT_VECTOR",r,i,o.length);continue}if(HF(n)){if(!Array.isArray(o))return r;let i=Lxe(n),a=o.length;for(let s=0;s<a;s++)if(typeof o[s]!==i)return r+"."+s;continue}if(typeof n=="object"){if(!o||typeof o!="object")return r;let i=Nxe(o,n);if(i)return r+"."+i;continue}if(typeof o!==n)return r}}}var pkr={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},hkr={"string[]":"string","number[]":"number","boolean[]":"boolean","enum[]":"enum"};function Wbt(e){return e==="geopoint"}function $x(e){return typeof e=="string"&&/^vector\[\d+\]$/.test(e)}function HF(e){return typeof e=="string"&&pkr[e]}function Lxe(e){return hkr[e]}function Fxe(e){let t=Number(e.slice(7,-1));switch(!0){case isNaN(t):throw bt("INVALID_VECTOR_VALUE",e);case t<=0:throw bt("INVALID_VECTOR_SIZE",e);default:return t}}function Jbt(){return{idToInternalId:new Map,internalIdToId:[],save:mkr,load:gkr}}function mkr(e){return{internalIdToId:e.internalIdToId}}function gkr(e,t){let{internalIdToId:r}=t;e.internalDocumentIDStore.idToInternalId.clear(),e.internalDocumentIDStore.internalIdToId=[];let n=r.length;for(let o=0;o<n;o++){let i=r[o];e.internalDocumentIDStore.idToInternalId.set(i,o+1),e.internalDocumentIDStore.internalIdToId.push(i)}}function Fo(e,t){if(typeof t=="string"){let r=e.idToInternalId.get(t);if(r)return r;let n=e.idToInternalId.size+1;return e.idToInternalId.set(t,n),e.internalIdToId.push(t),n}return t>e.internalIdToId.length?Fo(e,t.toString()):t}function $h(e,t){if(e.internalIdToId.length<t)throw new Error(`Invalid internalId ${t}`);return e.internalIdToId[t-1]}function bkr(e,t){return{sharedInternalDocumentStore:t,docs:{},count:0}}function _kr(e,t){let r=Fo(e.sharedInternalDocumentStore,t);return e.docs[r]}function vkr(e,t){let r=t.length,n=Array.from({length:r});for(let o=0;o<r;o++){let i=Fo(e.sharedInternalDocumentStore,t[o]);n[o]=e.docs[i]}return n}function wkr(e){return e.docs}function Skr(e,t,r){let n=Fo(e.sharedInternalDocumentStore,t);return typeof e.docs[n]<"u"?!1:(e.docs[n]=r,e.count++,!0)}function xkr(e,t){let r=Fo(e.sharedInternalDocumentStore,t);return typeof e.docs[r]>"u"?!1:(delete e.docs[r],e.count--,!0)}function Ckr(e){return e.count}function Okr(e,t){let r=t;return{docs:r.docs,count:r.count,sharedInternalDocumentStore:e}}function Ekr(e){return{docs:e.docs,count:e.count}}function Gbt(){return{create:bkr,get:_kr,getMultiple:vkr,getAll:wkr,store:Skr,remove:xkr,count:Ckr,load:Okr,save:Ekr}}var Kbt=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeLoad","afterLoad","afterCreate"];function Ybt(e,t){let r=[],n=e.plugins?.length;if(!n)return r;for(let o=0;o<n;o++)try{let i=e.plugins[o];typeof i[t]=="function"&&r.push(i[t])}catch(i){throw console.error("Caught error in getAllPluginsByHook:",i),bt("PLUGIN_CRASHED")}return r}var Zbt=["tokenizer","index","documentsStore","sorter"],kxe=["validateSchema","getDocumentIndexId","getDocumentProperties","for
which is longer than the specified ${this.chunkSize}`),o.length>0)){let l=this.joinDocs(o,r);for(l!==null&&n.push(l);i>this.chunkOverlap||i+u+o.length*r.length>this.chunkSize&&i>0;)i-=await this.lengthFunction(o[0]),o.shift()}o.push(s),i+=u}let a=this.joinDocs(o,r);return a!==null&&n.push(a),n}};var TQ=class e extends dCe{static lc_name(){return"RecursiveCharacterTextSplitter"}constructor(t){super(t),Object.defineProperty(this,"separators",{enumerable:!0,configurable:!0,writable:!0,value:[`
`,`
`," ",""]}),this.separators=t?.separators??this.separators,this.keepSeparator=t?.keepSeparator??!0}async _splitText(t,r){let n=[],o=r[r.length-1],i;for(let l=0;l<r.length;l+=1){let c=r[l];if(c===""){o=c;break}if(t.includes(c)){o=c,i=r.slice(l+1);break}}let a=this.splitOnSeparator(t,o),s=[],u=this.keepSeparator?"":o;for(let l of a)if(await this.lengthFunction(l)<this.chunkSize)s.push(l);else{if(s.length){let c=await this.mergeSplits(s,u);n.push(...c),s=[]}if(!i)n.push(l);else{let c=await this._splitText(l,i);n.push(...c)}}if(s.length){let l=await this.mergeSplits(s,u);n.push(...l)}return n}async splitText(t){return this._splitText(t,this.separators)}static fromLanguage(t,r){return new e({...r,separators:e.getSeparatorsForLanguage(t)})}static getSeparatorsForLanguage(t){if(t==="cpp")return[`
class `,`
void `,`
int `,`
float `,`
double `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
`,`
`," ",""];if(t==="go")return[`
func `,`
var `,`
const `,`
type `,`
if `,`
for `,`
switch `,`
case `,`
`,`
`," ",""];if(t==="java")return[`
class `,`
public `,`
protected `,`
private `,`
static `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
`,`
`," ",""];if(t==="js")return[`
function `,`
const `,`
let `,`
var `,`
class `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
default `,`
`,`
`," ",""];if(t==="php")return[`
function `,`
class `,`
if `,`
foreach `,`
while `,`
do `,`
switch `,`
case `,`
`,`
`," ",""];if(t==="proto")return[`
message `,`
service `,`
enum `,`
option `,`
import `,`
syntax `,`
`,`
`," ",""];if(t==="python")return[`
class `,`
def `,`
def `,`
`,`
`," ",""];if(t==="rst")return[`
===
`,`
---
`,`
***
`,`
.. `,`
`,`
`," ",""];if(t==="ruby")return[`
def `,`
class `,`
if `,`
unless `,`
while `,`
for `,`
do `,`
begin `,`
rescue `,`
`,`
`," ",""];if(t==="rust")return[`
fn `,`
const `,`
let `,`
if `,`
while `,`
for `,`
loop `,`
match `,`
const `,`
`,`
`," ",""];if(t==="scala")return[`
class `,`
object `,`
def `,`
val `,`
var `,`
if `,`
for `,`
while `,`
match `,`
case `,`
`,`
`," ",""];if(t==="swift")return[`
func `,`
class `,`
struct `,`
enum `,`
if `,`
for `,`
while `,`
do `,`
switch `,`
case `,`
`,`
`," ",""];if(t==="markdown")return[`
## `,`
### `,`
#### `,`
##### `,`
###### `,"```\n\n",`
***
`,`
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
---
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
`,`
___
`,`
`,`
`," ",""];if(t==="latex")return[`
\\chapter{`,`
\\section{`,`
\\subsection{`,`
\\subsubsection{`,`
\\begin{enumerate}`,`
\\begin{itemize}`,`
\\begin{description}`,`
\\begin{list}`,`
\\begin{quote}`,`
\\begin{quotation}`,`
\\begin{verse}`,`
\\begin{verbatim}`,`
\\begin{align}`,"$$","$",`
`,`
`," ",""];if(t==="html")return["<body>","<div>","<p>","<br>","<li>","<h1>","<h2>","<h3>","<h4>","<h5>","<h6>","<span>","<table>","<tr>","<td>","<th>","<ul>","<ol>","<header>","<footer>","<nav>","<head>","<style>","<script>","<meta>","<title>"," ",""];if(t==="sol")return[`
pragma `,`
using `,`
contract `,`
interface `,`
library `,`
constructor `,`
type `,`
function `,`
event `,`
modifier `,`
error `,`
struct `,`
enum `,`
if `,`
for `,`
while `,`
do while `,`
assembly `,`
`,`
`," ",""];throw new Error(`Language ${t} is not supported.`)}};var Rw=require("obsidian");var MQ=class{constructor(t,r,n){this.app=t;this.dbOps=r;this.embeddingsManager=n;this.state={isIndexingPaused:!1,isIndexingCancelled:!1,indexedCount:0,totalFilesToIndex:0,processedFiles:new Set,currentIndexingNotice:null,indexNoticeMessage:null};let o=pe();this.rateLimiter=new B4(o.embeddingRequestsPerMin),this.embeddingBatchSize=o.embeddingBatchSize,this.checkpointInterval=8*this.embeddingBatchSize,sl(async()=>{let i=pe();this.rateLimiter=new B4(i.embeddingRequestsPerMin),this.embeddingBatchSize=i.embeddingBatchSize,this.checkpointInterval=8*this.embeddingBatchSize})}async indexVaultToVectorStore(t){let r=[];try{let n=await this.embeddingsManager.getEmbeddingsAPI();if(!n)return console.error("Embedding instance not found."),0;await this.dbOps.checkAndHandleEmbeddingModelChange(n)&&(t=!0),t?(await this.dbOps.clearIndex(n),this.dbOps.clearFilesMissingEmbeddings()):await this.dbOps.garbageCollect();let i=await this.getFilesToIndex(t);if(i.length===0)return new Rw.Notice("Copilot vault index is up-to-date."),0;this.initializeIndexingState(i.length),this.createIndexingNotice(),this.dbOps.clearFilesMissingEmbeddings();let a=await this.prepareAllChunks(i);if(a.length===0)return new Rw.Notice("No valid content to index."),0;for(let s=0;s<a.length&&!this.state.isIndexingCancelled;s+=this.embeddingBatchSize){await this.handlePause();let u=a.slice(s,s+this.embeddingBatchSize);try{await this.rateLimiter.wait();let l=await n.embedDocuments(u.map(f=>f.content));if(!l||l.length!==u.length)throw new Error(`Embedding model returned ${l?.length??0} embeddings for ${u.length} documents`);for(let f=0;f<u.length;f++){let p=u[f],h=l[f];if(!h||!Array.isArray(h)||h.length===0){Ur(`Invalid embedding for document ${p.fileInfo.path}: ${h}`),this.dbOps.markFileMissingEmbeddings(p.fileInfo.path);continue}try{await this.dbOps.upsert({...p.fileInfo,id:this.getDocHash(p.content),content:p.content,embedding:h,created_at:Date.now(),nchars:p.content.length}),this.state.processedFiles.add(p.fileInfo.path)}catch(m){this.handleError(m,{filePath:p.fileInfo.path,errors:r}),this.dbOps.markFileMissingEmbeddings(p.fileInfo.path);continue}}this.state.indexedCount=this.state.processedFiles.size,this.updateIndexingNoticeMessage();let c=Math.floor((this.state.indexedCount-u.length)/this.checkpointInterval);Math.floor(this.state.indexedCount/this.checkpointInterval)>c&&(await this.dbOps.saveDB(),console.log("Copilot index checkpoint save completed."))}catch(l){if(this.handleError(l,{filePath:u?.[0]?.fileInfo?.path,errors:r,batch:u}),this.isRateLimitError(l))break}}return this.finalizeIndexing(r),await this.dbOps.saveDB(),console.log("Copilot index final save completed."),this.dbOps.checkIndexIntegrity().catch(s=>{Ur("Background integrity check failed:",s)}),this.state.indexedCount}catch(n){return this.handleError(n),0}}async prepareAllChunks(t){let r=await this.embeddingsManager.getEmbeddingsAPI();if(!r)return console.error("Embedding instance not found."),[];let n=ps.getModelName(r),o=TQ.fromLanguage("markdown",{chunkSize:nBe}),i=[];for(let a of t){let s=await this.app.vault.cachedRead(a);if(!s?.trim())continue;let u=this.app.metadataCache.getFileCache(a),l={title:a.basename,path:a.path,embeddingModel:n,ctime:a.stat.ctime,mtime:a.stat.mtime,tags:u?.tags?.map(d=>d.tag)??[],extension:a.extension,metadata:{...u?.frontmatter??{},created:ll(new Date(a.stat.ctime)).display,modified:ll(new Date(a.stat.mtime)).display}};(await o.createDocuments([s],[],{chunkHeader:`
NOTE TITLE: [[${l.title}]]
METADATA:${JSON.stringify(l.metadata)}
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
NOTE BLOCK CONTENT:
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
`,appendChunkOverlapHeader:!0})).forEach(d=>{d.pageContent.trim()&&i.push({content:d.pageContent,fileInfo:l})})}return i}getDocHash(t){return(0,o0t.MD5)(t).toString()}async getFilesToIndex(t){let{inclusions:r,exclusions:n}=MR(),o=this.app.vault.getMarkdownFiles();if(t)return o.filter(c=>TP(c,r,n));let i=new Set(await this.dbOps.getIndexedFiles()),a=await this.dbOps.getLatestFileMtime(),s=new Set(this.dbOps.getFilesMissingEmbeddings()),u=new Set,l=new Set;for(let c of o){if(!TP(c,r,n))continue;let d=await this.app.vault.cachedRead(c);if(!d||d.trim().length===0){l.add(c.path);continue}let f=i.has(c.path),p=s.has(c.path);(!f||p||c.stat.mtime>a)&&u.add(c)}return br([`Files to index: ${u.size}`,`Previously indexed: ${i.size}`,`Empty files skipped: ${l.size}`,`Files missing embeddings: ${s.size}`].join(`
`)),Array.from(u)}initializeIndexingState(t){this.state={isIndexingPaused:!1,isIndexingCancelled:!1,indexedCount:0,totalFilesToIndex:t,processedFiles:new Set,currentIndexingNotice:null,indexNoticeMessage:null}}createIndexingNotice(){let t=document.createDocumentFragment(),r=t.createEl("div",{cls:"copilot-notice-container"});this.state.indexNoticeMessage=r.createEl("div",{cls:"copilot-notice-message"}),this.updateIndexingNoticeMessage();let n=r.createEl("div",{cls:"copilot-notice-buttons"}),o=n.createEl("button");o.textContent="Pause",o.addEventListener("click",a=>{a.stopPropagation(),a.preventDefault(),this.state.isIndexingPaused?(this.resumeIndexing(),o.textContent="Pause"):(this.pauseIndexing(),o.textContent="Resume")});let i=n.createEl("button");return i.textContent="Stop",i.style.marginLeft="8px",i.addEventListener("click",a=>{a.stopPropagation(),a.preventDefault(),this.cancelIndexing()}),t.appendChild(this.state.indexNoticeMessage),t.appendChild(n),this.state.currentIndexingNotice=new Rw.Notice(t,0),this.state.currentIndexingNotice}async handlePause(){if(this.state.isIndexingPaused){for(;this.state.isIndexingPaused&&!this.state.isIndexingCancelled;)await new Promise(t=>setTimeout(t,100));if(!this.state.isIndexingCancelled){let t=await this.getFilesToIndex();if(t.length===0){console.log("No files to index after filter change, stopping indexing"),this.cancelIndexing(),new Rw.Notice("No files to index with current filters");return}this.state.totalFilesToIndex=t.length,console.log("Total files to index:",this.state.totalFilesToIndex),console.log("Files to index:",t),this.updateIndexingNoticeMessage()}}}pauseIndexing(){this.state.isIndexingPaused=!0}resumeIndexing(){this.state.isIndexingPaused=!1}updateIndexingNoticeMessage(){if(this.state.indexNoticeMessage){let t=this.state.isIndexingPaused?" (Paused)":"",r=["Copilot is indexing your vault...",`${this.state.indexedCount}/${this.state.totalFilesToIndex} files processed${t}`],n=pe(),o=PP(n.qaInclusions);o.length>0&&r.push(`Inclusions: ${o.join(", ")}`);let a=[...OQ(this.app),...PP(n.qaExclusions)];a.length>0&&r.push(`Exclusions: ${a.join(", ")}`),this.state.indexNoticeMessage.textContent=r.join(`
`)}}isStringLengthError(t){if(!t)return!1;if(t instanceof RangeError&&t.message.toLowerCase().includes("string length"))return!0;let n=(t.message||t.toString()).toLowerCase();return n.includes("string length")||n.includes("rangeerror")}handleError(t,r){let n=r?.filePath;if(n?(r.batch?console.error("Batch processing error:",{error:t,batchSize:r.batch.length||0,firstChunk:r.batch[0]?{path:r.batch[0].fileInfo?.path,contentLength:r.batch[0].content?.length,hasFileInfo:!!r.batch[0].fileInfo}:"No chunks in batch",errorType:t?.constructor?.name,errorMessage:t?.message}):console.error(`Error indexing file ${n}:`,t),r.errors?.push(n)):console.error("Fatal error during indexing:",t),this.state.currentIndexingNotice&&this.state.currentIndexingNotice.hide(),this.isStringLengthError(t)){new Rw.Notice("Vault is too large for 1 partition, please increase the number of partitions in your Copilot QA settings!",1e4);return}if(this.isRateLimitError(t))return;let o=n?`Error indexing file ${n}. Check console for details.`:"Fatal error during indexing. Check console for details.";new Rw.Notice(o)}isRateLimitError(t){return t?.message?.includes?.("rate limit")||!1}finalizeIndexing(t){if(this.state.currentIndexingNotice&&this.state.currentIndexingNotice.hide(),this.state.isIndexingCancelled){new Rw.Notice("Indexing cancelled");return}t.length>0?new Rw.Notice(`Indexing completed with ${t.length} errors. Check console for details.`):new Rw.Notice("Indexing completed successfully!")}async reindexFile(t){try{let r=await this.embeddingsManager.getEmbeddingsAPI();if(!r)return;if(await this.dbOps.removeDocs(t.path),await this.dbOps.checkAndHandleEmbeddingModelChange(r)){await this.indexVaultToVectorStore(!0);return}let o=await this.prepareAllChunks([t]);if(o.length===0)return;let i=await r.embedDocuments(o.map(a=>a.content));for(let a=0;a<o.length;a++){let s=o[a];await this.dbOps.upsert({...s.fileInfo,id:this.getDocHash(s.content),content:s.content,embedding:i[a],created_at:Date.now(),nchars:s.content.length})}this.dbOps.markUnsavedChanges(),pe().debug&&console.log(`Reindexed file: ${t.path}`)}catch(r){this.handleError(r,{filePath:t.path})}}async cancelIndexing(){console.log("Indexing cancelled by user"),this.state.isIndexingCancelled=!0,await new Promise(t=>setTimeout(t,100)),this.state.currentIndexingNotice&&this.state.currentIndexingNotice.hide()}};var ma=class e{constructor(){this.embeddingsManager=ps.getInstance(),this.dbOps=new Ux(app),this.indexOps=new MQ(app,this.dbOps,this.embeddingsManager),this.eventHandler=new EQ(app,this.indexOps,this.dbOps),this.initializationPromise=this.initialize(),this.setupSettingsSubscription()}static getInstance(){return e.instance||(e.instance=new e),e.instance}setupSettingsSubscription(){this.lastKnownSettings={...pe()};let t=async()=>{let r=pe(),n=this.lastKnownSettings;if(this.lastKnownSettings={...r},r.enableIndexSync!==n?.enableIndexSync){let o=await this.dbOps.getDbPath();this.dbOps.getCurrentDbPath()!==o&&await this.dbOps.initializeDB(await this.embeddingsManager.getEmbeddingsAPI())}};sl(()=>{this.initializationPromise=t()})}async initialize(){try{let t=3;for(;t>0;)try{await this.dbOps.initializeDB(await this.embeddingsManager.getEmbeddingsAPI());break}catch(r){if(r instanceof dr&&r.message.includes("Vault adapter not available")&&(t--,t>0)){await new Promise(n=>setTimeout(n,100));continue}new $4.Notice("Failed to initialize vector store. Please make sure you have a valid API key for your embedding model and restart the plugin."),console.error("Failed to initialize vector store:",r);break}}catch(t){console.error("Failed to initialize vector store:",t)}}async waitForInitialization(){await this.initializationPromise}async indexVaultToVectorStore(t){return await this.waitForInitialization(),$4.Platform.isMobile&&pe().disableIndexOnMobile?(new $4.Notice("Indexing is disabled on mobile devices"),0):this.indexOps.indexVaultToVectorStore(t)}async clearIndex(){await this.waitForInitialization(),await this.dbOps.clearIndex(await this.embeddingsManager.getEmbeddingsAPI())}async garbageCollectVectorStore(){return aw
`);o.enqueue(s)}catch(i){o.error(i)}},async cancel(){await r.return?.()}})}};async function*s$r(e,t){if(!e.body)throw t.abort(),new zr("Attempted to iterate over a response with no body");let r=new vCe,n=new QF,o=m0t(e.body);for await(let i of u$r(o))for(let a of n.decode(i)){let s=r.decode(a);s&&(yield s)}for(let i of n.flush()){let a=r.decode(i);a&&(yield a)}}async function*u$r(e){let t=new Uint8Array;for await(let r of e){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?new TextEncoder().encode(r):r,o=new Uint8Array(t.length+n.length);o.set(t),o.set(n,t.length),t=o;let i;for(;(i=l$r(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}function l$r(e){for(let n=0;n<e.length-2;n++){if(e[n]===10&&e[n+1]===10||e[n]===13&&e[n+1]===13)return n+2;if(e[n]===13&&e[n+1]===10&&n+3<e.length&&e[n+2]===13&&e[n+3]===10)return n+4}return-1}var vCe=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(t){if(t.endsWith("\r")&&(t=t.substring(0,t.length-1)),!t){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(t),t.startsWith(":"))return null;let[r,n,o]=c$r(t,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},QF=class e{constructor(){this.buffer=[],this.trailingCR=!1}decode(t){let r=this.decodeText(t);if(this.trailingCR&&(r="\r"+r,this.trailingCR=!1),r.endsWith("\r")&&(this.trailingCR=!0,r=r.slice(0,-1)),!r)return[];let n=e.NEWLINE_CHARS.has(r[r.length-1]||""),o=r.split(e.NEWLINE_REGEXP);return n&&o.pop(),o.length===1&&!n?(this.buffer.push(o[0]),[]):(this.buffer.length>0&&(o=[this.buffer.join("")+o[0],...o.slice(1)],this.buffer=[]),n||(this.buffer=[o.pop()||""]),o)}decodeText(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof Buffer<"u"){if(t instanceof Buffer)return t.toString();if(t instanceof Uint8Array)return Buffer.from(t).toString();throw new zr(`Unexpected: received non-Uint8Array (${t.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(t instanceof Uint8Array||t instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(t);throw new zr(`Unexpected: received non-Uint8Array/ArrayBuffer (${t.constructor.name}) in a web platform. Please report this error.`)}throw new zr("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let t=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,t}};QF.NEWLINE_CHARS=new Set([`
`,"\r"]);QF.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function c$r(e,t){let r=e.indexOf(t);return r!==-1?[e.substring(0,r),t,e.substring(r+t.length)]:[e,"",""]}function m0t(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var d$r=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function",f$r=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&q4(e),q4=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function";async function g0t(e,t,r){if(e=await e,f$r(e))return e;if(d$r(e)){let o=await e.blob();t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=q4(o)?[await o.arrayBuffer()]:[o];return new RQ(i,t,r)}let n=await p$r(e);if(t||(t=m$r(e)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new RQ(n,t,r)}async function p$r(e){let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(q4(e))t.push(await e.arrayBuffer());else if(g$r(e))for await(let r of e)t.push(r);else throw new Error(`Unexpected data type: ${typeof e}; constructor: ${e?.constructor?.name}; props: ${h$r(e)}`);return t}function h$r(e){return`[${Object.getOwnPropertyNames(e).map(r=>`"${r}"`).join(", ")}]`}function m$r(e){return SCe(e.name)||SCe(e.filename)||SCe(e.path)?.split(/[\\/]/).pop()}var SCe=e=>{if(typeof e=="string")return e;if(typeof Buffer<"u"&&e instanceof Buffer)return String(e)},g$r=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function",xCe=e=>e&&typeof e=="object"&&e.body&&e[Symbol.toStringTag]==="MultipartBody";var b$r=function(e,t,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r},_$r=function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},NQ;async function S0t(e){let{response:t}=e;if(e.options.stream)return ek("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):Dw.fromSSEResponse(t,e.controller);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let r=t.headers.get("content-type");if(r?.includes("application/json")||r?.includes("application/vnd.api+json")){let i=await t.json();return ek("response",t.status,t.url,t.headers,i),i}let o=await t.text();return ek("response",t.status,t.url,t.headers,o),o}var LQ=class e extends Promise{constructor(t,r=S0t){super(n=>{n(null)}),this.responsePromise=t,this.parseResponse=r}_thenUnwrap(t){return new e(this.responsePromise,async r=>t(await this.parseResponse(r)))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){let[t,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:r}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(t,r){return this.parse().then(t,r)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}},FQ=class{constructor({baseURL:t,maxRetries:r=2,timeout:n=6e5,httpAgent:o,fetch:i}){this.baseURL=t,this.maxRetries=CCe("maxRetries",r),this.timeout=CCe("timeout",n),this.httpAgent=o,this.fetch=i??yCe}authHeaders(t){return{}}defaultHeaders(t){return{Accept:"application/json","Content-Type":"application/json","User
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:t,timeout:this._client._options.timeout??6e5,...r,stream:t.stream??!1})}stream(t,r){return QQ.createMessage(this,t,r)}},I0t={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024"};DP||(DP={});var A0t,ei=class extends FQ{constructor({baseURL:t=BQ("ANTHROPIC_BASE_URL"),apiKey:r=BQ("ANTHROPIC_API_KEY")??null,authToken:n=BQ("ANTHROPIC_AUTH_TOKEN")??null,...o}={}){let i={apiKey:r,authToken:n,...o,baseURL:t||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&x0t())throw new zr(`It looks like you're running in a browser-like environment.
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
TODO: link!
`);super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new AP(this),this.messages=new DP(this),this.beta=new IP(this),this._options=i,this.apiKey=r,this.authToken=n}defaultQuery(){return this._options.defaultQuery}defaultHeaders(t){return{...super.defaultHeaders(t),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01",...this._options.defaultHeaders}}validateHeaders(t,r){if(!(this.apiKey&&t["x-api-key"])&&r["x-api-key"]!==null&&!(this.authToken&&t.authorization)&&r.authorization!==null)throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}authHeaders(t){let r=this.apiKeyAuth(t),n=this.bearerAuth(t);return r!=null&&!$Q(r)?r:n!=null&&!$Q(n)?n:{}}apiKeyAuth(t){return this.apiKey==null?{}:{"X-Api-Key":this.apiKey}}bearerAuth(t){return this.authToken==null?{}:{Authorization:`Bearer ${this.authToken}`}}};A0t=ei;ei.Anthropic=A0t;ei.HUMAN_PROMPT=`
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
Human:`;ei.AI_PROMPT=`
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
Assistant:`;ei.DEFAULT_TIMEOUT=6e5;ei.AnthropicError=zr;ei.APIError=Yu;ei.APIConnectionError=Hx;ei.APIConnectionTimeoutError=RR;ei.APIUserAbortError=vl;ei.NotFoundError=ok;ei.ConflictError=ik;ei.RateLimitError=sk;ei.BadRequestError=tk;ei.AuthenticationError=rk;ei.InternalServerError=uk;ei.PermissionDeniedError=nk;ei.UnprocessableEntityError=ak;ei.toFile=g0t;ei.fileFromPath=DQ;var{HUMAN_PROMPT:kCo,AI_PROMPT:BCo}=ei,{AnthropicError:$Co,APIError:qCo,APIConnectionError:UCo,APIConnectionTimeoutError:zCo,APIUserAbortError:HCo,NotFoundError:VCo,ConflictError:WCo,RateLimitError:JCo,BadRequestError:GCo,AuthenticationError:KCo,InternalServerError:YCo,PermissionDeniedError:ZCo,UnprocessableEntityError:XCo}=ECe;(function(e){e.Completions=AP,e.Messages=DP,e.Beta=IP})(ei||(ei={}));kh();Dx();oh();IS();SO();var Y4=class extends zM{static lc_name(){return"AnthropicToolsOutputParser"}constructor(t){super(t),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","anthropic","output_parsers"]}),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"keyName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"returnSingle",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"zodSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){let r=t;if(typeof t=="string")try{r=JSON.parse(t)}catch(o){throw new ep(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(o.message)}`,t)}else r=t;if(this.zodSchema===void 0)return r;let n=await this.zodSchema.safeParseAsync(r);if(n.success)return n.data;throw new ep(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(n.error.errors)}`,JSON.stringify(r,null,2))}async parseResult(t){let r=t.flatMap(i=>{let{message:a}=i;return Array.isArray(a.content)?FCe(a.content)[0]:[]});if(r[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");let[n]=r;return await this._validateResult(n.args)}};function FCe(e){let t=[];for(let r of e)r.type==="tool_use"&&t.push({name:r.name,args:r.input,id:r.id,type:"tool_call"});return t}function R0t(e){if(e)return e==="any"?{type:"any"}:e==="auto"?{type:"auto"}:typeof e=="string"?{type:"tool",name:e}:e}function D0t(e){let t,r=Array.isArray(e.content)?e.content.find(o=>o.type==="tool_use"):void 0;r&&"index"in r&&"name"in r&&"id"in r&&(t={args:"",id:r.id,name:r.name,index:r.index,type:"tool_call_chunk"});let n=Array.isArray(e.content)?e.content.find(o=>o.type==="input_json_delta"):void 0;return n&&"index"in n&&"input"in n&&(typeof n.input=="string"?t={id:n.id,name:n.name,args:n.input,index:n.index,type:"tool_call_chunk"}:t={id:n.id,name:n.name,args:JSON.stringify(n.input,null,2),index:n.index,type:"tool_call_chunk"}),t}function j0t(e){let t=/^data:(image\/.+);base64,(.+)$/,r=e.match(t);if(r===null)throw new Error(["Anthropic only supports base64-encoded images currently.","Example: data:image/png;base64,/9j/4AAQSk..."].join(`
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
`));return{type:"base64",media_type:r[1]??"",data:r[2]??""}}function L$r(e){let t=[];for(let r of e)if(r._getType()==="tool")if(typeof r.content=="string"){let n=t[t.length-1];n?._getType()==="human"&&Array.isArray(n.content)&&"type"in n.content[0]&&n.content[0].type==="tool_result"?n.content.push({type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}):t.push(new Ua({content:[{type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}]}))}else t.push(new Ua({content:r.content}));else{let n=t[t.length-1];if(n?._getType()==="human"&&r._getType()==="human"){let o;typeof n.content=="string"?o=[{type:"text",text:n.content}]:o=n.content,typeof r.content=="string"?o.push({type:"text",text:r.content}):o=o.concat(r.content),n.content=o}else t.push(r)}return t}function N0t(e){if(e.id===void 0)throw new Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:e.id,name:e.name,input:e.args}}function L0t(e){let t=["tool_use","tool_result","input_json_delta"],r=["text","text_delta"];return typeof e=="string"?e:e.map(o=>{let i="cache_control"in o?o.cache_control:void 0;if(o.type==="image_url"){let a;return typeof o.image_url=="string"?a=j0t(o.image_url):a=j0t(o.image_url.url),{type:"image",source:a,...i?{cache_control:i}:{}}}else{if(r.find(a=>a===o.type)&&"text"in o)return{type:"text",text:o.text,...i?{cache_control:i}:{}};if(t.find(a=>a===o.type)){let a={...o};if("index"in a&&delete a.index,a.type==="input_json_delta"&&(a.type="tool_use"),"input"in a)try{a.input=JSON.parse(a.input)}catch{}return{...a,...i?{cache_control:i}:{}}}else throw new Error("Unsupported message content format")}})}function eee(e){let t=L$r(e),r;return t.length>0&&t[0]._getType()==="system"&&(r=e[0].content),{messages:(r!==void 0?t.slice(1):t).map(i=>{let a;if(i._getType()==="human")a="user";else if(i._getType()==="ai")a="assistant";else if(i._getType()==="tool")a="user";else throw i._getType()==="system"?new Error("System messages are only permitted as the first passed message."):new Error(`Message type "${i._getType()}" is not supported.`);if(Fu(i)&&i.tool_calls?.length){if(typeof i.content=="string")return i.content===""?{role:a,content:i.tool_calls.map(N0t)}:{role:a,content:[{type:"text",text:i.content},...i.tool_calls.map(N0t)]};{let{content:s}=i;return!i.tool_calls.every(l=>s.find(c=>(c.type==="tool_use"||c.type==="input_json_delta")&&c.id===l.id))&&console.warn('The "tool_calls" field on a message is only respected if content is a string.'),{role:a,content:L0t(i.content)}}}else return{role:a,content:L0t(i.content)}}),system:r}}function F0t(e,t){if(e.type==="message_start"){let{content:r,usage:n,...o}=e.message,i={};for(let[s,u]of Object.entries(o))u!=null&&(i[s]=u);let a={input_tokens:n.input_tokens,output_tokens:n.output_tokens,total_tokens:n.input_tokens+n.output_tokens};return{chunk:new Jr({content:t.coerceContentToString?"":[],additional_kwargs:i,usage_metadata:t.streamUsage?a:void 0,id:e.message.id})}}else if(e.type==="message_delta"){let r={input_tokens:0,output_tokens:e.usage.output_tokens,total_tokens:e.usage.output_tokens};return{chunk:new Jr({content:t.coerceContentToString?"":[],additional_kwargs:{...e.delta},usage_metadata:t.streamUsage?r:void 0})}}else{if(e.type==="content_block_start"&&e.content_block.type==="tool_use")return{chunk:new Jr({content:t.coerceContentToString?"":[{index:e.index,...e.content_block,input:""}],additional_kwargs:{}})};if(e.type==="content_block_delta"&&e.delta.type==="text_delta"){let r=e.delta?.text;if(r!==void 0)return{chunk:new Jr({content:t.coerceContentToString?r:[{index:e.index,...e.delta}],additional_kwargs:{}})}}else{if(e.type==="content_block_delta"&&e.delta.type==="input_json_delta")return{chunk:new Jr({content:t.coerceContentToString?"":[{index:e.index,input:e.delta.partial_json,type:e.delta.type}],additional_kwargs:{}})};if(e.type==="content_block_start"&&e.content_block.type==="text"){let r=e.content_block?.text;if(r!==void 0)return{chunk:new Jr({content:t.coerceContentToString?r:[{index:e.index,...e.content_block}],additional_kwargs:{}})}}}}return null}func
`);o.enqueue(s)}catch(i){o.error(i)}},async cancel(){await r.return?.()}})}},WCe=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(t){if(t.endsWith("\r")&&(t=t.substring(0,t.length-1)),!t){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(t),t.startsWith(":"))return null;let[r,n,o]=V$r(t,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},vk=class e{constructor(){this.buffer=[],this.trailingCR=!1}decode(t){let r=this.decodeText(t);if(this.trailingCR&&(r="\r"+r,this.trailingCR=!1),r.endsWith("\r")&&(this.trailingCR=!0,r=r.slice(0,-1)),!r)return[];let n=e.NEWLINE_CHARS.has(r[r.length-1]||""),o=r.split(e.NEWLINE_REGEXP);return o.length===1&&!n?(this.buffer.push(o[0]),[]):(this.buffer.length>0&&(o=[this.buffer.join("")+o[0],...o.slice(1)],this.buffer=[]),n||(this.buffer=[o.pop()||""]),o)}decodeText(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof Buffer<"u"){if(t instanceof Buffer)return t.toString();if(t instanceof Uint8Array)return Buffer.from(t).toString();throw new wl(`Unexpected: received non-Uint8Array (${t.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(t instanceof Uint8Array||t instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(t);throw new wl(`Unexpected: received non-Uint8Array/ArrayBuffer (${t.constructor.name}) in a web platform. Please report this error.`)}throw new wl("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let t=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,t}};vk.NEWLINE_CHARS=new Set([`
`,"\r","\v","\f","","","","\x85","\u2028","\u2029"]);vk.NEWLINE_REGEXP=/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g;function V$r(e,t){let r=e.indexOf(t);return r!==-1?[e.substring(0,r),t,e.substring(r+t.length)]:[e,"",""]}function U0t(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var z0t=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function",H0t=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&see(e),see=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",W$r=e=>H0t(e)||z0t(e)||HCe(e);async function KCe(e,t,r){if(e=await e,r??(r=H0t(e)?{lastModified:e.lastModified,type:e.type}:{}),z0t(e)){let o=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file"),new ree([o],t,r)}let n=await J$r(e);if(t||(t=K$r(e)??"unknown_file"),!r.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new ree(n,t,r)}async function J$r(e){let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(see(e))t.push(await e.arrayBuffer());else if(Y$r(e))for await(let r of e)t.push(r);else throw new Error(`Unexpected data type: ${typeof e}; constructor: ${e?.constructor?.name}; props: ${G$r(e)}`);return t}function G$r(e){return`[${Object.getOwnPropertyNames(e).map(r=>`"${r}"`).join(", ")}]`}function K$r(e){return JCe(e.name)||JCe(e.filename)||JCe(e.path)?.split(/[\\/]/).pop()}var JCe=e=>{if(typeof e=="string")return e;if(typeof Buffer<"u"&&e instanceof Buffer)return String(e)},Y$r=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function",YCe=e=>e&&typeof e=="object"&&e.body&&e[Symbol.toStringTag]==="MultipartBody";var Z4=async e=>{let t=await V0t(e.body);return UCe(t,e)},V0t=async e=>{let t=new $Ce;return await Promise.all(Object.entries(e||{}).map(([r,n])=>GCe(t,r,n))),t};var GCe=async(e,t,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")e.append(t,String(r));else if(W$r(r)){let n=await KCe(r);e.append(t,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>GCe(e,t+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>GCe(e,`${t}[${n}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var X$r=function(e,t,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r},Q$r=function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},uee;async function Z0t(e){let{response:t}=e;if(e.options.stream)return wk("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):aee.fromSSEResponse(t,e.controller);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let r=t.headers.get("content-type");if(r?.includes("application/json")||r?.includes("application/vnd.api+json")){let i=await t.json();return wk("response",t.status,t.url,t.headers,i),i}let o=await t.text();return wk("response",t.status,t.url,t.headers,o),o}var lee=class e extends Promise{constructor(t
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
new Groq({ apiKey, dangerouslyAllowBrowser: true })`);super({baseURL:o.baseURL,timeout:o.timeout??6e4,httpAgent:o.httpAgent,maxRetries:o.maxRetries,fetch:o.fetch}),this.completions=new FP(this),this.chat=new LP(this),this.embeddings=new kP(this),this.audio=new NP(this),this.models=new BP(this),this._options=o,this.apiKey=r}defaultQuery(){return this._options.defaultQuery}defaultHeaders(t){return{...super.defaultHeaders(t),...this._options.defaultHeaders}}authHeaders(t){return{Authorization:`Bearer ${this.apiKey}`}}};Q0t=ja;ja.Groq=Q0t;ja.GroqError=wl;ja.APIError=Zu;ja.APIConnectionError=Jx;ja.APIConnectionTimeoutError=FR;ja.APIUserAbortError=jP;ja.NotFoundError=mk;ja.ConflictError=gk;ja.RateLimitError=bk;ja.BadRequestError=fk;ja.AuthenticationError=pk;ja.InternalServerError=_k;ja.PermissionDeniedError=hk;ja.UnprocessableEntityError=yk;ja.toFile=KCe;ja.fileFromPath=nee;var{GroqError:CEo,APIError:OEo,APIConnectionError:EEo,APIConnectionTimeoutError:PEo,APIUserAbortError:TEo,NotFoundError:MEo,ConflictError:IEo,RateLimitError:AEo,BadRequestError:REo,AuthenticationError:DEo,InternalServerError:jEo,PermissionDeniedError:NEo,UnprocessableEntityError:LEo}=VCe;(function(e){e.Completions=FP,e.Chat=LP,e.Embeddings=kP,e.Audio=NP,e.Models=BP})(ja||(ja={}));var ewt=ja;IS();SO();function gqr(e){let t=e._getType();switch(t){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";default:throw new Error(`Unknown message type: ${t}`)}}function twt(e){return e.map(t=>{if(typeof t.content!="string")throw new Error("Non string message content not supported");let r={role:gqr(t),content:t.content,name:t.name,function_call:t.additional_kwargs.function_call,tool_calls:t.additional_kwargs.tool_calls,tool_call_id:t.tool_call_id};return Fu(t)&&t.tool_calls?.length?r.tool_calls=t.tool_calls.map(BF):(t.additional_kwargs.tool_calls!=null&&(r.tool_calls=t.additional_kwargs.tool_calls),t.tool_call_id!=null&&(r.tool_call_id=t.tool_call_id)),r})}function yqr(e,t){let r=e.tool_calls;switch(e.role){case"assistant":{let n=[],o=[];for(let i of r??[])try{n.push(wR(i,{returnId:!0}))}catch(a){o.push($F(i,a.message))}return new Po({content:e.content||"",additional_kwargs:{tool_calls:r},tool_calls:n,invalid_tool_calls:o,usage_metadata:t})}default:return new xd(e.content||"",e.role??"unknown")}}function bqr(e,t){if(e?.length)return e.map(r=>({id:r.id,name:r.function?.name,args:r.function?.arguments,type:"tool_call_chunk",index:t}))}function _qr(e,t,r){let{role:n}=e,o=e.content??"",i;e.function_call?i={function_call:e.function_call}:e.tool_calls?i={tool_calls:e.tool_calls}:i={};let a,s;if(r?.usage&&(a={input_tokens:r.usage.prompt_tokens,output_tokens:r.usage.completion_tokens,total_tokens:r.usage.total_tokens},s=r.id),n==="user")return{message:new jm({content:o})};if(n==="assistant"){let u=bqr(e.tool_calls,t);return{message:new Jr({content:o,additional_kwargs:i,tool_call_chunks:u?u.map(l=>({type:l.type,args:l.args,index:l.index})):void 0,usage_metadata:a,id:s}),toolCallData:u?u.map(l=>({id:l.id??"",name:l.name??"",index:l.index??t,type:"tool_call_chunk"})):void 0}}else return n==="system"?{message:new ry({content:o})}:{message:new Dm({content:o,role:n})}}var dee=class extends Qc{static lc_name(){return"ChatGroq"}_llmType(){return"groq"}get lc_secrets(){return{apiKey:"GROQ_API_KEY"}}constructor(t){super(t??{}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","chat_models","groq"]}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"modelName",{enumerable:!0,configurable:!0,writable:!0,value:"mixtral-8x7b-32768"}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"mixtral-8x7b-32768"}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:.7}),Object.defineProperty(this,"stop",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stopSequences",{enumerable:!0,confi
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
Received: ${JSON.stringify(o,null,2)}`)};if(typeof o=="string")return o;if(Array.isArray(o)){let s=t(i),u=[];return o.forEach(l=>{if(l.type==="text"||l.type==="image_url")u.push(a(l,s));else throw new Error('Mistral only supports types "text" or "image_url" for complex message types.')}),u}throw new Error(`Message content must be a string or an array.
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
Received: ${JSON.stringify(o,null,2)}`)},n=o=>{if(Fu(o)&&o.tool_calls?.length)return o.tool_calls.map(i=>({...i,id:$Pe(i.id??"")})).map(BF)};return e.map(o=>{let i=n(o),a=r(o.content,o.getType());return"tool_call_id"in o&&typeof o.tool_call_id=="string"?{role:t(o.getType()),content:a,name:o.name,toolCallId:$Pe(o.tool_call_id)}:Fu(o)?i===void 0?{role:t(o.getType()),content:a}:{role:t(o.getType()),toolCalls:i}:{role:t(o.getType()),content:a}})}function Ern(e,t){let{message:r}=e;if(r===void 0)throw new Error("No message found in response");let n=[];"toolCalls"in r&&Array.isArray(r.toolCalls)&&(n=r.toolCalls);let o=qPe(r.content);switch(r.role){case"assistant":{let i=[],a=[];for(let s of n)try{let u=wR(s,{returnId:!0});i.push({...u,id:u.id??hee().replace(/-/g,"")})}catch(u){a.push($F(s,u.message))}return new Po({content:o,tool_calls:i,invalid_tool_calls:a,additional_kwargs:{},usage_metadata:t?{input_tokens:t.promptTokens,output_tokens:t.completionTokens,total_tokens:t.totalTokens}:void 0})}default:return new Ua({content:o})}}function Prn(e,t){if(!e.content&&!e.toolCalls)return t?new Jr({content:"",usage_metadata:t?{input_tokens:t.promptTokens,output_tokens:t.completionTokens,total_tokens:t.totalTokens}:void 0}):null;let r=e.toolCalls?.length?e.toolCalls?.map((s,u)=>({...s,index:u,id:s.id??hee().replace(/-/g,""),type:"function"})):void 0,n="assistant";e.role&&(n=e.role);let o=qPe(e.content),i,a=[];if(r!==void 0)for(let s of r){let u=s.function?.arguments,l=u===void 0||typeof u=="string"?u:JSON.stringify(u);a.push({name:s.function?.name,args:l,id:s.id,index:s.index,type:"tool_call_chunk"})}else i={};return n==="user"?new jm({content:o}):n==="assistant"?new Jr({content:o,tool_call_chunks:a,additional_kwargs:i,usage_metadata:t?{input_tokens:t.promptTokens,output_tokens:t.completionTokens,total_tokens:t.totalTokens}:void 0}):n==="tool"?new mO({content:o,additional_kwargs:i,tool_call_id:r?.[0].id??""}):n==="function"?new wS({content:o,additional_kwargs:i}):new Dm({content:o,role:n})}function lAt(e){return e.map(t=>{if("function"in t)return t;let r=t.description??`Tool: ${t.name}`;return{type:"function",function:{name:t.name,description:r,parameters:Li(t.schema)}}})}var vne=class extends Qc{static lc_name(){return"ChatMistralAI"}constructor(t){super(t??{}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","chat_models","mistralai"]}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"mistral-small-latest"}),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"endpoint",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serverURL",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:.7}),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"safeMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"safePrompt",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"randomSeed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"seed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"streamUsage",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"beforeRequestHooks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"requestErrorHooks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"r
without CORS Error: `+bi(n)+`
with CORS Error: `+bi(o);throw new Error(i)}}}findModelByName(t){return pe().activeModels.find(n=>n.name===t)}};async function Sne(e,t){let r=`Given the following conversation and a follow up question,
summarize the conversation as context and keep the follow up question unchanged, in its original language.
If the follow up question is unrelated to its preceding messages, return this follow up question directly.
If it is related, then combine the summary and the follow up question to construct a standalone question.
Make sure to keep any [[]] wrapped note titles in the question unchanged.
If there's nothing in the chat history, just return the follow up question.
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
Chat History:
{chat_history}
Follow Up Input: {question}
Standalone question:`,n=t.map(([a,s])=>`Human: ${a}
Assistant: ${s}`).join(`
`),i=await Ud.getInstance().getChatModel().bind({temperature:0}).invoke([{role:"user",content:r.replace("{chat_history}",n).replace("{question}",e)}]);return aj(i.content)}var UPe=require("obsidian"),pAt=e=>{switch(e){case"@vault":return"Search through your vault for relevant information";case"@web":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";default:return""}},Kk=class{static async callTool(t,r){try{if(!t)throw new Error("Tool is undefined");let n=await t.call(r);return n??(console.warn(`Tool ${t.name} returned null/undefined result`),null)}catch(n){return console.error("Error calling tool:",n),n instanceof Error?new UPe.Notice(n.message):new UPe.Notice("An error occurred while executing the tool. Check console for details."),null}}};var M1t=require("obsidian");GM();bO();sf();ny();var xne=class extends nn{constructor(t){super(t),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.callbacks=t?.callbacks,this.tags=t?.tags??[],this.metadata=t?.metadata??{},this.verbose=t?.verbose??!1}_getRelevantDocuments(t,r){throw new Error("Not implemented!")}async invoke(t,r){return this.getRelevantDocuments(t,Rr(r))}async getRelevantDocuments(t,r){let n=Rr(qM(r)),i=await(await ns.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),t,n.runId,void 0,void 0,void 0,n.runName);try{let a=await this._getRelevantDocuments(t,i);return await i?.handleRetrieverEnd(a),a}catch(a){throw await i?.handleRetrieverError(a),a}}};var oT=class extends xne{constructor(r){super();this.options=r;this.lc_namespace=["hybrid_retriever"];this.queryRewritePrompt=ah.fromTemplate(`Please write a passage to answer the question. If you don't know the answer, just make up a passage.
Question: {question}
Passage:`)}async getRelevantDocuments(r,n){let o=ly(r,app.vault),i=o.map(m=>m.basename),a=[...new Set([...this.options.salientTerms,...i])],s=await this.getExplicitChunks(o),u=r;n?.runName!=="no_hyde"&&(u=await this.rewriteQuery(r));let l=await this.getOramaChunks(u,a,this.options.textWeight),c=this.filterAndFormatChunks(l,s),d=c;if(c.length===0)return pe().debug&&console.log("No chunks found for query:",r),d;let f=c.reduce((m,_)=>{let g=_.metadata.score;return typeof g=="number"&&!isNaN(g)?Math.max(m,g):m},0),p=c.every(m=>typeof m.metadata.score!="number"||isNaN(m.metadata.score)),h=this.options.useRerankerThreshold&&(f<this.options.useRerankerThreshold||p);return h&&(d=(await _l.getInstance().rerank(r,c.map(_=>_.pageContent.slice(0,3e3)))).response.data.map(_=>({...c[_.index],metadata:{...c[_.index].metadata,rerank_score:_.relevance_score}}))),pe().debug&&(console.log("*** HYBRID RETRIEVER DEBUG INFO: ***"),n?.runName!=="no_hyde"&&(console.log(`
Original Query: `,r),console.log("Rewritten Query: ",u)),console.log(`
Explicit Chunks: `,s),console.log("Orama Chunks: ",l),console.log("Combined Chunks: ",c),console.log("Max Orama Score: ",f),h?console.log("Reranked Chunks: ",d):console.log("No reranking applied.")),d}async rewriteQuery(r){try{let n=await this.queryRewritePrompt.format({question:r}),i=await Ud.getInstance().getChatModel().bind({temperature:0}).invoke(n);return i&&"content"in i?aj(i.content):(console.warn("Unexpected rewrittenQuery format. Falling back to original query."),r)}catch(n){return console.error("Error in rewriteQuery:",n),r}}async getExplicitChunks(r){let n=[];for(let o of r){let i=await ma.getInstance().getDb(),a=await Ux.getDocsByPath(i,o.path);if(a){let s=a.map(u=>new zx({pageContent:u.document.content,metadata:{...u.document.metadata,score:u.score,path:u.document.path,mtime:u.document.mtime,ctime:u.document.ctime,title:u.document.title,id:u.document.id,embeddingModel:u.document.embeddingModel,tags:u.document.tags,extension:u.document.extension,created_at:u.document.created_at,nchars:u.document.nchars}}));n.push(...s)}}return n}async getOramaChunks(r,n,o){let i;try{i=await this.convertQueryToVector(r)}catch(l){throw console.error("Error in convertQueryToVector, please ensure your embedding model is working and has an adequate context length:",l,`
Query:`,r),l}let a=await ma.getInstance().getDb(),s={similarity:this.options.minSimilarityScore,limit:this.options.maxK,includeVectors:!0};if(n.length>0){let l;o||(o=.5),l=1-o;let c=!0;for(let d of n)if(!d.startsWith("#")){c=!1;break}c&&(pe().debug&&console.log("Tag only query detected, setting textWeight to 1 and vectorWeight to 0."),o=1,l=0),s.mode="hybrid",s.term=n.join(" "),s.vector={value:i,property:"embedding"},s.hybridWeights={text:o,vector:l}}else s.mode="vector",s.vector={value:i,property:"embedding"};if(this.options.timeRange){let{startTime:l,endTime:c}=this.options.timeRange,d=this.generateDailyNoteDateRange(l,c);br("==== Daily note date range: ====",d[0],d[d.length-1]);let f=ly(d.join(", "),app.vault),h=(await this.getExplicitChunks(f)).map(S=>({...S,metadata:{...S.metadata,includeInContext:!0}}));br("==== Modified time range: ====",l,c),s.where={mtime:{between:[l,c]}};let _=(await ic(a,s)).hits.map(S=>new zx({pageContent:S.document.content,metadata:{...S.document.metadata,score:S.score,path:S.document.path,mtime:S.document.mtime,ctime:S.document.ctime,title:S.document.title,id:S.document.id,embeddingModel:S.document.embeddingModel,tags:S.document.tags,extension:S.document.extension,created_at:S.document.created_at,nchars:S.document.nchars}})),g=[...h,..._];return Array.from(new Set(g.map(S=>S.metadata.id))).map(S=>g.find(x=>x.metadata.id===S)).filter(S=>S!==void 0)}pe().debug&&console.log(`==== Orama Search Params: ====
`,s);let u=await ic(a,s);return!u||!u.hits?(console.warn("Search results or hits are undefined"),[]):u.hits.map(l=>!l||!l.document?(console.warn("Invalid hit or document in search results"),null):((typeof l.score!="number"||isNaN(l.score))&&console.warn("NaN/invalid score detected:",{score:l.score,path:l.document.path,title:l.document.title}),new zx({pageContent:l.document.content||"",metadata:{...l.document.metadata||{},score:l.score,path:l.document.path||"",mtime:l.document.mtime,ctime:l.document.ctime,title:l.document.title||"",id:l.document.id,embeddingModel:l.document.embeddingModel,tags:l.document.tags||[],extension:l.document.extension,created_at:l.document.created_at,nchars:l.document.nchars}}))).filter(l=>l!==null)}async convertQueryToVector(r){let o=await(await ps.getInstance().getEmbeddingsAPI()).embedQuery(r);if(o.length===0)throw new Error("Query embedding returned an empty vector");return o}generateDailyNoteDateRange(r,n){let o=[],i=new Date(r),a=new Date(n),s=new Date(i);for(;s<=a;)o.push(`[[${s.toLocaleDateString("en-CA")}]]`),s.setDate(s.getDate()+1);return o}filterAndFormatChunks(r,n){let o=this.options.minSimilarityScore,i=r.filter(u=>{let l=u.metadata.score;return typeof l!="number"||isNaN(l)?!0:l>=o}),a=new Set(n.map(u=>u.pageContent)),s=[...n];for(let u of i){let l=u.pageContent;a.has(l)||(a.add(l),s.push(u))}return s.map(u=>({...u,metadata:{...u.metadata,includeInContext:!0}}))}};bd();var zPe=Ep(async({timeRange:e,query:t,salientTerms:r})=>{if(await ma.getInstance().isIndexEmpty())throw new dr(s5);let o=e!==void 0,i=pe().maxSourceChunks<Ale?Ale:pe().maxSourceChunks;pe().debug&&console.log("returnAll:",o);let u=(await new oT({minSimilarityScore:o?0:.1,maxK:o?1e3:i,salientTerms:r,timeRange:e?{startTime:e.startTime.epoch,endTime:e.endTime.epoch}:void 0,textWeight:oBe,returnAll:o,useRerankerThreshold:.5}).getRelevantDocuments(t)).map(l=>({title:l.metadata.title,content:l.pageContent,path:l.metadata.path,score:l.metadata.score,rerank_score:l.metadata.rerank_score,includeInContext:l.metadata.includeInContext}));return JSON.stringify(u)},{name:"localSearch",description:"Search for notes based on the time range and query",schema:Er.object({timeRange:Er.object({startTime:Er.any(),endTime:Er.any()}).optional(),query:Er.string().describe("The search query"),salientTerms:Er.array(Er.string()).describe("List of salient terms extracted from the query")})}),hAt=Ep(async()=>{try{let e=await ma.getInstance().indexVaultToVectorStore();return`Please report whether the indexing was successful.
If success is true, just say it is successful. If 0 files is indexed, say there are no new files to index.`+JSON.stringify({success:!0,message:e===0?"No new files to index.":`Indexed ${e} files in the vault.`})}catch(e){return console.error("Error indexing vault:",e),JSON.stringify({success:!1,message:"An error occurred while indexing the vault."})}},{name:"indexVault",description:"Index the vault to the Copilot index"}),HPe=Ep(async({query:e,chatHistory:t})=>{try{let r=await Sne(e,t),n=await _l.getInstance().webSearch(r),o=n.response.citations||[],i=o.length>0?`
Sources:
`+o.map((a,s)=>`[${s+1}] ${a}`).join(`
`):"";return`Here are the web search results. Please provide a response based on this information and include source citations listed at the end of your response under the heading '#### Sources' as a list of markdown links. For each URL, create a descriptive title based on the domain and path and return it in the markdown format '- [title](url)':
`+n.response.choices[0].message.content+i}catch(r){return console.error(`Error processing web search query ${e}:`,r),""}},{name:"webSearch",description:"Search the web for information",schema:Er.object({query:Er.string().describe("The search query"),chatHistory:Er.array(Er.tuple([Er.string(),Er.string()])).describe("Previous conversation turns")})});var bAt=B(mAt(),1),B3=B(iT(),1);var Rn;(function(e){e[e.AM=0]="AM",e[e.PM=1]="PM"})(Rn||(Rn={}));var Tu;(function(e){e[e.SUNDAY=0]="SUNDAY",e[e.MONDAY=1]="MONDAY",e[e.TUESDAY=2]="TUESDAY",e[e.WEDNESDAY=3]="WEDNESDAY",e[e.THURSDAY=4]="THURSDAY",e[e.FRIDAY=5]="FRIDAY",e[e.SATURDAY=6]="SATURDAY"})(Tu||(Tu={}));var Rp;(function(e){e[e.JANUARY=1]="JANUARY",e[e.FEBRUARY=2]="FEBRUARY",e[e.MARCH=3]="MARCH",e[e.APRIL=4]="APRIL",e[e.MAY=5]="MAY",e[e.JUNE=6]="JUNE",e[e.JULY=7]="JULY",e[e.AUGUST=8]="AUGUST",e[e.SEPTEMBER=9]="SEPTEMBER",e[e.OCTOBER=10]="OCTOBER",e[e.NOVEMBER=11]="NOVEMBER",e[e.DECEMBER=12]="DECEMBER"})(Rp||(Rp={}));function gAt(e,t){t=t.add(1,"day"),b1(e,t),Yk(e,t)}function Ag(e,t){e.assign("day",t.date()),e.assign("month",t.month()+1),e.assign("year",t.year())}function Cne(e,t){e.assign("hour",t.hour()),e.assign("minute",t.minute()),e.assign("second",t.second()),e.assign("millisecond",t.millisecond()),e.get("hour")<12?e.assign("meridiem",Rn.AM):e.assign("meridiem",Rn.PM)}function b1(e,t){e.imply("day",t.date()),e.imply("month",t.month()+1),e.imply("year",t.year())}function Yk(e,t){e.imply("hour",t.hour()),e.imply("minute",t.minute()),e.imply("second",t.second()),e.imply("millisecond",t.millisecond())}var KPe=B(iT(),1);var Mrn={ACDT:630,ACST:570,ADT:-180,AEDT:660,AEST:600,AFT:270,AKDT:-480,AKST:-540,ALMT:360,AMST:-180,AMT:-240,ANAST:720,ANAT:720,AQTT:300,ART:-180,AST:-240,AWDT:540,AWST:480,AZOST:0,AZOT:-60,AZST:300,AZT:240,BNT:480,BOT:-240,BRST:-120,BRT:-180,BST:60,BTT:360,CAST:480,CAT:120,CCT:390,CDT:-300,CEST:120,CET:{timezoneOffsetDuringDst:2*60,timezoneOffsetNonDst:60,dstStart:e=>yAt(e,Rp.MARCH,Tu.SUNDAY,2),dstEnd:e=>yAt(e,Rp.OCTOBER,Tu.SUNDAY,3)},CHADT:825,CHAST:765,CKT:-600,CLST:-180,CLT:-240,COT:-300,CST:-360,CT:{timezoneOffsetDuringDst:-5*60,timezoneOffsetNonDst:-6*60,dstStart:e=>aT(e,Rp.MARCH,Tu.SUNDAY,2,2),dstEnd:e=>aT(e,Rp.NOVEMBER,Tu.SUNDAY,1,2)},CVT:-60,CXT:420,ChST:600,DAVT:420,EASST:-300,EAST:-360,EAT:180,ECT:-300,EDT:-240,EEST:180,EET:120,EGST:0,EGT:-60,EST:-300,ET:{timezoneOffsetDuringDst:-4*60,timezoneOffsetNonDst:-5*60,dstStart:e=>aT(e,Rp.MARCH,Tu.SUNDAY,2,2),dstEnd:e=>aT(e,Rp.NOVEMBER,Tu.SUNDAY,1,2)},FJST:780,FJT:720,FKST:-180,FKT:-240,FNT:-120,GALT:-360,GAMT:-540,GET:240,GFT:-180,GILT:720,GMT:0,GST:240,GYT:-240,HAA:-180,HAC:-300,HADT:-540,HAE:-240,HAP:-420,HAR:-360,HAST:-600,HAT:-90,HAY:-480,HKT:480,HLV:-210,HNA:-240,HNC:-360,HNE:-300,HNP:-480,HNR:-420,HNT:-150,HNY:-540,HOVT:420,ICT:420,IDT:180,IOT:360,IRDT:270,IRKST:540,IRKT:540,IRST:210,IST:330,JST:540,KGT:360,KRAST:480,KRAT:480,KST:540,KUYT:240,LHDT:660,LHST:630,LINT:840,MAGST:720,MAGT:720,MART:-510,MAWT:300,MDT:-360,MESZ:120,MEZ:60,MHT:720,MMT:390,MSD:240,MSK:180,MST:-420,MT:{timezoneOffsetDuringDst:-6*60,timezoneOffsetNonDst:-7*60,dstStart:e=>aT(e,Rp.MARCH,Tu.SUNDAY,2,2),dstEnd:e=>aT(e,Rp.NOVEMBER,Tu.SUNDAY,1,2)},MUT:240,MVT:300,MYT:480,NCT:660,NDT:-90,NFT:690,NOVST:420,NOVT:360,NPT:345,NST:-150,NUT:-660,NZDT:780,NZST:720,OMSST:420,OMST:420,PDT:-420,PET:-300,PETST:720,PETT:720,PGT:600,PHOT:780,PHT:480,PKT:300,PMDT:-120,PMST:-180,PONT:660,PST:-480,PT:{timezoneOffsetDuringDst:-7*60,timezoneOffsetNonDst:-8*60,dstStart:e=>aT(e,Rp.MARCH,Tu.SUNDAY,2,2),dstEnd:e=>aT(e,Rp.NOVEMBER,Tu.SUNDAY,1,2)},PWT:540,PYST:-180,PYT:-240,RET:240,SAMT:240,SAST:120,SBT:660,SCT:240,SGT:480,SRT:-180,SST:-660,TAHT:-600,TFT:300,TJT:300,TKT:780,TLT:540,TMT:300,TVT:720,ULAT:480,UTC:0,UYST:-120,UYT:-180,UZT:300,VET:-210,VLAST:660,VLAT:660,VUT:660,WAST:120,WAT:60,WEST:60,WESZ:60,WET:0,WEZ:0,WFT:720,WGST:-120,WGT:-180,WIB:420,WIT:540,WITA:480,WST:780,WT:0,YAKST:600,YAKT:600,YAPT:600,YEKST:360,YEKT:360};function aT(e,t,r,n,o=0){let i=0,a=0;for(;a<n;)i++,new Date(e,t-1,i).getDay()===r&&a++;return new Date(e,t-1,i,o)}function yAt(e
tags: ${JSON.stringify(Array.from(this._tags).sort())},
knownValues: ${JSON.stringify(this.knownValues)},
impliedValues: ${JSON.stringify(this.impliedValues)}},
reference: ${JSON.stringify(this.reference)}]`}dayjs(){return(0,B3.default)(this.date())}date(){let t=this.dateWithoutTimezoneAdjustment(),r=this.reference.getSystemTimezoneAdjustmentMinute(t,this.get("timezoneOffset"));return new Date(t.getTime()+r*6e4)}addTag(t){return this._tags.add(t),this}addTags(t){for(let r of t)this._tags.add(r);return this}tags(){return new Set(this._tags)}dateWithoutTimezoneAdjustment(){let t=new Date(this.get("year"),this.get("month")-1,this.get("day"),this.get("hour"),this.get("minute"),this.get("second"),this.get("millisecond"));return t.setFullYear(this.get("year")),t}static createRelativeFromReference(t,r){let n=(0,B3.default)(t.instant);for(let i in r)n=n.add(r[i],i);let o=new e(t);return r.hour||r.minute||r.second?(Cne(o,n),Ag(o,n),t.timezoneOffset!==null&&o.assign("timezoneOffset",-t.instant.getTimezoneOffset())):(Yk(o,n),t.timezoneOffset!==null&&o.imply("timezoneOffset",-t.instant.getTimezoneOffset()),r.d?(o.assign("day",n.date()),o.assign("month",n.month()+1),o.assign("year",n.year())):r.week?(o.assign("day",n.date()),o.assign("month",n.month()+1),o.assign("year",n.year()),o.imply("weekday",n.day())):(o.imply("day",n.date()),r.month?(o.assign("month",n.month()+1),o.assign("year",n.year())):(o.imply("month",n.month()+1),r.year?o.assign("year",n.year()):o.imply("year",n.year())))),o}},jC=class e{constructor(t,r,n,o,i){this.reference=t,this.refDate=t.instant,this.index=r,this.text=n,this.start=o||new Dn(t),this.end=i}clone(){let t=new e(this.reference,this.index,this.text);return t.start=this.start?this.start.clone():null,t.end=this.end?this.end.clone():null,t}date(){return this.start.date()}tags(){let t=new Set(this.start.tags());if(this.end)for(let r of this.end.tags())t.add(r);return t}toString(){let t=Array.from(this.tags()).sort();return`[ParsingResult {index: ${this.index}, text: '${this.text}', tags: ${JSON.stringify(t)} ...}]`}};function YPe(e,t,r="\\s{0,5},?\\s{0,5}"){let n=t.replace(/\((?!\?)/g,"(?:");return`${e}${n}(?:${r}${n}){0,10}`}function Irn(e){let t;return e instanceof Array?t=[...e]:e instanceof Map?t=Array.from(e.keys()):t=Object.keys(e),t}function fc(e){return`(?:${Irn(e).sort((r,n)=>n.length-r.length).join("|").replace(/\./g,"\\.")})`}var _At=B(iT(),1);function Ene(e){return e<100&&(e>50?e=e+1900:e=e+2e3),e}function uT(e,t,r){let n=(0,_At.default)(e),o=n;o=o.month(r-1),o=o.date(t),o=o.year(n.year());let i=o.add(1,"y"),a=o.add(-1,"y");return Math.abs(i.diff(n))<Math.abs(o.diff(n))?o=i:Math.abs(a.diff(n))<Math.abs(o.diff(n))&&(o=a),o.year()}var QPe={sunday:0,sun:0,"sun.":0,monday:1,mon:1,"mon.":1,tuesday:2,tue:2,"tue.":2,wednesday:3,wed:3,"wed.":3,thursday:4,thurs:4,"thurs.":4,thur:4,"thur.":4,thu:4,"thu.":4,friday:5,fri:5,"fri.":5,saturday:6,sat:6,"sat.":6},eTe={january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12},sm={...eTe,jan:1,"jan.":1,feb:2,"feb.":2,mar:3,"mar.":3,apr:4,"apr.":4,jun:6,"jun.":6,jul:7,"jul.":7,aug:8,"aug.":8,sep:9,"sep.":9,sept:9,"sept.":9,oct:10,"oct.":10,nov:11,"nov.":11,dec:12,"dec.":12},ZPe={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12},XPe={first:1,second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,tenth:10,eleventh:11,twelfth:12,thirteenth:13,fourteenth:14,fifteenth:15,sixteenth:16,seventeenth:17,eighteenth:18,nineteenth:19,twentieth:20,"twenty first":21,"twenty-first":21,"twenty second":22,"twenty-second":22,"twenty third":23,"twenty-third":23,"twenty fourth":24,"twenty-fourth":24,"twenty fifth":25,"twenty-fifth":25,"twenty sixth":26,"twenty-sixth":26,"twenty seventh":27,"twenty-seventh":27,"twenty eighth":28,"twenty-eighth":28,"twenty ninth":29,"twenty-ninth":29,thirtieth:30,"thirty first":31,"thirty-first":31},wAt={second:"second",seconds:"second",minute:"minute",minutes:"minute",hour:"hour",hours:"hour",day:"d",days:"d",week:"week",weeks:"week",month:"month",months:"month",quarter:"quarter",quarters:"quarter",year:"year",years:"year"},$3={s:"second",sec:"second",second:"second",seconds:"second",m:"minut
* The root object has a key "vault" which contains a FileTreeNode object.
* Each FileTreeNode has these properties:
* files: An array of filenames in the current directory (if any files exist)
* subFolders: An object mapping folder names to their FileTreeNode objects (if any subfolders exist)
* extensionCounts: An object with counts of file extensions in this folder and all subfolders
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
`,n=JSON.stringify(t);if(n.length>15e5){let o=JTe(e,!1);return r+JSON.stringify(o)}return r+n},{name:"getFileTree",description:"Get the file tree as a nested structure of folders and files",schema:Er.void()});bd();var GTe=Ep(async({url:e})=>{try{let t=await _l.getInstance().youtube4llm(e);return t.response.transcript?JSON.stringify({success:!0,transcript:t.response.transcript,elapsed_time_ms:t.elapsed_time_ms}):JSON.stringify({success:!1,message:"Transcript not available. Only English videos with the auto transcript option turned on are supported at the moment"})}catch(t){return console.error(`Error transcribing YouTube video ${e}:`,t),JSON.stringify({success:!1,message:"An error occurred while transcribing the YouTube video."})}},{name:"youtubeTranscription",description:"Get the transcript of a YouTube video",schema:Er.object({url:Er.string().describe("The YouTube video URL"),brevilabsClient:Er.any().describe("The BrevilabsClient instance")})});var _B=class{},C1t=(e,t)=>{if(t!==void 0)return e[t];let r=Object.keys(e);if(r.length===1)return e[r[0]]},Zne=(e,t)=>{let r=C1t(e,t);if(!r){let n=Object.keys(e);throw new Error(`input values have ${n.length} keys, you must specify an input key or pass only 1 key as input`)}return r},KTe=(e,t)=>{let r=C1t(e,t);if(!r&&r!==""){let n=Object.keys(e);throw new Error(`output values have ${n.length} keys, you must specify an output key or pass only 1 key as output`)}return r};NM();UM();var YTe=class extends tf{addUserMessage(t){return this.addMessage(new Ua(t))}addAIChatMessage(t){return this.addMessage(new Po(t))}addAIMessage(t){return this.addMessage(new Po(t))}async addMessages(t){for(let r of t)await this.addMessage(r)}clear(){throw new Error("Not implemented.")}},vB=class extends YTe{constructor(t){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","stores","message","in_memory"]}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.messages=t??[]}async getMessages(){return this.messages}async addMessage(t){this.messages.push(t)}async clear(){this.messages=[]}};var Ww=class extends _B{constructor(t){super(),Object.defineProperty(this,"chatHistory",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"returnMessages",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"inputKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.chatHistory=t?.chatHistory??new vB,this.returnMessages=t?.returnMessages??this.returnMessages,this.inputKey=t?.inputKey??this.inputKey,this.outputKey=t?.outputKey??this.outputKey}async saveContext(t,r){await this.chatHistory.addUserMessage(Zne(t,this.inputKey)),await this.chatHistory.addAIChatMessage(KTe(r,this.outputKey))}async clear(){await this.chatHistory.clear()}};ZTe();GM();var W8=class extends Ww{constructor(t){super({returnMessages:t?.returnMessages??!1,chatHistory:t?.chatHistory,inputKey:t?.inputKey,outputKey:t?.outputKey}),Object.defineProperty(this,"humanPrefix",{enumerable:!0,configurable:!0,writable:!0,value:"Human"}),Object.defineProperty(this,"aiPrefix",{enumerable:!0,configurable:!0,writable:!0,value:"AI"}),Object.defineProperty(this,"memoryKey",{enumerable:!0,configurable:!0,writable:!0,value:"history"}),Object.defineProperty(this,"k",{enumerable:!0,configurable:!0,writable:!0,value:5}),this.humanPrefix=t?.humanPrefix??this.humanPrefix,this.aiPrefix=t?.aiPrefix??this.aiPrefix,this.memoryKey=t?.memoryKey??this.memoryKey,this.k=t?.k??this.k}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(t){let r=await this.chatHistory.getMessages();return this.returnMessages?{[this.memoryKey]:r.slice(-this.k*2)}:{[this.memoryKey]:of(r.slice(-this.k*2),this.humanPrefix,this.aiPrefix)}}};NM();ZTe();var O1=class e{constructor(){this.initMemory(),sl(()=>this.initMemory())}static getInstance(){return e.instance||(e.instance=new e),e.instance}initMemory(){let t=pe(
`,this.chainManager.memoryManager.getMemory().chatHistory.messages.map(u=>u.content)),console.log(`==== Final AI Response ====
`,t)),t}async handleError(t,r,n,o){let i=bi(t);r&&console.error("Error during LLM invocation:",i);let a=t?.response?.data?.error||i,s=a?.code||i,u="";if(t?.message?.includes("Invalid license key")?u="Invalid Copilot Plus license key. Please check your license key in settings.":s==="model_not_found"?u="You do not have access to this model or the model does not exist, please check with your API provider.":u=`${s}`,console.error(a),n&&o){o("");let l=u.search("Troubleshooting URL");u=l!==-1?u.slice(0,l):u,i.search(/401|invalid|not valid/gi)!==-1&&(u=`Something went wrong. Please check if you have set your API key.
Path: Settings > copilot plugin > Basic Tab > Set Keys.
Or check model config
Error Details: `+u),n({message:u,isErrorMessage:!0,sender:cy,isVisible:!0,timestamp:ll(new Date)})}else new M1t.Notice(u),console.error(a)}},Xne=class extends G8{async run(t,r,n,o,i){let{debug:a=!1}=i,s="";try{let l=await $C.getChain().stream({input:t.message});for await(let c of l){if(r.signal.aborted)break;s+=c.content,n(s)}}catch(u){await this.handleError(u,a,o,n)}return this.handleResponse(s,t,r,o,n,a)}},Qne=class extends G8{async run(t,r,n,o,i){let{debug:a=!1}=i,s="";try{if(await this.chainManager.vectorStoreManager.isIndexEmpty())return this.handleResponse(s5,t,r,o,n,a);let c=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),d=ij(c),f=await $C.getRetrievalChain().stream({question:t.message,chat_history:d});for await(let p of f){if(r.signal.aborted)break;s+=p.content,n(s)}s=this.addSourcestoResponse(s)}catch(u){await this.handleError(u,a,o,n)}return this.handleResponse(s,t,r,o,n,a)}addSourcestoResponse(t){let r=Yke($C.retrievedDocuments);if(r.length>0){let n=r.map(o=>`- [[${o}]]`).join(`
`);t+=`
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
#### Sources:
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
`+n}return t}},eoe=class extends G8{isYoutubeOnlyMessage(t){let r=t.trim(),n=r.includes("@youtube"),o=gq(r),i=r.split(/\s+/).filter(a=>a!=="@youtube"&&a.length>0);return n&&o!==null&&i.length===1}async processImageUrls(t){try{return(await Promise.all(t.map(async n=>await DS.isImageUrl(n)?await DS.convertToBase64(n,this.chainManager.app.vault):null))).filter(n=>n!==null)}catch(r){return console.error("Error processing image URLs:",r),[]}}async processExistingImages(t){try{return await Promise.all(t.filter(n=>n.type==="image_url"&&!!n.image_url?.url).map(async n=>await DS.convertToBase64(n.image_url.url,this.chainManager.app.vault)))}catch(r){throw console.error("Error processing images:",r),r}}async buildMessageContent(t,r){let n=[{type:"text",text:t}];if(r.context?.urls&&r.context.urls.length>0){let o=await this.processImageUrls(r.context.urls);n.push(...o)}if(r.content&&r.content.length>0){let o=await this.processExistingImages(r.content);n.push(...o)}return n}hasCapability(t,r){let n=t.modelName||t.model||"";return this.chainManager.chatModelManager.findModelByName(n)?.capabilities?.includes(r)??!1}isMultimodalModel(t){return this.hasCapability(t,"vision")}async streamMultimodalResponse(t,r,n,o,i){let s=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),u=ij(s),l=[],c=ZM();u.length>0&&(c+=`
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
The following is the relevant conversation history. Use this context to maintain consistency in your responses:`);let d=this.chainManager.chatModelManager.getChatModel();c&&l.push({role:rBe(d),content:`${c}
IMPORTANT: Maintain consistency with previous responses in the conversation. If you've provided information about a person or topic before, use that same information in follow-up questions.`});for(let[g,v]of u)l.push({role:"user",content:g}),l.push({role:"assistant",content:v});let f=this.chainManager.chatModelManager.getChatModel(),h=this.isMultimodalModel(f)?await this.buildMessageContent(t,r):t;l.push({role:"user",content:h}),i&&console.log(`==== Final Request to AI ====
`,l);let m="",_=await this.chainManager.chatModelManager.getChatModel().stream(l);for await(let g of _){if(n.signal.aborted)break;m+=g.content,o(m)}return m}async run(t,r,n,o,i){let{debug:a=!1,updateLoadingMessage:s}=i,u="",l=[];try{if(this.isYoutubeOnlyMessage(t.message)){let h=gq(t.message),m="Transcript not available. Only videos with the auto transcript option turned on are supported at the moment.";if(h)try{let _=await _l.getInstance().youtube4llm(h);return _.response.transcript?this.handleResponse(_.response.transcript,t,r,o,n,a):this.handleResponse(m,t,r,o,n,a)}catch(_){return console.error("Error processing YouTube video:",_),this.handleResponse(m,t,r,o,n,a)}}a&&console.log("==== Step 1: Analyzing intent ====");let c;try{let h=t.originalMessage||t.message;c=await E1.analyzeIntent(h)}catch(h){return this.handleResponse(Vke(h),t,r,o,n,a)}let d=t.message.split(" ").filter(h=>!J8.includes(h.toLowerCase())).join(" ").trim(),f=await this.executeToolCalls(c,a,s),p=f.find(h=>h.tool==="localSearch"&&h.output&&h.output.length>0);if(p){a&&console.log("==== Step 2: Processing local search results ====");let h=JSON.parse(p.output),_=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),g=ij(_);a&&console.log("==== Step 3: Condensing Question ====");let v=await Sne(d,g);a&&console.log("Condensed standalone question: ",v),a&&console.log("==== Step 4: Preparing context ====");let S=this.getTimeExpression(c),x=this.prepareLocalSearchResult(h,S),O=f.filter(M=>M.tool==="getCurrentTime"),T=this.prepareEnhancedUserMessage(v,O);a&&console.log(x),a&&console.log("==== Step 5: Invoking QA Chain ====");let E=await this.chainManager.promptManager.getQAPrompt({question:T,context:x,systemMessage:""});u=await this.streamMultimodalResponse(E,t,r,n,a),l=this.getSources(h)}else{let h=this.prepareEnhancedUserMessage(d,f);a&&(console.log("No local search results. Using standard LLM Chain."),console.log("Enhanced user message:",h)),u=await this.streamMultimodalResponse(h,t,r,n,a)}}catch(c){s?.(jS.DEFAULT),await this.handleError(c,a,o,n)}return this.handleResponse(u,t,r,o,n,a,l)}getSources(t){return!t||!Array.isArray(t)?(console.warn("No valid documents provided to getSources"),[]):this.sortUniqueDocsByScore(t)}sortUniqueDocsByScore(t){let r=new Map;for(let n of t){if(!n.title||!n?.score&&!n?.rerank_score){console.warn("Invalid document structure:",n);continue}let o=r.get(n.title),i=n&&"rerank_score"in n,a=i?n.rerank_score:n.score;(!o||a>(o.score??0))&&r.set(n.title,{title:n.title,score:a,isReranked:i})}return Array.from(r.values()).sort((n,o)=>(o.score??0)-(n.score??0))}async executeToolCalls(t,r,n){let o=[];for(let i of t){r&&console.log(`==== Step 2: Calling tool: ${i.tool.name} ====`),i.tool.name==="localSearch"?n?.(jS.READING_FILES):i.tool.name==="webSearch"?n?.(jS.SEARCHING_WEB):i.tool.name==="getFileTree"&&n?.(jS.READING_FILE_TREE);let a=await Kk.callTool(i.tool,i.args);o.push({tool:i.tool.name,output:a})}return o}prepareEnhancedUserMessage(t,r){let n="";if(r.length>0){let o=r.filter(i=>i.output!=null);o.length>0&&(n=`
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
# Additional context:
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
`+o.map(i=>`<${i.tool}>
${typeof i.output!="string"?JSON.stringify(i.output):i.output}
</${i.tool}>`).join(`
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
`))}return`User message: ${t}${n}`}getTimeExpression(t){let r=t.find(n=>n.tool.name==="getTimeRangeMs");return r?r.args.timeExpression:""}prepareLocalSearchResult(t,r){let n=t.filter(s=>s.includeInContext),o=n.reduce((s,u)=>s+u.content.length,0),i=n;if(o>Rle){let s=Rle/o;console.log("Truncating documents to fit context length. Truncation ratio:",s),i=n.map(u=>({...u,content:u.content.slice(0,Math.floor(u.content.length*s))}))}let a=i.map(s=>`Note in Vault: ${s.content}`).join(`
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
`);return r?`Local Search Result for ${r}:
${a}`:`Local Search Result:
${a}`}};GM();var I1t=require("obsidian");GM();var K8=class e{constructor(){this.initChatPrompt(),this.initQAPrompt(),sl(()=>{this.initChatPrompt(),this.initQAPrompt()})}static getInstance(){return e.instance||(e.instance=new e),e.instance}initChatPrompt(){let t=this.escapeTemplateString(ZM());this.chatPrompt=ah.fromMessages([KD.fromTemplate(t),new xO("history"),CO.fromTemplate("{input}")])}initQAPrompt(){let t=`{system_message}
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
Answer the question with as detailed as possible based only on the following context:
{context}
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
Question: {question}
`;this.qaPrompt=ah.fromMessages([KD.fromTemplate(t)])}escapeTemplateString(t){return t.replace(/\{/g,"{{").replace(/\}/g,"}}")}getChatPrompt(){return this.chatPrompt}async getQAPrompt({question:t,context:r,systemMessage:n}){return await this.qaPrompt.format({question:t,context:r,system_message:n})}};var Np=class Np{constructor(t,r){this.app=t,this.vectorStoreManager=r,this.memoryManager=O1.getInstance(),this.chatModelManager=Ud.getInstance(),this.promptManager=K8.getInstance(),this.initialize(),pBe(async()=>await this.createChainWithNewModel()),hBe(()=>this.setChain(qm(),{refreshIndex:pe().indexVaultToVectorStore==="ON MODE SWITCH"&&(qm()==="vault_qa"||qm()==="copilot_plus")})),sl(async()=>await this.createChainWithNewModel())}async initialize(){await this.createChainWithNewModel()}static getChain(){return Np.chain}static getRetrievalChain(){return Np.retrievalChain}validateChainType(t){if(t==null)throw new Error("No chain type set")}validateChatModel(){if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){let t="Chat model is not initialized properly, check your API key in Copilot setting and make sure you have API access.";throw new I1t.Notice(t),new Error(t)}}validateChainInitialization(){(!Np.chain||!Jke(Np.chain))&&(console.error("Chain is not initialized properly, re-initializing chain: ",qm()),this.setChain(qm()))}static storeRetrieverDocuments(t){Np.retrievedDocuments=t}async createChainWithNewModel(){let t=m5();try{let r=n5(t,pe().activeModels);r||(console.error("Resetting default model. No model configuration found for: ",t),r=PO[0],t=r.name+"|"+r.provider),await this.chatModelManager.setChatModel(r),this.setChain(qm()),br(`Setting model to ${t}`)}catch(r){Ur(`createChainWithNewModel failed: ${r}`),br(`modelKey: ${t}`)}}async setChain(t,r={}){if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){console.error("setChain failed: No chat model set.");return}this.validateChainType(t);let n=this.chatModelManager.getChatModel(),o=this.memoryManager.getMemory(),i=this.promptManager.getChatPrompt();switch(t){case"llm_chain":{Np.chain=a5.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),cj("llm_chain");break}case"vault_qa":{await this.initializeQAChain(r);let a=new oT({minSimilarityScore:.01,maxK:pe().maxSourceChunks,salientTerms:[]});Np.retrievalChain=a5.createConversationalRetrievalChain({llm:n,retriever:a,systemMessage:ZM()},Np.storeRetrieverDocuments.bind(Np),pe().debug),cj("vault_qa"),pe().debug&&(console.log("New Vault QA chain with hybrid retriever created for entire vault"),console.log("Set chain:","vault_qa"));break}case"copilot_plus":{await this.initializeQAChain(r),Np.chain=a5.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),cj("copilot_plus");break}default:this.validateChainType(t);break}}getChainRunner(){let t=qm();switch(t){case"llm_chain":return new Xne(this);case"vault_qa":return new Qne(this);case"copilot_plus":return new eoe(this);default:throw new Error(`Unsupported chain type: ${t}`)}}async initializeQAChain(t){t.refreshIndex&&await this.vectorStoreManager.indexVaultToVectorStore()}async runChain(t,r,n,o,i={}){let{debug:a=!1,ignoreSystemMessage:s=!1}=i;a&&console.log(`==== Step 0: Initial user message ====
`,t),this.validateChatModel(),this.validateChainInitialization();let u=this.chatModelManager.getChatModel();if(s||tI(u)){let c=ah.fromMessages([new xO("history"),CO.fromTemplate("{input}")]);tI(u)&&(c=ah.fromMessages([[Uo,ZM()||""],c])),this.setChain(qm(),{prompt:c})}return await this.getChainRunner().run(t,r,n,o,i)}async updateMemoryWithLoadedMessages(t){await this.memoryManager.clearChatMemory();for(let r=0;r<t.length;r+=2){let n=t[r],o=t[r+1];n&&o&&n.sender===Uo&&await this.memoryManager.getMemory().saveContext({input:n.message},{output:o.message})}}};Np.retrievedDocuments=[];var $C=Np;function A1t(e){let t=e.split(`
`),r=[],n="",o="",i="";for(let a of t)a.startsWith("**user**:")||a.startsWith("**ai**:")?(n&&o&&r.push({sender:n===Uo?Uo:cy,message:o.trim(),isVisible:!0,timestamp:i?Cle(i):null}),n=a.startsWith("**user**:")?Uo:cy,o=a.substring(a.indexOf(":")+1).trim(),i=""):a.startsWith("[Timestamp:")?i=a.substring(11,a.length-1).trim():o+=`
`+a;return n&&o&&r.push({sender:n===Uo?Uo:cy,message:o.trim(),isVisible:!0,timestamp:i?Cle(i):null}),r}async function Y8(e,t){await t.clearChatMemory();for(let r=0;r<e.length-1;r++){let n=e[r];if(n.sender===Uo){let o=e[r+1];o?.sender===cy&&await t.getMemory().saveContext({input:n.message},{output:o.message})}}}var wB=require("obsidian"),pr=B(Y()),R1t=B(gh());var toe=B(Y());var ti=toe.forwardRef(({className:e,type:t,...r},n)=>toe.createElement("input",{type:t,className:_e("!h-9 !min-w-[50px] !border border-border border-solid !rounded-md !bg-transparent !px-3 !py-1 md:!text-base !text-sm !transition-colors","focus-visible:!shadow-sm focus-visible:!outline-none focus-visible:!ring-1 focus-visible:!ring-ring","placeholder:text-xs","flex w-full shadow-sm placeholder:text-muted disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...r}));ti.displayName="Input";var pm=B(Y());var P1=pm.forwardRef(({className:e,value:t,...r},n)=>{let o=pm.useRef(null),i=pm.useCallback(()=>{let s=o.current;if(s){s.style.height="auto";let u=Math.min(s.scrollHeight,300);s.style.height=`${u}px`}},[]);pm.useLayoutEffect(()=>{i()},[t,i]),pm.useEffect(()=>(i(),window.addEventListener("resize",i),()=>window.removeEventListener("resize",i)),[i]);let a=s=>{o.current=s,typeof n=="function"?n(s):n&&(n.current=s)};return pm.createElement("textarea",{className:_e("border-solid resize-y min-w-fit overflow-auto","flex min-h-[60px] max-h-[300px] w-full rounded-md border border-primary-alt bg-transparent px-3 py-2 text-base shadow-sm placeholder:text-muted focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),value:t,ref:a,onChange:s=>{i(),r.onChange?.(s)},onInput:i,onCompositionEnd:i,onPaste:()=>{setTimeout(i,0)},...r})});P1.displayName="Textarea";function Iin({initialTitle:e="",initialPrompt:t="",disabledTitle:r=!1,onSave:n,onCancel:o}){let[i,a]=(0,pr.useState)(e),[s,u]=(0,pr.useState)(t),[l,c]=(0,pr.useState)({title:!1,prompt:!1}),[d,f]=(0,pr.useState)(!1),h=i&&/[<>:"/\\|?*\x00-\x1F]/g.test(i),m=async()=>{if(h){new wB.Notice("Title contains invalid characters. Please remove them before saving.");return}if(i&&s)try{f(!0),await n(i,s)}catch(S){new wB.Notice(bi(S))}finally{f(!1)}else c({title:!0,prompt:!0}),new wB.Notice("Please fill in both fields: Title and Prompt.")},_=l.title&&!i,g=l.prompt&&!s,v=i.trim()!==""&&s.trim()!==""&&!h;return pr.default.createElement("div",{className:"flex flex-col gap-4 p-4"},pr.default.createElement("div",{className:"text-xl font-bold text-normal mb-2"},"User Custom Prompt"),pr.default.createElement("div",{className:"flex flex-col"},pr.default.createElement("div",{className:"flex items-center gap-1"},pr.default.createElement("div",{className:"text-base font-medium text-normal"},"Title"),pr.default.createElement("span",{className:"text-error"},"*")),pr.default.createElement("div",{className:"flex flex-col gap-1"},pr.default.createElement("div",{className:"text-sm text-muted"},"The title of the prompt, must be unique."),pr.default.createElement("div",{className:"text-xs text-warning"},"Note: Title will be used as filename. Avoid using: ",'< > : " / \\ | ? *')),pr.default.createElement(ti,{type:"text",value:i,onChange:S=>{a(S.target.value),l.title||c(x=>({...x,title:!0}))},onBlur:()=>c(S=>({...S,title:!0})),disabled:r,className:"w-full mt-1",required:!0}),_&&pr.default.createElement("div",{className:"text-error text-xs mt-1"},"Title is required"),h&&pr.default.createElement("div",{className:"text-error text-xs mt-1"},"Title contains invalid characters")),pr.default.createElement("div",{className:"flex flex-col gap-1"},pr.default.createElement("div",{className:"space-y-2"},pr.default.createElement("div",{className:"flex items-center gap-1"},pr.default.createElement("div",{className:"text-base font-medium text-normal"},"Prompt"),pr.default.createElement("span",{className:"text-error"},"*")),pr.default.createElement("div",{className:"text-sm text-muted -mt-1"},"Use the following syntax in your prompt:")),pr.default.createElement("div",{className:"text
`),l="OramaDB-Debug-Search.md",c=this.app.vault.getAbstractFileByPath(l);c instanceof wT.TFile?await this.app.vault.modify(c,u):await this.app.vault.create(l,u);let d=this.app.vault.getAbstractFileByPath(l);d instanceof wT.TFile&&(await this.app.workspace.getLeaf().openFile(d),this.close())}catch(i){console.error("Error in debug search:",i),new wT.Notice("Error executing search. Check console for details.")}})}onClose(){let{contentEl:t}=this;t.empty()}};function SB(e){return e.replace(/\s+/g,"-").toLowerCase()}function j1t(e,t){if(!e)throw new Error("Command name is required");if(e.length>Mle)throw new Error(`Command name must be less than ${Mle} characters`);if(!/^[a-zA-Z0-9\s]+$/.test(e))throw new Error("Command name must only contain alphanumeric characters and spaces");if(T1().some(n=>n.name.toLowerCase()===e.toLowerCase()&&n.name.toLowerCase()!==t?.toLowerCase()))throw new Error("A command with this name already exists")}function N1t(e){return T1().find(r=>SB(r.name)===e)}function T1(){return pe().inlineEditCommands??uj}function L1t(){return qo().inlineEditCommands??uj}function F1t(e,t){let r=e.indexOf(cf);return r===-1?e+`
`+t:e.slice(0,r)+t+e.slice(r+cf.length)}function k1t(){return T1()!==uj}var Jw=B(Y());var XTe=({capabilities:e=[],iconSize:t=16})=>Jw.default.createElement(Jw.default.Fragment,null,e.sort((r,n)=>r.localeCompare(n)).map((r,n)=>{switch(r){case"reasoning":return Jw.default.createElement(KS,{key:n,className:"text-model-capabilities-blue",style:{width:t,height:t}});case"vision":return Jw.default.createElement(GS,{key:n,className:"text-model-capabilities-green",style:{width:t,height:t}});case"websearch":return Jw.default.createElement(EI,{key:n,className:"text-model-capabilities-blue",style:{width:t,height:t}});default:return null}})),QTe=({model:e,iconSize:t=14})=>{let r=e.displayName||e.name;return Jw.default.createElement("div",{className:"flex items-center gap-1"},Jw.default.createElement("span",null,r),e.capabilities&&e.capabilities.length>0&&Jw.default.createElement("div",{className:"flex gap-0.5 items-center"},Jw.default.createElement(XTe,{capabilities:e.capabilities,iconSize:t})))},ooe=e=>{let t=e.displayName||e.name,r=`(${uh(e.provider)})`;return`${t} ${r}`},eMe=e=>{let t=e.displayName||e.name,r=`(${uh(e.provider,e)})`,n=e.capabilities?.map(o=>{switch(o){case"reasoning":return"Reasoning";case"vision":return"Vision";case"websearch":return"Websearch";default:return""}}).join("|")||"";return`${t} ${r} ${n}`};var aoe=require("obsidian"),di=B(Y()),B1t=B(gh());function Ain({originalText:e,command:t,onInsert:r,onReplace:n,onClose:o}){let[i,a]=(0,di.useState)(null),[s,u]=(0,di.useState)(null),[l]=lj(),c=qo(),d=(0,di.useMemo)(()=>n5(t.modelKey||l,c.activeModels),[t.modelKey,l,c.activeModels]),f=t.name,p=(0,di.useCallback)(h=>{u(h.message)},[]);return(0,di.useEffect)(()=>{let h=new AbortController;async function m(){let _=F1t(t.prompt,e),g="",S=await(await Ud.getInstance().createModelInstance(d)).stream(_);for await(let x of S){if(h?.signal.aborted)break;g+=x.content,a(g)}h?.signal.aborted||u(g)}return m(),()=>{h.abort()}},[t.prompt,e,p,d]),di.default.createElement("div",{className:"flex flex-col gap-4"},di.default.createElement("div",{className:"max-h-60 overflow-y-auto text-muted whitespace-pre-wrap"},e),di.default.createElement("div",{className:"flex flex-col gap-2"},f&&di.default.createElement("div",{className:"text-normal flex items-center gap-2 font-bold"},di.default.createElement(oE,{className:"w-4 h-4"}),f),di.default.createElement("div",{className:"text-muted flex items-center gap-2 font-bold"},di.default.createElement(_I,{className:"w-4 h-4"}),ooe(d))),di.default.createElement("div",{className:"relative group"},di.default.createElement("textarea",{className:"w-full h-60 text-text peer",value:s??i??"loading...",disabled:s==null,onChange:h=>u(h.target.value)}),s&&di.default.createElement("button",{className:"absolute top-2 right-2 opacity-0 peer-focus-visible:!opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>{navigator.clipboard.writeText(s),new aoe.Notice("Copied to clipboard")}},di.default.createElement(SI,{className:"w-4 h-4 text-muted-foreground hover:text-accent"}))),di.default.createElement("div",{className:"flex justify-end gap-2"},di.default.createElement("button",{onClick:o},"Close"),di.default.createElement("button",{disabled:s==null,className:"!bg-interactive-accent !text-on-accent cursor-pointer",onClick:()=>r(s??"")},"Insert"),di.default.createElement("button",{disabled:s==null,className:"!bg-interactive-accent !text-on-accent cursor-pointer",onClick:()=>n(s??"")},"Replace")))}var ioe=class extends aoe.Modal{constructor(r,n){super(r);this.configs=n}onOpen(){let{contentEl:r}=this;this.root=(0,B1t.createRoot)(r);let{selectedText:n,command:o}=this.configs,i=u=>{yq(u),this.close()},a=u=>{yq(u,!0),this.close()},s=()=>{this.close()};this.root.render(di.default.createElement(Ain,{originalText:n,command:o,onInsert:i,onReplace:a,onClose:s}))}onClose(){this.root.unmount()}};var $1t=require("obsidian"),qC=class extends $1t.FuzzySuggestModal{constructor(t,r,n,o=[]){super(t),this.promptTitles=r,this.onChoosePromptTitle=n,this.descriptions=o}getItems(){return this.promptTitles}getItemText(t){let r=this.
- [[Note 1]]
- [[Note 2]]`,rows:"10",style:"width: 100%; min-height: 200px; margin: 10px 0; padding: 10px; font-family: monospace;"}}),t.createEl("div",{cls:"search-button-container"}).createEl("button",{text:"Show Index Data",cls:"mod-cta"}).addEventListener("click",async()=>{let o=this.searchInput.value,i=ly(o,this.app.vault).map(a=>a.path);if(i.length===0){new X8.Notice("No valid note paths found. Use format: - [[Note Name]]");return}try{let s=await(await this.plugin.vectorStoreManager.getDbOps()).getDocsJsonByPaths(i),u="CopilotDB-Search-Results.md",l=["## Searched Paths",...i.map(f=>`- [[${f}]]`),"","## Index Data","```json",JSON.stringify(s,null,2),"```"].join(`
`),c=this.app.vault.getAbstractFileByPath(u);c?await this.app.vault.modify(c,l):await this.app.vault.create(u,l);let d=this.app.vault.getAbstractFileByPath(u);d&&await this.app.workspace.getLeaf().openFile(d),this.close()}catch(a){console.error("Error searching DB:",a),new X8.Notice("Error searching database. Check console for details.")}})}onClose(){let{contentEl:t}=this;t.empty()}};var Q8=require("obsidian"),uoe=class extends Q8.Modal{constructor(r,n){super(r);this.filePaths="";this.onSubmit=n}onOpen(){let{contentEl:r}=this;r.createEl("h2",{text:"Remove Files from Copilot Index"});let n=r.createDiv({cls:"remove-files-container"});new Q8.Setting(n).setName("File paths").setDesc("Paste the markdown list of file paths to remove from the index. You can get the list by running the command `List all indexed files`.").setClass("remove-files-setting").addTextArea(o=>o.setPlaceholder(`- [[path/to/file1.md]]
- [[path/to/file2.md]]`).setValue(this.filePaths).onChange(i=>{this.filePaths=i})),new Q8.Setting(n).addButton(o=>o.setButtonText("Remove").setCta().onClick(()=>{let i=this.filePaths.split(`
`).map(a=>{let s=a.match(/\[\[(.*?)\]\]/);return s?s[1].trim():""}).filter(a=>a.length>0);this.onSubmit(i),this.close()})),r.createEl("style",{text:`
2025-01-09 14:41:22 +08:00
.remove-files-container {
width: 100%;
margin-top: 12px;
}
.remove-files-setting {
display: block;
}
.remove-files-setting .setting-item-control {
padding: 0;
}
.remove-files-setting textarea {
width: 100%;
height: 300px;
margin-top: 12px;
}
.remove-files-setting textarea::placeholder {
opacity: 0.5;
}
2025-03-14 16:09:40 +08:00
`})}onClose(){let{contentEl:r}=this;r.empty()}};var loe=class{get usageData(){return pe().promptUsageTimestamps}recordUsage(t){It("promptUsageTimestamps",{...this.usageData,[t]:Date.now()})}updateUsage(t,r){let n={...this.usageData};n[r]=n[t],delete n[t],It("promptUsageTimestamps",n)}removeUnusedPrompts(t){let r={...this.usageData};for(let n of Object.keys(r))t.includes(n)||delete r[n];It("promptUsageTimestamps",r)}compare(t,r){return(this.usageData[t]||0)-(this.usageData[r]||0)}};var ST=require("obsidian"),UC=class e{constructor(t){this.vault=t;this.lastProcessedPrompt=null;this.usageStrategy=new loe}get customPromptsFolder(){return pe().customPromptsFolder}static getInstance(t){return e.instance||(e.instance=new e(t)),e.instance}recordPromptUsage(t){this.usageStrategy.recordUsage(t)}async getAllPrompts(){let t=this.customPromptsFolder,r=this.vault.getFiles().filter(o=>o.path.startsWith(t)&&o.extension==="md"),n=[];for(let o of r){let i=await this.vault.read(o);n.push({title:o.basename,content:i})}return this.usageStrategy.removeUnusedPrompts(n.map(o=>o.title)),n.sort((o,i)=>this.usageStrategy.compare(i.title,o.title)||0)}async getPrompt(t){let r=`${this.customPromptsFolder}/${t}.md`,n=this.vault.getAbstractFileByPath(r);if(n instanceof ST.TFile){let o=await this.vault.read(n);return{title:t,content:o}}return null}async savePrompt(t,r){let n=(0,ST.normalizePath)(this.customPromptsFolder),o=`${n}/${t}.md`;await this.vault.adapter.exists(n)||await this.vault.createFolder(n),await this.vault.create(o,r)}async updatePrompt(t,r,n){let o=`${this.customPromptsFolder}/${t}.md`,i=this.vault.getAbstractFileByPath(o);if(i instanceof ST.TFile){if(t!==r){let a=`${this.customPromptsFolder}/${r}.md`;if(this.vault.getAbstractFileByPath(a))throw new dr("Error saving custom prompt. Please check if the title already exists.");this.usageStrategy.updateUsage(t,r),await this.vault.rename(i,a)}await this.vault.modify(i,n)}}async deletePrompt(t){let r=`${this.customPromptsFolder}/${t}.md`,n=this.vault.getAbstractFileByPath(r);n instanceof ST.TFile&&(this.usageStrategy.removeUnusedPrompts([t]),await this.vault.delete(n))}async extractVariablesFromPrompt(t,r){let n=[],o=/\{([^}]+)\}/g,i;for(;(i=o.exec(t))!==null;){let a=i[1].trim(),s=[];if(a.toLowerCase()==="activenote")if(r){let u=await oj(r,this.vault);u&&s.push({name:r5(r),content:u})}else new ST.Notice("No active note found.");else if(a.startsWith("#")){let u=a.slice(1).split(",").map(c=>c.trim()),l=await Wke(this.vault,u);for(let c of l){let d=await oj(c,this.vault);d&&s.push({name:r5(c),content:d})}}else{let u=Kke(a),l=await xle(this.vault,u);for(let c of l){let d=await oj(c,this.vault);d&&s.push({name:r5(c),content:d})}}if(s.length>0){let u=s.map(l=>`## ${l.name}
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
${l.content}`).join(`
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
`);n.push(u)}else console.warn(`No notes found for variable: ${a}`)}return n}async processCustomPrompt(t,r,n){this.lastProcessedPrompt=t;let o=await this.extractVariablesFromPrompt(t,n),i=t,a=[...i.matchAll(/\{([^}]+)\}/g)],s="",u=null;i.includes("{}")&&(i=i.replace(/\{\}/g,"{selectedText}"),r?s+=`selectedText:
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
${r}`:n?(u=await oj(n,this.vault),s+=`selectedText (entire active note):
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
${u}`):s+=`selectedText:
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
(No selected text or active note available)`);for(let c=0;c<o.length;c++)if(a[c]){let d=a[c][1];if(d.toLowerCase()==="activenote"&&u)continue;s+=`
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
${d}:
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
${o[c]}`}let l=ly(i,this.vault);for(let c of l)if(!a.some(d=>d[1].includes(`[[${c.basename}]]`))){let d=await oj(c,this.vault);d&&(s+=`
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
Title: [[${c.basename}]]
Path: ${c.path}
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
${d}`)}return i+`
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
`+s}async getProcessedVariables(){let t=new Set,r=this.lastProcessedPrompt?.matchAll(/\{([^}]+)\}/g)||[];for(let o of r)t.add(o[1]);let n=ly(this.lastProcessedPrompt||"",this.vault);for(let o of n)t.add(`[[${o.basename}]]`);return t}};var yo=require("obsidian");function sd(e,t,r){e.addCommand({id:t,name:u5[t],callback:r})}function Rin(e,t,r){e.addCommand({id:t,name:u5[t],editorCallback:r})}function q1t(e,t,r){e.addCommand({id:t,name:u5[t],checkCallback:r})}async function Din(e,t){let r=e.getSelection().trim();if(!r)return;let n=N1t(t);if(!n){Ur(`Command not found for id ${t}`);return}new ioe(app,{selectedText:r,command:n}).open()}function jin(e,t,r){t.forEach(n=>{let o=SB(n.name);o&&e.removeCommand(o)}),r.forEach(n=>{let o=SB(n.name);e.addCommand({id:o,name:n.name,editorCallback:i=>{Din(i,o)}})})}function tMe(e,t,r){jin(e,t?.inlineEditCommands??[],r.inlineEditCommands??T1());let n=UC.getInstance(e.app.vault);Rin(e,rr.COUNT_WORD_AND_TOKENS_SELECTION,async o=>{let i=await o.getSelection(),a=i.split(" ").length,s=await e.chainManager.chatModelManager.countTokens(i);new yo.Notice(`Selected text contains ${a} words and ${s} tokens.`)}),sd(e,rr.COUNT_TOTAL_VAULT_TOKENS,async()=>{try{let o=await e0t(e.app),i=await e.chainManager.chatModelManager.countTokens(o);new yo.Notice(`Total tokens in your vault: ${i}`)}catch(o){console.error("Error counting tokens: ",o),new yo.Notice("An error occurred while counting tokens.")}}),sd(e,rr.TOGGLE_COPILOT_CHAT_WINDOW,()=>{e.toggleView()}),sd(e,rr.OPEN_COPILOT_CHAT_WINDOW,()=>{e.activateView()}),sd(e,rr.ADD_CUSTOM_PROMPT,()=>{new Z8(e.app,async(o,i)=>{try{await n.savePrompt(o,i),new yo.Notice("Custom prompt saved successfully.")}catch(a){let s="An error occurred while saving the custom prompt: "+bi(a);throw console.error(s),new Error(s)}}).open()}),sd(e,rr.APPLY_CUSTOM_PROMPT,async()=>{let i=(await n.getAllPrompts()).map(a=>a.title);new qC(e.app,i,async a=>{if(!a){new yo.Notice("Please select a prompt title.");return}try{let s=await n.getPrompt(a);if(!s){new yo.Notice(`No prompt found with the title "${a}".`);return}e.processCustomPrompt(rr.APPLY_CUSTOM_PROMPT,s.content)}catch(s){console.error(s),new yo.Notice("An error occurred.")}}).open()}),sd(e,rr.APPLY_ADHOC_PROMPT,async()=>{new roe(e.app,async i=>{try{e.processCustomPrompt(rr.APPLY_ADHOC_PROMPT,i)}catch(a){console.error(a),new yo.Notice("An error occurred.")}}).open()}),q1t(e,rr.DELETE_CUSTOM_PROMPT,o=>(o||n.getAllPrompts().then(i=>{let a=i.map(s=>s.title);new qC(e.app,a,async s=>{if(!s){new yo.Notice("Please select a prompt title.");return}try{await n.deletePrompt(s),new yo.Notice(`Prompt "${s}" has been deleted.`)}catch(u){console.error(u),new yo.Notice("An error occurred while deleting the prompt.")}}).open()}),!0)),q1t(e,rr.EDIT_CUSTOM_PROMPT,o=>(o||n.getAllPrompts().then(i=>{let a=i.map(s=>s.title);new qC(e.app,a,async s=>{if(!s){new yo.Notice("Please select a prompt title.");return}try{let u=await n.getPrompt(s);u?new Z8(e.app,async(l,c)=>{try{await n.updatePrompt(s,l,c),new yo.Notice(`Prompt "${l}" has been updated.`)}catch(d){let f="An error occurred while updating the custom prompt: "+bi(d);throw console.error(f),new Error(f)}},u.title,u.content,!1).open():new yo.Notice(`No prompt found with the title "${s}".`)}catch(u){console.error(u),new yo.Notice("An error occurred.")}}).open()}),!0)),sd(e,rr.CLEAR_LOCAL_COPILOT_INDEX,async()=>{await e.vectorStoreManager.clearIndex()}),sd(e,rr.GARBAGE_COLLECT_COPILOT_INDEX,async()=>{try{let o=await e.vectorStoreManager.garbageCollectVectorStore();new yo.Notice(`${o} documents removed from Copilot index.`)}catch(o){console.error("Error garbage collecting the Copilot index:",o),new yo.Notice("An error occurred while garbage collecting the Copilot index.")}}),sd(e,rr.INDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let o=await e.vectorStoreManager.indexVaultToVectorStore();new yo.Notice(`${o} vault files indexed to Copilot index.`)}catch(o){console.error("Error indexing vault to Copilot index:",o),new yo.Notice("An error occurred while indexing vault to Copilot index.")}}),sd(e,rr.FORCE_REINDEX_VA
`),p=`${`Copilot-Indexed-Files-${new Date().toLocaleDateString().replace(/\//g,"-")}.md`}`,h=e.app.vault.getAbstractFileByPath(p);h instanceof yo.TFile?await e.app.vault.modify(h,d):await e.app.vault.create(p,d);let m=e.app.vault.getAbstractFileByPath(p);m instanceof yo.TFile&&(await e.app.workspace.getLeaf().openFile(m),new yo.Notice(`Listed ${o.length} indexed files`))}catch(o){console.error("Error listing indexed files:",o),new yo.Notice("Failed to list indexed files.")}}),sd(e,rr.REMOVE_FILES_FROM_COPILOT_INDEX,async()=>{new uoe(e.app,async o=>{let i=await e.vectorStoreManager.getDbOps();try{for(let a of o)await i.removeDocs(a);await i.saveDB(),new yo.Notice(`Successfully removed ${o.length} files from the index.`)}catch(a){console.error("Error removing files from index:",a),new yo.Notice("An error occurred while removing files from the index.")}}).open()}),sd(e,rr.CLEAR_COPILOT_CACHE,async()=>{try{await e.fileParserManager.clearPDFCache(),new yo.Notice("Copilot cache cleared successfully")}catch(o){console.error("Error clearing Copilot cache:",o),new yo.Notice("Failed to clear Copilot cache")}})}var hr=B(Y());var el=B(Y(),1);function eH(e,t,{checkForDefaultPrevented:r=!0}={}){return function(o){if(e?.(o),r===!1||!o.defaultPrevented)return t?.(o)}}var Nin=B(Y(),1);function U1t(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function coe(...e){return t=>{let r=!1,n=e.map(o=>{let i=U1t(o,t);return!r&&typeof i=="function"&&(r=!0),i});if(r)return()=>{for(let o=0;o<n.length;o++){let i=n[o];typeof i=="function"?i():U1t(e[o],null)}}}}var hm=B(Y(),1),rMe=B(lt(),1);function z1t(e,t){let r=hm.createContext(t),n=i=>{let{children:a,...s}=i,u=hm.useMemo(()=>s,Object.values(s));return(0,rMe.jsx)(r.Provider,{value:u,children:a})};n.displayName=e+"Provider";function o(i){let a=hm.useContext(r);if(a)return a;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return[n,o]}function Ro(e,t=[]){let r=[];function n(i,a){let s=hm.createContext(a),u=r.length;r=[...r,a];let l=d=>{let{scope:f,children:p,...h}=d,m=f?.[e]?.[u]||s,_=hm.useMemo(()=>h,Object.values(h));return(0,rMe.jsx)(m.Provider,{value:_,children:p})};l.displayName=i+"Provider";function c(d,f){let p=f?.[e]?.[u]||s,h=hm.useContext(p);if(h)return h;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[l,c]}let o=()=>{let i=r.map(a=>hm.createContext(a));return function(s){let u=s?.[e]||i;return hm.useMemo(()=>({[`__scope${e}`]:{...s,[e]:u}}),[s,u])}};return o.scopeName=e,[n,Lin(o,...t)]}function Lin(...e){let t=e[0];if(e.length===1)return t;let r=()=>{let n=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let a=n.reduce((s,{useScope:u,scopeName:l})=>{let d=u(i)[`__scope${l}`];return{...s,...d}},{});return hm.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return r.scopeName=t.scopeName,r}var xT=B(Y(),1);var xB=B(Y(),1);function Wt(e){let t=xB.useRef(e);return xB.useEffect(()=>{t.current=e}),xB.useMemo(()=>(...r)=>t.current?.(...r),[])}function Qu({prop:e,defaultProp:t,onChange:r=()=>{}}){let[n,o]=Fin({defaultProp:t,onChange:r}),i=e!==void 0,a=i?e:n,s=Wt(r),u=xT.useCallback(l=>{if(i){let d=typeof l=="function"?l(e):l;d!==e&&s(d)}else o(l)},[i,e,o,s]);return[a,u]}function Fin({defaultProp:e,onChange:t}){let r=xT.useState(e),[n]=r,o=xT.useRef(n),i=Wt(t);return xT.useEffect(()=>{o.current!==n&&(i(n),o.current=n)},[n,o,i]),r}var H1t=B(Y(),1),Uin=B(as(),1);var pc=B(Y(),1);var CB=B(lt(),1),oMe=pc.forwardRef((e,t)=>{let{children:r,...n}=e,o=pc.Children.toArray(r),i=o.find(Bin);if(i){let a=i.props.children,s=o.map(u=>u===i?pc.Children.count(a)>1?pc.Children.only(null):pc.isValidElement(a)?a.props.children:null:u);return(0,CB.jsx)(nMe,{...n,ref:t,children:pc.isValidElement(a)?pc.cloneElement(a,void 0,s):null})}return(0,CB.jsx)(nMe,{...n,ref:t,children:r})});oMe.displayName="Slot";var nMe=pc.forwardRef((e,t)=>{let{children:r,...n}=e;if(pc.isValidElement(r)){let o=qin(r);return pc.cloneElement(r,{...$in(n,r.props),ref:t?coe(t,o):o})}return pc.Children.count(r)>1?pc.Children.only(null):null});nMe
.`.concat(DMe,` {
overflow: hidden `).concat(n,`;
padding-right: `).concat(s,"px ").concat(n,`;
2025-01-09 14:41:22 +08:00
}
2025-03-14 16:09:40 +08:00
body[`).concat(DB,`] {
overflow: hidden `).concat(n,`;
overscroll-behavior: contain;
`).concat([t&&"position: relative ".concat(n,";"),r==="margin"&&`
padding-left: `.concat(o,`px;
padding-top: `).concat(i,`px;
padding-right: `).concat(a,`px;
margin-left:0;
margin-top:0;
margin-right: `).concat(s,"px ").concat(n,`;
`),r==="padding"&&"padding-right: ".concat(s,"px ").concat(n,";")].filter(Boolean).join(""),`
2025-01-09 14:41:22 +08:00
}
2025-03-14 16:09:40 +08:00
.`).concat(qg,` {
right: `).concat(s,"px ").concat(n,`;
2025-01-09 14:41:22 +08:00
}
2025-03-14 16:09:40 +08:00
.`).concat(Ug,` {
margin-right: `).concat(s,"px ").concat(n,`;
2025-01-09 14:41:22 +08:00
}
2025-03-14 16:09:40 +08:00
.`).concat(qg," .").concat(qg,` {
right: 0 `).concat(n,`;
2025-01-09 14:41:22 +08:00
}
2025-03-14 16:09:40 +08:00
.`).concat(Ug," .").concat(Ug,` {
margin-right: 0 `).concat(n,`;
2025-01-09 14:41:22 +08:00
}
2025-03-14 16:09:40 +08:00
body[`).concat(DB,`] {
`).concat(jMe,": ").concat(s,`px;
}
`)},Bjt=function(){var e=parseInt(document.body.getAttribute(DB)||"0",10);return isFinite(e)?e:0},xsn=function(){jB.useEffect(function(){return document.body.setAttribute(DB,(Bjt()+1).toString()),function(){var e=Bjt()-1;e<=0?document.body.removeAttribute(DB):document.body.setAttribute(DB,e.toString())}},[])},B1=function(e){var t=e.noRelative,r=e.noImportant,n=e.gapMode,o=n===void 0?"margin":n;xsn();var i=jB.useMemo(function(){return BMe(o)},[o]);return jB.createElement(wsn,{styles:Ssn(i,!t,o,r?"":"!important")})};var $Me=!1;if(typeof window<"u")try{lH=Object.defineProperty({},"passive",{get:function(){return $Me=!0,!0}}),window.addEventListener("test",lH,lH),window.removeEventListener("test",lH,lH)}catch{$Me=!1}var lH,$1=$Me?{passive:!1}:!1;var Csn=function(e){return e.tagName==="TEXTAREA"},$jt=function(e,t){if(!(e instanceof Element))return!1;var r=window.getComputedStyle(e);return r[t]!=="hidden"&&!(r.overflowY===r.overflowX&&!Csn(e)&&r[t]==="visible")},Osn=function(e){return $jt(e,"overflowY")},Esn=function(e){return $jt(e,"overflowX")},qMe=function(e,t){var r=t.ownerDocument,n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var o=qjt(e,n);if(o){var i=Ujt(e,n),a=i[1],s=i[2];if(a>s)return!0}n=n.parentNode}while(n&&n!==r.body);return!1},Psn=function(e){var t=e.scrollTop,r=e.scrollHeight,n=e.clientHeight;return[t,r,n]},Tsn=function(e){var t=e.scrollLeft,r=e.scrollWidth,n=e.clientWidth;return[t,r,n]},qjt=function(e,t){return e==="v"?Osn(t):Esn(t)},Ujt=function(e,t){return e==="v"?Psn(t):Tsn(t)},Msn=function(e,t){return e==="h"&&t==="rtl"?-1:1},zjt=function(e,t,r,n,o){var i=Msn(e,window.getComputedStyle(t).direction),a=i*n,s=r.target,u=t.contains(s),l=!1,c=a>0,d=0,f=0;do{var p=Ujt(e,s),h=p[0],m=p[1],_=p[2],g=m-_-i*h;(h||g)&&qjt(e,s)&&(d+=g,f+=h),s instanceof ShadowRoot?s=s.host:s=s.parentNode}while(!u&&s!==document.body||u&&(t.contains(s)||t===s));return(c&&(o&&Math.abs(d)<1||!o&&a>d)||!c&&(o&&Math.abs(f)<1||!o&&-a>f))&&(l=!0),l};var Loe=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Hjt=function(e){return[e.deltaX,e.deltaY]},Vjt=function(e){return e&&"current"in e?e.current:e},Isn=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Asn=function(e){return`
.block-interactivity-`.concat(e,` {pointer-events: none;}
.allow-interactivity-`).concat(e,` {pointer-events: all;}
`)},Rsn=0,NB=[];function Wjt(e){var t=Ii.useRef([]),r=Ii.useRef([0,0]),n=Ii.useRef(),o=Ii.useState(Rsn++)[0],i=Ii.useState(WC)[0],a=Ii.useRef(e);Ii.useEffect(function(){a.current=e},[e]),Ii.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var m=RB([e.lockRef.current],(e.shards||[]).map(Vjt),!0).filter(Boolean);return m.forEach(function(_){return _.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),m.forEach(function(_){return _.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var s=Ii.useCallback(function(m,_){if("touches"in m&&m.touches.length===2||m.type==="wheel"&&m.ctrlKey)return!a.current.allowPinchZoom;var g=Loe(m),v=r.current,S="deltaX"in m?m.deltaX:v[0]-g[0],x="deltaY"in m?m.deltaY:v[1]-g[1],O,T=m.target,E=Math.abs(S)>Math.abs(x)?"h":"v";if("touches"in m&&E==="h"&&T.type==="range")return!1;var M=qMe(E,T);if(!M)return!0;if(M?O=E:(O=E==="v"?"h":"v",M=qMe(E,T)),!M)return!1;if(!n.current&&"changedTouches"in m&&(S||x)&&(n.current=O),!O)return!0;var A=n.current||O;return zjt(A,_,m,A==="h"?S:x,!0)},[]),u=Ii.useCallback(function(m){var _=m;if(!(!NB.length||NB[NB.length-1]!==i)){var g="deltaY"in _?Hjt(_):Loe(_),v=t.current.filter(function(O){return O.name===_.type&&(O.target===_.target||_.target===O.shadowParent)&&Isn(O.delta,g)})[0];if(v&&v.should){_.cancelable&&_.preventDefault();return}if(!v){var S=(a.current.shards||[]).map(Vjt).filter(Boolean).filter(function(O){return O.contains(_.target)}),x=S.length>0?s(_,S[0]):!a.current.noIsolation;x&&_.cancelable&&_.preventDefault()}}},[]),l=Ii.useCallback(function(m,_,g,v){var S={name:m,delta:_,target:g,should:v,shadowParent:Dsn(g)};t.current.push(S),setTimeout(function(){t.current=t.current.filter(function(x){return x!==S})},1)},[]),c=Ii.useCallback(function(m){r.current=Loe(m),n.current=void 0},[]),d=Ii.useCallback(function(m){l(m.type,Hjt(m),m.target,s(m,e.lockRef.current))},[]),f=Ii.useCallback(function(m){l(m.type,Loe(m),m.target,s(m,e.lockRef.current))},[]);Ii.useEffect(function(){return NB.push(i),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,$1),document.addEventListener("touchmove",u,$1),document.addEventListener("touchstart",c,$1),function(){NB=NB.filter(function(m){return m!==i}),document.removeEventListener("wheel",u,$1),document.removeEventListener("touchmove",u,$1),document.removeEventListener("touchstart",c,$1)}},[]);var p=e.removeScrollBar,h=e.inert;return Ii.createElement(Ii.Fragment,null,h?Ii.createElement(i,{styles:Asn(o)}):null,p?Ii.createElement(B1,{gapMode:e.gapMode}):null)}function Dsn(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var Jjt=k1(Noe,Wjt);var Gjt=Foe.forwardRef(function(e,t){return Foe.createElement(uH,Do({},e,{ref:t,sideCar:Jjt}))});Gjt.classNames=uH.classNames;var UMe=Gjt;var tr=B(lt(),1),zMe=["Enter"," "],jsn=["ArrowDown","PageUp","Home"],Yjt=["ArrowUp","PageDown","End"],Nsn=[...jsn,...Yjt],Lsn={ltr:[...zMe,"ArrowRight"],rtl:[...zMe,"ArrowLeft"]},Fsn={ltr:["ArrowLeft"],rtl:["ArrowRight"]},pH="Menu",[dH,ksn,Bsn]=K1t(pH),[q1,HMe]=Ro(pH,[Bsn,SMe,AMe]),hH=SMe(),Zjt=AMe(),[Xjt,UT]=q1(pH),[$sn,mH]=q1(pH),Qjt=e=>{let{__scopeMenu:t,open:r=!1,children:n,dir:o,onOpenChange:i,modal:a=!0}=e,s=hH(t),[u,l]=vt.useState(null),c=vt.useRef(!1),d=Wt(i),f=ET(o);return vt.useEffect(()=>{let p=()=>{c.current=!0,document.addEventListener("pointerdown",h,{capture:!0,once:!0}),document.addEventListener("pointermove",h,{capture:!0,once:!0})},h=()=>c.current=!1;return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",h,{capture:!0}),document.removeEventListener("pointermove",h,{capture:!0})}},[]),(0,tr.jsx)(CMe,{...s,children:(0,tr.jsx)(Xjt,{scope:t,open:r,onOpenChange:d,content:u,onContentChange:l,children:(0,tr.jsx)($sn,{scope:t,onClose:vt.useCallback(()=>d(!1),[d]),isUsingKeyboardRef
Embedded PDF (${s}):
${l}
`)}catch(l){console.error(`Error processing embedded PDF ${s}:`,l),t=t.replace(a[0],`
Embedded PDF (${s}): [Error: Could not process PDF]
`)}}return t}async processContextNotes(t,r,n,o,i,a,s){let u=await t.getProcessedVariables(),l="",c=async d=>{try{let f=`[[${d.basename}]]`;if(u.has(f))return;if(s!=="copilot_plus"&&d.extension!=="md"){r.supportsExtension(d.extension)?console.warn(`File type ${d.extension} only supported in Copilot Plus mode`):console.warn(`Unsupported file type: ${d.extension}`);return}if(!r.supportsExtension(d.extension)){console.warn(`Unsupported file type: ${d.extension}`);return}let p=await r.parseFile(d,n);d.extension==="md"&&s==="copilot_plus"&&(p=await this.processEmbeddedPDFs(p,n,r)),l+=`
Title: [[${d.basename}]]
Path: ${d.path}
${p}`}catch(f){console.error(`Error processing file ${d.path}:`,f),l+=`
Title: [[${d.basename}]]
Path: ${d.path}
[Error: Could not process file]`}};if(i&&a){let d="activeNote",f=`[[${a.basename}]]`;!u.has(d)&&!u.has(f)&&await c(a)}for(let d of o)await c(d);return l}async hasEmbeddedPDFs(t){return/!\[\[(.*?\.pdf)\]\]/g.test(t)}async addNoteToContext(t,r,n,o,i,a){if(n.some(l=>l.path===t.path))return;let s=await r.read(t),u=await this.hasEmbeddedPDFs(s);o&&t.path===o.path&&a(!0),i(l=>[...l,Object.assign(t,{wasAddedViaReference:!0,hasEmbeddedPDFs:u})])}};var qB=require("obsidian"),Ge=B(Y());var Vr=B(Y()),Go=B(tFt());function WT(e,t,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(c){try{l(n.next(c))}catch(d){a(d)}}function u(c){try{l(n.throw(c))}catch(d){a(d)}}function l(c){c.done?i(c.value):o(c.value).then(s,u)}l((n=n.apply(e,t||[])).next())})}var Tln=new Map([["1km","application/vnd.1000minds.decision-model+xml"],["3dml","text/vnd.in3d.3dml"],["3ds","image/x-3ds"],["3g2","video/3gpp2"],["3gp","video/3gp"],["3gpp","video/3gpp"],["3mf","model/3mf"],["7z","application/x-7z-compressed"],["7zip","application/x-7z-compressed"],["123","application/vnd.lotus-1-2-3"],["aab","application/x-authorware-bin"],["aac","audio/x-acc"],["aam","application/x-authorware-map"],["aas","application/x-authorware-seg"],["abw","application/x-abiword"],["ac","application/vnd.nokia.n-gage.ac+xml"],["ac3","audio/ac3"],["acc","application/vnd.americandynamics.acc"],["ace","application/x-ace-compressed"],["acu","application/vnd.acucobol"],["acutc","application/vnd.acucorp"],["adp","audio/adpcm"],["aep","application/vnd.audiograph"],["afm","application/x-font-type1"],["afp","application/vnd.ibm.modcap"],["ahead","application/vnd.ahead.space"],["ai","application/pdf"],["aif","audio/x-aiff"],["aifc","audio/x-aiff"],["aiff","audio/x-aiff"],["air","application/vnd.adobe.air-application-installer-package+zip"],["ait","application/vnd.dvb.ait"],["ami","application/vnd.amiga.ami"],["amr","audio/amr"],["apk","application/vnd.android.package-archive"],["apng","image/apng"],["appcache","text/cache-manifest"],["application","application/x-ms-application"],["apr","application/vnd.lotus-approach"],["arc","application/x-freearc"],["arj","application/x-arj"],["asc","application/pgp-signature"],["asf","video/x-ms-asf"],["asm","text/x-asm"],["aso","application/vnd.accpac.simply.aso"],["asx","video/x-ms-asf"],["atc","application/vnd.acucorp"],["atom","application/atom+xml"],["atomcat","application/atomcat+xml"],["atomdeleted","application/atomdeleted+xml"],["atomsvc","application/atomsvc+xml"],["atx","application/vnd.antix.game-component"],["au","audio/x-au"],["avi","video/x-msvideo"],["avif","image/avif"],["aw","application/applixware"],["azf","application/vnd.airzip.filesecure.azf"],["azs","application/vnd.airzip.filesecure.azs"],["azv","image/vnd.airzip.accelerator.azv"],["azw","application/vnd.amazon.ebook"],["b16","image/vnd.pco.b16"],["bat","application/x-msdownload"],["bcpio","application/x-bcpio"],["bdf","application/x-font-bdf"],["bdm","application/vnd.syncml.dm+wbxml"],["bdoc","application/x-bdoc"],["bed","application/vnd.realvnc.bed"],["bh2","application/vnd.fujitsu.oasysprs"],["bin","application/octet-stream"],["blb","application/x-blorb"],["blorb","application/x-blorb"],["bmi","application/vnd.bmi"],["bmml","application/vnd.balsamiq.bmml+xml"],["bmp","image/bmp"],["book","application/vnd.framemaker"],["box","application/vnd.previewsystems.box"],["boz","application/x-bzip2"],["bpk","application/octet-stream"],["bpmn","application/octet-stream"],["bsp","model/vnd.valve.source.compiled-map"],["btif","image/prs.btif"],["buffer","application/octet-stream"],["bz","application/x-bzip"],["bz2","application/x-bzip2"],["c","text/x-c"],["c4d","application/vnd.clonk.c4group"],["c4f","application/vnd.clonk.c4group"],["c4g","application/vnd.clonk.c4group"],["c4p","application/vnd.clonk.c4group"],["c4u","application/vnd.clonk.c4group"],["c11amc","application/vnd.cluetrust.cartomobile-config"],["c11amz","application/vnd.cluetrust.cartomobile-config-pkg"],["cab","application/vnd.ms-cab-compressed"],["caf","audio/x-c
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function $ln(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function qln(e){if(Array.isArray(e))return RIe(e)}function lFt(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(o){return Object.getOwnPropertyDescriptor(e,o).enumerable})),r.push.apply(r,n)}return r}function cFt(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?lFt(Object(r),!0).forEach(function(n){pFt(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):lFt(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function pFt(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function wH(e,t){return Hln(e)||zln(e,t)||hFt(e,t)||Uln()}function Uln(){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 hFt(e,t){if(e){if(typeof e=="string")return RIe(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return RIe(e,t)}}function RIe(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function zln(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n=[],o=!0,i=!1,a,s;try{for(r=r.call(e);!(o=(a=r.next()).done)&&(n.push(a.value),!(t&&n.length===t));o=!0);}catch(u){i=!0,s=u}finally{try{!o&&r.return!=null&&r.return()}finally{if(i)throw s}}return n}}function Hln(e){if(Array.isArray(e))return e}var Vln=typeof Xoe.default=="function"?Xoe.default:Xoe.default.default,Wln="file-invalid-type",Jln="file-too-large",Gln="file-too-small",Kln="too-many-files";var Yln=function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",r=t.split(","),n=r.length>1?"one of ".concat(r.join(", ")):r[0];return{code:Wln,message:"File type must be ".concat(n)}},dFt=function(t){return{code:Jln,message:"File is larger than ".concat(t," ").concat(t===1?"byte":"bytes")}},fFt=function(t){return{code:Gln,message:"File is smaller than ".concat(t," ").concat(t===1?"byte":"bytes")}},mFt={code:Kln,message:"Too many files"};function DIe(e,t){var r=e.type==="application/x-moz-file"||Vln(e,t);return[r,r?null:Yln(t)]}function jIe(e,t,r){if(z1(e.size))if(z1(t)&&z1(r)){if(e.size>r)return[!1,dFt(r)];if(e.size<t)return[!1,fFt(t)]}else{if(z1(t)&&e.size<t)return[!1,fFt(t)];if(z1(r)&&e.size>r)return[!1,dFt(r)]}return[!0,null]}function z1(e){return e!=null}function gFt(e){var t=e.files,r=e.accept,n=e.minSize,o=e.maxSize,i=e.multiple,a=e.maxFiles,s=e.validator;return!i&&t.length>1||i&&a>=1&&t.length>a?!1:t.every(function(u){var l=DIe(u,r),c=wH(l,1),d=c[0],f=jIe(u,n,o),p=wH(f,1),h=p[0],m=s?s(u):null;return d&&h&&!m})}function SH(e){return typeof e.isPropagationStopped=="function"?e.isPropagationStopped():typeof e.cancelBubble<"u"?e.cancelBubble:!1}function xH(e){return e.dataTransfer?Array.prototype.some.call(e.dataTransfer.types,function(t){return t==="Files"||t==="application/x-moz-file"}):!!e.target&&!!e.target.files}function NIe(e){e.preventDefault()}function Zln(e){return e.indexOf("MSIE")!==-1||e.indexOf("Trident/")!==-1}function Xln(e){return e.indexOf("Edge/")!==-1}function yFt(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.navigator.userAgent;return Zln(e)||Xln(e)}function Hg(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[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 t.some(function(s){return!SH(n)&&s&&s.apply(void 0,[n].concat(i)),SH(n)})}}function bFt(){return"showOpenFilePicker"in window}function _Ft(e){if(z1(e)){var t=Object.entries(e).filter(function(r){var n=wH(r,2),o=n[0],i=n[1],a=!0;return xFt(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(CFt))&&(console.warn('Skipped "'.concat(o,'" because an invalid file extension was provided.')),a=!1),a}).reduce(function(r,n){var o=wH(n,2),i=o[0],a=o[1];return cFt(cFt({},r),{},pFt({},i,a))},{});return[{description:"Files",accept:t}]}return e}function vFt(e){if(z1(e))return Object.entries(e).reduce(function(t,r){var n=wH(r,2),o=n[0],i=n[1];return[].concat(uFt(t),[o],uFt(i))},[]).filter(function(t){return xFt(t)||CFt(t)}).join(",")}function wFt(e){return e instanceof DOMException&&(e.name==="AbortError"||e.code===e.ABORT_ERR)}function SFt(e){return e instanceof DOMException&&(e.name==="SecurityError"||e.code===e.SECURITY_ERR)}function xFt(e){return e==="audio/*"||e==="video/*"||e==="image/*"||e==="text/*"||e==="application/*"||/\w+\/[-+.\w]+/g.test(e)}function
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function icn(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function acn(e){if(Array.isArray(e))return FIe(e)}function LIe(e,t){return lcn(e)||ucn(e,t)||PFt(e,t)||scn()}function scn(){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 PFt(e,t){if(e){if(typeof e=="string")return FIe(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return FIe(e,t)}}function FIe(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function ucn(e,t){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var n=[],o=!0,i=!1,a,s;try{for(r=r.call(e);!(o=(a=r.next()).done)&&(n.push(a.value),!(t&&n.length===t));o=!0);}catch(u){i=!0,s=u}finally{try{!o&&r.return!=null&&r.return()}finally{if(i)throw s}}return n}}function lcn(e){if(Array.isArray(e))return e}function OFt(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(o){return Object.getOwnPropertyDescriptor(e,o).enumerable})),r.push.apply(r,n)}return r}function wa(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?OFt(Object(r),!0).forEach(function(n){kIe(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):OFt(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function kIe(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Qoe(e,t){if(e==null)return{};var r=ccn(e,t),n,o;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(o=0;o<i.length;o++)n=i[o],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function ccn(e,t){if(e==null)return{};var r={},n=Object.keys(e),o,i;for(i=0;i<n.length;i++)o=n[i],!(t.indexOf(o)>=0)&&(r[o]=e[o]);return r}var $Ie=(0,Vr.forwardRef)(function(e,t){var r=e.children,n=Qoe(e,Qln),o=qIe(n),i=o.open,a=Qoe(o,ecn);return(0,Vr.useImperativeHandle)(t,function(){return{open:i}},[i]),Vr.default.createElement(Vr.Fragment,null,r(wa(wa({},a),{},{open:i})))});$Ie.displayName="Dropzone";var TFt={disabled:!1,getFilesFromEvent:IIe,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};$Ie.defaultProps=TFt;$Ie.propTypes={children:Go.default.func,accept:Go.default.objectOf(Go.default.arrayOf(Go.default.string)),multiple:Go.default.bool,preventDropOnDocument:Go.default.bool,noClick:Go.default.bool,noKeyboard:Go.default.bool,noDrag:Go.default.bool,noDragEventsBubbling:Go.default.bool,minSize:Go.default.number,maxSize:Go.default.number,maxFiles:Go.default.number,disabled:Go.default.bool,getFilesFromEvent:Go.default.func,onFileDialogCancel:Go.default.func,onFileDialogOpen:Go.default.func,useFsAccessApi:Go.default.bool,autoFocus:Go.default.bool,onDragEnter:Go.default.func,onDragLeave:Go.default.func,onDragOver:Go.default.func,onDrop:Go.default.func,onDropAccepted:Go.default.func,onDropRejected:Go.default.func,onError:Go.default.func,validator:Go.default.func};var BIe={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function qIe(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=wa(wa({},TFt),e),r=t.accept,n=t.disabled,o=t.getFilesFromEvent,i=t.maxSize,a=t.minSize,s=t.multiple,u=t.maxFiles,l=t.onDragEnter,c=t.onDragLeave,d=t.onDragOver,f=t.onDrop,p=t.onDropAccepted,h=t.onDropRejected,m=t.onFileDialogCancel,_=t.onFileDialogOpen,g=t.useFsAccessApi,v=t.autoFocus,S=t.preventDropOnDocument,x=t.noClick,O=t.noKeyboard,T=t.noDrag,E=t.noDragEventsBubbling,M=t.onError,A=t.validator,j=(0,Vr.useMemo)(function(){return vFt(r)},[r]),N=(0,Vr.useMemo)(function(){return _Ft(r)},[r]),F=(0,Vr.useMemo)(function(){return typeof _=="function"?_:EFt},[_]),k=(0,Vr.useMemo)(function(){return typeof m=="function"?m:EFt},[m]),L=(0,Vr.useRef)(null),q=(0,Vr.useRef)(null),U=(0,Vr
`),Je=Ue.substring(0,ge).split(`
`).length-1;if(ie.key==="Enter"&&ie.shiftKey&&(qB.Platform.isMacOS?ie.metaKey:ie.ctrlKey)){ie.preventDefault(),ie.stopPropagation(),D(!0),g(-1),S("");return}if(ie.key==="Enter"&&!ie.shiftKey)ie.preventDefault(),D(!1),g(-1),S("");else if(ie.key==="ArrowUp"){if(Je>0||ge>0)return;ie.preventDefault(),_===-1&&Ue.trim()!==""&&S(Ue);let sr=a("up");sr!==e&&(g(_+1),t(sr),setTimeout(()=>{ee&&(ee.selectionStart=ee.selectionEnd=0)},0))}else if(ie.key==="ArrowDown"){if(Je<ct.length-1||ge<Ue.length)return;if(ie.preventDefault(),_>-1){let sr=a("down");g(_-1),t(_===0?v:sr),setTimeout(()=>{ee&&(ee.selectionStart=ee.selectionEnd=0)},0)}}},Q=(0,Ge.useCallback)(async ie=>{let ee=ie.clipboardData?.items;if(!ee||!V)return;let ge=Array.from(ee).filter(Ue=>Ue.type.indexOf("image")!==-1);if(ge.length>0){ie.preventDefault();let ct=(await Promise.all(ge.map(Je=>{let sr=Je.getAsFile();return sr||null}))).filter(Je=>Je!==null);ct.length>0&&p(ct)}},[p,V]);(0,Ge.useEffect)(()=>{let ie=new Set(ly(e,i.vault)),ee=d.extractAllUrls(e);u(ge=>ge.filter(Ue=>{if(Ue.wasAddedManually===!0)return!0;let Je=Ue.wasAddedViaReference===!0;return Ue.path===q?.path?Je?ie.has(Ue):l:Je?ie.has(Ue):!0})),E(ge=>ge.filter(Ue=>ee.includes(Ue)))},[e,l,q,d,u,i.vault]),(0,Ge.useEffect)(()=>{let ie,ee=()=>{clearTimeout(ie),ie=setTimeout(()=>{let Ue=i.workspace.getActiveFile();U(Ue)},100)},ge=i.workspace.on("active-leaf-change",ee);return()=>{clearTimeout(ie),i.workspace.offref(ge)}},[i.workspace]);let{getRootProps:ue,getInputProps:Me,isDragActive:ht}=qIe({accept:{"image/*":[".png",".gif",".jpeg",".jpg",".webp"]},onDrop:ie=>{p(ie)},noClick:!0,noDragEventsBubbling:!0}),we=(0,Ge.useMemo)(()=>[...s.map(ie=>ie.path),...l&&q?[q.path]:[]].filter(ie=>ie!=null),[s,l,q]);return Ge.default.createElement("div",{className:"flex flex-col gap-0.5 w-full border border-border border-solid rounded-md pt-2 pb-1 px-1 @container/chat-input",ref:A},Ge.default.createElement(RFt,{app:i,excludeNotePaths:we,contextNotes:s,setContextNotes:u,includeActiveNote:l,setIncludeActiveNote:c,activeNote:q,contextUrls:T,onRemoveUrl:ie=>E(ee=>ee.filter(ge=>ge!==ie))}),f.length>0&&Ge.default.createElement("div",{className:"selected-images"},f.map((ie,ee)=>Ge.default.createElement("div",{key:ee,className:"image-preview-container"},Ge.default.createElement("img",{src:URL.createObjectURL(ie),alt:ie.name,className:"selected-image-preview"}),Ge.default.createElement("button",{className:"remove-image-button",onClick:()=>h(ge=>ge.filter((Ue,ct)=>ct!==ee)),title:"Remove image"},Ge.default.createElement(bh,{className:"size-4"}))))),Ge.default.createElement("div",{className:"relative",...V?ue():{}},Ge.default.createElement("textarea",{ref:M,className:"w-full bg-transparent focus-visible:ring-0 border-none min-h-[60px] max-h-40 overflow-y-auto resize-none px-2 rounded-md text-sm text-normal",placeholder:"Ask anything. [[ for notes. / for custom prompts. "+(V?"@ for tools.":""),value:e,onChange:z,onKeyDown:Z,onPaste:Q}),V&&Ge.default.createElement(Ge.default.Fragment,null,Ge.default.createElement("input",{...Me()}),ht&&Ge.default.createElement("div",{className:"absolute inset-0 bg-primary border border-dashed border-primary rounded-md flex items-center justify-center"},Ge.default.createElement("span",{className:"text-primary"},"Drop images here...")))),Ge.default.createElement("div",{className:"flex gap-1 justify-between px-1 h-6"},n?Ge.default.createElement("div",{className:"flex items-center gap-1 px-1 text-faint text-sm"},Ge.default.createElement(Uc,{className:"size-3 animate-spin"}),Ge.default.createElement("span",null,"Generating...")):Ge.default.createElement(qoe,{open:x,onOpenChange:O},Ge.default.createElement(Uoe,{asChild:!0},Ge.default.createElement(qe,{variant:"ghost2",size:"fit"},F?Ge.default.createElement("span",{className:"text-error"},"Model Load Failed"):G.activeModels.find(ie=>ie.enabled&&Dr(ie)===j)?Ge.default.createElement(QTe,{model:G.activeModels.find(ie=>ie.enabled&&Dr(ie)===j),iconSize:8}):"Select Model",Ge.default.createElement(ss,{className:"size-5 mt-0.5"}))),Ge.default.createElement(zT,{align:"start"},G.a
<summary style="${J}">Thought for a second</summary>
<div class="text-muted" style="${te}">${Q.trim()}</div>
</details>
`),z=z.replace(/<think>([\s\S]*)$/,(Z,Q)=>`<div style="${W}">
<div style="${J}">Thinking...</div>
<div class="text-muted" style="${te}">${Q.trim()}</div>
</div>`),z;let Ae=/<think>([\s\S]*?)<\/think>/g;return z.replace(Ae,(Z,Q)=>`<details style="${W}">
<summary style="${J}">Thought for a second</summary>
<div class="text-muted" style="${te}">${Q.trim()}</div>
</details>
`)},L=(z,W,J)=>z.replace(W,(te,Ae)=>{let Z=t.metadataCache.getFirstLinkpathDest(Ae,F);return Z?J(Z):te}),q=j.replace(/\\\[\s*/g,"$$").replace(/\s*\\\]/g,"$$").replace(/\\\(\s*/g,"$").replace(/\s*\\\)/g,"$"),U=L(q,/!\[\[(.*?)]]/g,z=>`![](${t.vault.getResourcePath(z)})`),G=k(U),V=g(G);return L(V,/(?<!!)\[\[([^\]]+)]]/g,z=>`<a href="obsidian://open?file=${encodeURIComponent(z.path)}">${z.basename}</a>`)},[t,r]),g=j=>{let N=j.split(`
#### Sources:
`);if(N.length!==2)return j;let[F,k]=N,L=k.split(`
`).map(q=>{let U=q.match(/- \[\[(.*?)\]\]/);return U?`<li>[[${U[1]}]]</li>`:q}).join(`
`);return F+`
<br/>
<details><summary>Sources</summary>
<ul>
`+L+`
</ul>
</details>`};(0,Gt.useEffect)(()=>{if(f.current&&e.sender!==Uo){f.current.innerHTML="",p.current||(p.current=new H1.Component);let j=_(e.message);H1.MarkdownRenderer.renderMarkdown(j,f.current,"",p.current)}return()=>{p.current&&(p.current.unload(),p.current=null)}},[e,t,p,r,_]),(0,Gt.useEffect)(()=>{u&&h.current&&v(h.current)},[u]),(0,Gt.useEffect)(()=>{d(e.message)},[e.message]);let v=j=>{j.style.height="auto",j.style.height=`${j.scrollHeight}px`},S=j=>{d(j.target.value),v(j.target)},x=j=>{j.nativeEvent.isComposing||j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),T())},O=()=>{l(!0)},T=()=>{l(!1),o&&o(c)},E=()=>{e.sources&&e.sources.length>0&&new tie(t,e.sources).open()},M=()=>{let j=t.workspace.getMostRecentLeaf();if((!j||!(j.view instanceof H1.MarkdownView))&&(j=t.workspace.getLeaf(!1),!j||!(j.view instanceof H1.MarkdownView)))return;let F=j.view.editor.getSelection().length>0;yq(e.message,F)},A=()=>e.content?Gt.default.createElement("div",{className:"message-content-items"},e.content.map((j,N)=>j.type==="text"?Gt.default.createElement("div",{key:N,className:"message-text-content"},e.sender===Uo&&u?Gt.default.createElement("textarea",{ref:h,value:c,onChange:S,onKeyDown:x,onBlur:T,autoFocus:!0,className:"edit-textarea"}):e.sender===Uo?Gt.default.createElement("div",{className:"whitespace-pre-wrap break-words font-normal text-[calc(var(--font-text-size)_-_2px)]"},e.message):Gt.default.createElement("div",{ref:f,className:e.isErrorMessage?"text-error":""})):j.type==="image_url"?Gt.default.createElement("div",{key:N,className:"message-image-content"},Gt.default.createElement("img",{src:j.image_url.url,alt:"User uploaded image",className:"chat-message-image"})):null)):e.sender===Uo&&u?Gt.default.createElement("textarea",{ref:h,value:c,onChange:S,onKeyDown:x,onBlur:T,autoFocus:!0,className:"edit-textarea"}):e.sender===Uo?Gt.default.createElement("div",{className:"whitespace-pre-wrap break-words font-normal text-[calc(var(--font-text-size)_-_2px)]"},e.message):Gt.default.createElement("div",{ref:f,className:e.isErrorMessage?"text-error":""});return Gt.default.createElement("div",{className:"flex flex-col w-full my-1"},Gt.default.createElement("div",{className:_e("flex rounded-md p-2 mx-2 gap-2 group",e.sender===Uo&&"border border-border border-solid")},Gt.default.createElement("div",{className:"w-6 shrink-0"},e.sender===Uo?Gt.default.createElement(LU,null):Gt.default.createElement(_I,null)),Gt.default.createElement("div",{className:"flex flex-col flex-grow max-w-full gap-2"},!u&&Gt.default.createElement(mcn,{context:e.context}),Gt.default.createElement("div",{className:"message-content"},A()),!r&&Gt.default.createElement("div",{className:"flex justify-between items-center"},Gt.default.createElement("div",{className:"text-faint text-xs"},e.timestamp?.display),Gt.default.createElement(LFt,{message:e,onCopy:m,isCopied:a,onInsertIntoEditor:M,onRegenerate:n,onEdit:O,onDelete:i,onShowSources:E,hasSources:!!(e.sources&&e.sources.length>0)})))))},UIe=gcn;var Sc=B(Y(),1);function kFt(e,t,{checkForDefaultPrevented:r=!0}={}){return function(o){if(e?.(o),r===!1||!o.defaultPrevented)return t?.(o)}}var $Ft=B(Y(),1);function BFt(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function zIe(...e){return t=>{let r=!1,n=e.map(o=>{let i=BFt(o,t);return!r&&typeof i=="function"&&(r=!0),i});if(r)return()=>{for(let o=0;o<n.length;o++){let i=n[o];typeof i=="function"?i():BFt(e[o],null)}}}}function qFt(...e){return $Ft.useCallback(zIe(...e),e)}var UFt=B(Y(),1),wcn=B(as(),1);var wc=B(Y(),1);var UB=B(lt(),1),VIe=wc.forwardRef((e,t)=>{let{children:r,...n}=e,o=wc.Children.toArray(r),i=o.find(bcn);if(i){let a=i.props.children,s=o.map(u=>u===i?wc.Children.count(a)>1?wc.Children.only(null):wc.isValidElement(a)?a.props.children:null:u);return(0,UB.jsx)(HIe,{...n,ref:t,children:wc.isValidElement(a)?wc.cloneElement(a,void 0,s):null})}return(0,UB.jsx)(HIe,{...n,ref:t,children:r})});VIe.displayName="Slot";var HIe=wc.forwardRef((e,t)=>{let{children:r,...n}=e;if(wc.isValidElement(r)){let o=vcn(r);return wc.cloneElement(r,{..._cn(n,r.props),ref:t
.block-interactivity-`.concat(e,` {pointer-events: none;}
.allow-interactivity-`).concat(e,` {pointer-events: all;}
`)},cdn=0,HB=[];function Rkt(e){var t=Ri.useRef([]),r=Ri.useRef([0,0]),n=Ri.useRef(),o=Ri.useState(cdn++)[0],i=Ri.useState(WC)[0],a=Ri.useRef(e);Ri.useEffect(function(){a.current=e},[e]),Ri.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var m=RB([e.lockRef.current],(e.shards||[]).map(Akt),!0).filter(Boolean);return m.forEach(function(_){return _.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),m.forEach(function(_){return _.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var s=Ri.useCallback(function(m,_){if("touches"in m&&m.touches.length===2||m.type==="wheel"&&m.ctrlKey)return!a.current.allowPinchZoom;var g=iie(m),v=r.current,S="deltaX"in m?m.deltaX:v[0]-g[0],x="deltaY"in m?m.deltaY:v[1]-g[1],O,T=m.target,E=Math.abs(S)>Math.abs(x)?"h":"v";if("touches"in m&&E==="h"&&T.type==="range")return!1;var M=hAe(E,T);if(!M)return!0;if(M?O=E:(O=E==="v"?"h":"v",M=hAe(E,T)),!M)return!1;if(!n.current&&"changedTouches"in m&&(S||x)&&(n.current=O),!O)return!0;var A=n.current||O;return Mkt(A,_,m,A==="h"?S:x,!0)},[]),u=Ri.useCallback(function(m){var _=m;if(!(!HB.length||HB[HB.length-1]!==i)){var g="deltaY"in _?Ikt(_):iie(_),v=t.current.filter(function(O){return O.name===_.type&&(O.target===_.target||_.target===O.shadowParent)&&udn(O.delta,g)})[0];if(v&&v.should){_.cancelable&&_.preventDefault();return}if(!v){var S=(a.current.shards||[]).map(Akt).filter(Boolean).filter(function(O){return O.contains(_.target)}),x=S.length>0?s(_,S[0]):!a.current.noIsolation;x&&_.cancelable&&_.preventDefault()}}},[]),l=Ri.useCallback(function(m,_,g,v){var S={name:m,delta:_,target:g,should:v,shadowParent:ddn(g)};t.current.push(S),setTimeout(function(){t.current=t.current.filter(function(x){return x!==S})},1)},[]),c=Ri.useCallback(function(m){r.current=iie(m),n.current=void 0},[]),d=Ri.useCallback(function(m){l(m.type,Ikt(m),m.target,s(m,e.lockRef.current))},[]),f=Ri.useCallback(function(m){l(m.type,iie(m),m.target,s(m,e.lockRef.current))},[]);Ri.useEffect(function(){return HB.push(i),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,W1),document.addEventListener("touchmove",u,W1),document.addEventListener("touchstart",c,W1),function(){HB=HB.filter(function(m){return m!==i}),document.removeEventListener("wheel",u,W1),document.removeEventListener("touchmove",u,W1),document.removeEventListener("touchstart",c,W1)}},[]);var p=e.removeScrollBar,h=e.inert;return Ri.createElement(Ri.Fragment,null,h?Ri.createElement(i,{styles:ldn(o)}):null,p?Ri.createElement(B1,{gapMode:e.gapMode}):null)}function ddn(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var Dkt=k1(oie,Rkt);var jkt=aie.forwardRef(function(e,t){return aie.createElement(TH,Do({},e,{ref:t,sideCar:Dkt}))});jkt.classNames=TH.classNames;var mAe=jkt;var Ru=B(lt(),1),gAe="Popover",[Nkt,NHo]=Ro(gAe,[uAe]),IH=uAe(),[fdn,KT]=Nkt(gAe),Lkt=e=>{let{__scopePopover:t,children:r,open:n,defaultOpen:o,onOpenChange:i,modal:a=!1}=e,s=IH(t),u=Yi.useRef(null),[l,c]=Yi.useState(!1),[d=!1,f]=Qu({prop:n,defaultProp:o,onChange:i});return(0,Ru.jsx)(wkt,{...s,children:(0,Ru.jsx)(fdn,{scope:t,contentId:Fa(),triggerRef:u,open:d,onOpenChange:f,onOpenToggle:Yi.useCallback(()=>f(p=>!p),[f]),hasCustomAnchor:l,onCustomAnchorAdd:Yi.useCallback(()=>c(!0),[]),onCustomAnchorRemove:Yi.useCallback(()=>c(!1),[]),modal:a,children:r})})};Lkt.displayName=gAe;var Fkt="PopoverAnchor",pdn=Yi.forwardRef((e,t)=>{let{__scopePopover:r,...n}=e,o=KT(Fkt,r),i=IH(r),{onCustomAnchorAdd:a,onCustomAnchorRemove:s}=o;return Yi.useEffect(()=>(a(),()=>s()),[a,s]),(0,Ru.jsx)(cAe,{...i,...n,ref:t})});pdn.displayName=Fkt;var kkt="PopoverTrigger",Bkt=Yi.forwardRef((e,t)=>{let{__scopePopover:r,...n}=e,o=KT(kkt,r),i=IH(r),a=Wg(t,o.triggerRef),s=(0,Ru.jsx)(Vd.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Hkt(o.open),...n,ref:a,onClick:Xw(e.
Content from ${s.original}:
${s.processed}`)}),{urlContext:n,imageUrls:o}}getMentions(){return this.mentions}clearMentions(){this.mentions.clear()}};var J1=B(Y()),EAe=class{constructor(){this.chatHistory=[]}addMessage(t){this.chatHistory.push(t)}getMessages(){return this.chatHistory}clearChatHistory(){this.chatHistory=[]}};function iBt(e){let[t,r]=(0,J1.useState)(e.getMessages());(0,J1.useEffect)(()=>{r(e.getMessages())},[e]);let n=(0,J1.useCallback)(i=>{e.addMessage(i),r([...e.getMessages()])},[e]),o=(0,J1.useCallback)(()=>{e.clearChatHistory(),r([])},[e]);return[t,n,o]}var aBt=EAe;var Qw=require("obsidian"),jn=B(Y()),sBt=B(Td()),kdn=({sharedState:e,chainManager:t,onSaveChat:r,updateUserMessageHistory:n,fileParserManager:o,plugin:i})=>{let a=qo(),s=(0,jn.useContext)(WB),[u,l,c]=iBt(e),[d]=lj(),[f]=dy(),[p,h]=(0,jn.useState)(""),[m,_]=(0,jn.useState)(""),[g,v]=(0,jn.useState)(null),[S,x]=(0,jn.useState)(!1),[O,T]=(0,jn.useState)(jS.DEFAULT),[E,M]=(0,jn.useState)(-1),[A,j]=(0,jn.useState)([]),[N,F]=(0,jn.useState)(!1),[k,L]=(0,jn.useState)([]),q=die.getInstance(),U=$B.getInstance(),G=(0,jn.useRef)(null);(0,jn.useEffect)(()=>{let ee=()=>{G.current&&G.current.focus()};return s?.addEventListener(NS.CHAT_IS_VISIBLE,ee),()=>{s?.removeEventListener(NS.CHAT_IS_VISIBLE,ee)}},[s]);let V=(0,jn.useContext)(sie),D=i.app||V,z=async(ee,ge)=>{let Ue=D.workspace.getActiveFile();return await U.processContextNotes(ee,ge,D.vault,A,N,Ue,f)},W=async({toolCalls:ee,urls:ge,contextNotes:Ue}={})=>{if(!m&&k.length===0)return;let ct=ll(new Date),Je=[];m&&Je.push({type:"text",text:m});for(let lr of k){let Xe=await lr.arrayBuffer(),Bn=sBt.Buffer.from(Xe).toString("base64");Je.push({type:"image_url",image_url:{url:`data:${lr.type};base64,${Bn}`}})}let sr=[...Ue||[]],Xr=D.workspace.getActiveFile();N&&Xr&&!sr.some(lr=>lr.path===Xr.path)&&sr.push(Xr);let ur={message:m||"Image message",originalMessage:m,sender:Uo,isVisible:!0,timestamp:ct,content:Je,context:{notes:sr,urls:ge||[]}};_(""),L([]),l(ur),x(!0),T(jS.DEFAULT);let Bt=UC.getInstance(D.vault),Bo=await Bt.processCustomPrompt(m||"","",D.workspace.getActiveFile()),Xi=f==="copilot_plus"?await q.processUrls(m||""):{urlContext:"",imageUrls:[]},jo=await z(Bt,o);Bo=Bo+Xi.urlContext+jo;let Ie=m;ee&&(Ie+=" "+ee.join(`
`));let Ze={message:Bo,originalMessage:Ie,sender:Uo,isVisible:!1,timestamp:ct,content:Je,context:{notes:sr,urls:f==="copilot_plus"?[...ge||[],...Xi.imageUrls]:ge||[]}};l(Ze),m&&(n(m),M(-1)),await OAe(Ze,t,l,h,v,{debug:a.debug,updateLoadingMessage:T}),x(!1),T(jS.DEFAULT)},J=ee=>{let ge=i.userMessageHistory;return ee==="up"&&E<ge.length-1?(M(E+1),ge[ge.length-1-E-1]):ee==="down"&&E>-1?(M(E-1),E===0?"":ge[ge.length-1-E+1]):m},te=(0,jn.useCallback)(async(ee=!1)=>{if(!D){console.error("App instance is not available.");return}let ge=u.filter(Je=>Je.isVisible);if(ge.length===0){new Qw.Notice("No messages to save.");return}let Ue=ge[0].timestamp?.epoch||Date.now(),ct=ge.map(Je=>`**${Je.sender}**: ${Je.message}
[Timestamp: ${Je.timestamp?.display}]`).join(`
`);try{D.vault.getAbstractFileByPath(a.defaultSaveFolder)||await D.vault.createFolder(a.defaultSaveFolder);let{fileName:sr}=ll(new Date(Ue)),Xr=ge.find(Ze=>Ze.sender===Uo),ur=Xr?Xr.message.split(/\s+/).slice(0,10).join(" ").replace(/[\\/:*?"<>|]/g,"").trim():"Untitled Chat",Bt=a.defaultConversationNoteName||"{$date}_{$time}__{$topic}";Bt=Bt.replace("{$topic}",ur.slice(0,100).replace(/\s+/g,"_")).replace("{$date}",sr.split("_")[0]).replace("{$time}",sr.split("_")[1]);let Bo=Bt.replace(/[\\/:*?"<>|]/g,"_"),Xi=`${a.defaultSaveFolder}/${Bo}.md`,jo=`---
epoch: ${Ue}
modelKey: ${d}
tags:
- ${a.defaultConversationTag}
---
2025-01-09 14:41:22 +08:00
2025-03-14 16:09:40 +08:00
${ct}`,Ie=D.vault.getAbstractFileByPath(Xi);if(Ie instanceof Qw.TFile?(await D.vault.modify(Ie,jo),new Qw.Notice(`Chat updated in existing note: ${Xi}`)):(await D.vault.create(Xi,jo),new Qw.Notice(`Chat saved as new note: ${Xi}`)),ee){let Ze=D.vault.getAbstractFileByPath(Xi);Ze instanceof Qw.TFile&&D.workspace.getLeaf().openFile(Ze)}}catch(Je){console.error("Error saving chat as note:",bi(Je)),new Qw.Notice("Failed to save chat as note. Check console for details.")}},[D,u,d,a.defaultConversationTag,a.defaultSaveFolder,a.defaultConversationNoteName]),Ae=(0,jn.useCallback)(ee=>{g&&(a.debug&&console.log(`stopping generation..., reason: ${ee}`),g.abort(ee),x(!1))},[g,a.debug]),Z=(0,jn.useCallback)(async ee=>{let ge=ee-1;if(ge<0||u[ge].sender!==Uo){new Qw.Notice("Cannot regenerate the first message or a user message.");return}let Ue=u[ge],ct=u.slice(0,ee);c(),ct.forEach(l),t.memoryManager.clearChatMemory();for(let Je=0;Je<ct.length;Je+=2){let sr=ct[Je],Xr=ct[Je+1];sr&&Xr&&await t.memoryManager.getMemory().saveContext({input:sr.message},{output:Xr.message})}x(!0);try{await t.runChain(Ue,new AbortController,h,l,{debug:a.debug})&&a.debug&&console.log("Message regenerated successfully")}catch(Je){console.error("Error regenerating message:",Je),new Qw.Notice("Failed to regenerate message. Please try again.")}finally{x(!1)}},[l,t,u,c,a.debug]),Q=(0,jn.useCallback)(async(ee,ge)=>{let Ue=u[ee].message;if(Ue===ge)return;let ct=[...u];for(let Je=ee;Je<ct.length;Je++)ct[Je].originalMessage===Ue&&(ct[Je].message=ge,ct[Je].originalMessage=ge,ct[Je].context={notes:[],urls:[]});c(),ct.forEach(l),await Y8(ct,t.memoryManager),ct[ee].sender===Uo&&ee<ct.length-1&&Z(ee+1)},[l,t.memoryManager,u,c,Z]),ue=(ee,ge)=>()=>{let Ue=pe().debug,ct=async Je=>{let Xr={message:await ge(Je.detail.selectedText,Je.detail.eventSubtype),sender:Uo,isVisible:Ue,timestamp:ll(new Date)};Ue&&l(Xr),x(!0),await OAe(Xr,t,l,h,v,{debug:Ue,ignoreSystemMessage:!0}),x(!1)};return s?.addEventListener(ee,ct),()=>{s?.removeEventListener(ee,ct)}},Me=UC.getInstance(D.vault);(0,jn.useEffect)(ue(rr.APPLY_CUSTOM_PROMPT,async(ee,ge)=>ge?await Me.processCustomPrompt(ge,ee,D.workspace.getActiveFile()??void 0):ee),[]),(0,jn.useEffect)(ue(rr.APPLY_ADHOC_PROMPT,async(ee,ge)=>ge?await Me.processCustomPrompt(ge,ee,D.workspace.getActiveFile()):ee),[]),(0,jn.useEffect)(()=>{r&&r(te)},[r,te]);let ht=(0,jn.useCallback)(async ee=>{let ge=[...u];ge.splice(ee,1),c(),ge.forEach(l),await Y8(ge,t.memoryManager)},[l,t.memoryManager,u,c]),we=(0,jn.useCallback)(ee=>{_(ge=>`${ge} ${ee} `)},[]),ie=(0,jn.useCallback)(async()=>{Ae("new-chat"),a.autosaveChat&&u.length>0&&await te(!0),c(),t.memoryManager.clearChatMemory(),h(""),j([]),F(!1)},[Ae,a.autosaveChat,u.length,c,t.memoryManager,te]);return jn.default.createElement("div",{className:"chat-container"},jn.default.createElement(oBt,{chatHistory:u,currentAiMessage:p,loading:S,loadingMessage:O,app:D,onRegenerate:Z,onEdit:Q,onDelete:ht,onInsertToChat:we,onReplaceChat:_}),jn.default.createElement("div",{className:"bottom-container"},jn.default.createElement(VLt,{onNewChat:ie,onSaveAsNote:()=>te(!0)}),jn.default.createElement(jFt,{ref:G,inputMessage:m,setInputMessage:_,handleSendMessage:W,isGenerating:S,onStopGenerating:()=>Ae("user-stopped"),app:D,navigateHistory:J,contextNotes:A,setContextNotes:j,includeActiveNote:N,setIncludeActiveNote:F,mention:q,selectedImages:k,onAddImage:ee=>L(ge=>[...ge,...ee]),setSelectedImages:L})))},uBt=kdn;var lBt=require("obsidian"),YT=B(Y()),cBt=B(gh()),ZT=class extends lBt.ItemView{constructor(r,n){super(r);this.plugin=n;this.root=null;this.handleSaveAsNote=null;this.sharedState=n.sharedState,this.app=n.app,this.chainManager=n.chainManager,this.fileParserManager=n.fileParserManager,this.eventTarget=new EventTarget,this.plugin=n}getViewType(){return cl}getIcon(){return"message-square"}getTitle(){return"Copilot Chat"}getDisplayText(){return"Copilot"}async onOpen(){let r=(0,cBt.createRoot)(this.containerEl.children[1]),n=i=>{this.handleSaveAsNote=i},o=i=>{this.plugin.updateUserMessageHistory(i)};r.render(YT.createElement(sie.Provider
.block-interactivity-`.concat(e,` {pointer-events: none;}
.allow-interactivity-`).concat(e,` {pointer-events: all;}
`)},Rfn=0,QB=[];function l$t(e){var t=Di.useRef([]),r=Di.useRef([0,0]),n=Di.useRef(),o=Di.useState(Rfn++)[0],i=Di.useState(WC)[0],a=Di.useRef(e);Di.useEffect(function(){a.current=e},[e]),Di.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var m=RB([e.lockRef.current],(e.shards||[]).map(u$t),!0).filter(Boolean);return m.forEach(function(_){return _.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),m.forEach(function(_){return _.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var s=Di.useCallback(function(m,_){if("touches"in m&&m.touches.length===2||m.type==="wheel"&&m.ctrlKey)return!a.current.allowPinchZoom;var g=bie(m),v=r.current,S="deltaX"in m?m.deltaX:v[0]-g[0],x="deltaY"in m?m.deltaY:v[1]-g[1],O,T=m.target,E=Math.abs(S)>Math.abs(x)?"h":"v";if("touches"in m&&E==="h"&&T.type==="range")return!1;var M=WAe(E,T);if(!M)return!0;if(M?O=E:(O=E==="v"?"h":"v",M=WAe(E,T)),!M)return!1;if(!n.current&&"changedTouches"in m&&(S||x)&&(n.current=O),!O)return!0;var A=n.current||O;return a$t(A,_,m,A==="h"?S:x,!0)},[]),u=Di.useCallback(function(m){var _=m;if(!(!QB.length||QB[QB.length-1]!==i)){var g="deltaY"in _?s$t(_):bie(_),v=t.current.filter(function(O){return O.name===_.type&&(O.target===_.target||_.target===O.shadowParent)&&Ifn(O.delta,g)})[0];if(v&&v.should){_.cancelable&&_.preventDefault();return}if(!v){var S=(a.current.shards||[]).map(u$t).filter(Boolean).filter(function(O){return O.contains(_.target)}),x=S.length>0?s(_,S[0]):!a.current.noIsolation;x&&_.cancelable&&_.preventDefault()}}},[]),l=Di.useCallback(function(m,_,g,v){var S={name:m,delta:_,target:g,should:v,shadowParent:Dfn(g)};t.current.push(S),setTimeout(function(){t.current=t.current.filter(function(x){return x!==S})},1)},[]),c=Di.useCallback(function(m){r.current=bie(m),n.current=void 0},[]),d=Di.useCallback(function(m){l(m.type,s$t(m),m.target,s(m,e.lockRef.current))},[]),f=Di.useCallback(function(m){l(m.type,bie(m),m.target,s(m,e.lockRef.current))},[]);Di.useEffect(function(){return QB.push(i),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,Y1),document.addEventListener("touchmove",u,Y1),document.addEventListener("touchstart",c,Y1),function(){QB=QB.filter(function(m){return m!==i}),document.removeEventListener("wheel",u,Y1),document.removeEventListener("touchmove",u,Y1),document.removeEventListener("touchstart",c,Y1)}},[]);var p=e.removeScrollBar,h=e.inert;return Di.createElement(Di.Fragment,null,h?Di.createElement(i,{styles:Afn(o)}):null,p?Di.createElement(B1,{gapMode:e.gapMode}):null)}function Dfn(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var c$t=k1(yie,l$t);var d$t=_ie.forwardRef(function(e,t){return _ie.createElement(UH,Do({},e,{ref:t,sideCar:c$t}))});d$t.classNames=UH.classNames;var HH=d$t;var Ko=B(lt(),1),JAe="Dialog",[f$t,C9o]=Ro(JAe),[jfn,Jg]=f$t(JAe),p$t=e=>{let{__scopeDialog:t,children:r,open:n,defaultOpen:o,onOpenChange:i,modal:a=!0}=e,s=mi.useRef(null),u=mi.useRef(null),[l=!1,c]=Qu({prop:n,defaultProp:o,onChange:i});return(0,Ko.jsx)(jfn,{scope:t,triggerRef:s,contentRef:u,contentId:Fa(),titleId:Fa(),descriptionId:Fa(),open:l,onOpenChange:c,onOpenToggle:mi.useCallback(()=>c(d=>!d),[c]),modal:a,children:r})};p$t.displayName=JAe;var h$t="DialogTrigger",m$t=mi.forwardRef((e,t)=>{let{__scopeDialog:r,...n}=e,o=Jg(h$t,r),i=GC(t,o.triggerRef);return(0,Ko.jsx)(Hp.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":YAe(o.open),...n,ref:i,onClick:tS(e.onClick,o.onOpenToggle)})});m$t.displayName=h$t;var GAe="DialogPortal",[Nfn,g$t]=f$t(GAe,{forceMount:void 0}),y$t=e=>{let{__scopeDialog:t,forceMount:r,children:n,container:o}=e,i=Jg(GAe,t);return(0,Ko.jsx)(Nfn,{scope:t,forceMount:r,children:mi.Children.map(n,a=>(0,Ko.jsx)(Iu,{present:r||i.open,children:(0,Ko.jsx)(zAe,{asChild:!0,container:o,children:a})}))})};y$t.displayName=GAe;var
If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return mi.useEffect(()=>{e&&(document.getElementById(e)||console.error(r))},[r,e]),null},$fn="DialogDescriptionWarning",qfn=({contentRef:e,descriptionId:t})=>{let n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${P$t($fn).contentName}}.`;return mi.useEffect(()=>{let o=e.current?.getAttribute("aria-describedby");t&&o&&(document.getElementById(t)||console.warn(n))},[n,e,t]),null},T$t=p$t,M$t=m$t,I$t=y$t,ZAe=b$t,XAe=_$t,QAe=w$t,eRe=x$t,A$t=O$t;var rM=T$t,R$t=M$t,zfn=I$t;var D$t=Ec.forwardRef(({className:e,...t},r)=>Ec.createElement(ZAe,{ref:r,className:_e("fixed inset-0 z-modal data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0","bg-overlay/50",e),...t}));D$t.displayName=ZAe.displayName;var KC=Ec.forwardRef(({className:e,children:t,container:r,...n},o)=>Ec.createElement(zfn,{container:r},Ec.createElement(D$t,null),Ec.createElement(XAe,{ref:o,className:_e("fixed left-[50%] top-[50%] z-modal grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-primary p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...n},t,Ec.createElement(A$t,{className:"absolute border-none right-4 top-4 text-faint clickable-icon bg-transparent hover:bg-opacity-100 hover:text-normal hover:bg-transparent outline-none focus-visible:outline-none focus-visible:text-normal focus-visible:ring-0"},Ec.createElement(bh,{className:"h-4 w-4"}),Ec.createElement("span",{className:"sr-only"},"Close")))));KC.displayName=XAe.displayName;var YC=({className:e,...t})=>Ec.createElement("div",{className:_e("flex flex-col space-y-0.5 text-center sm:text-left",e),...t});YC.displayName="DialogHeader";var Hfn=({className:e,...t})=>Ec.createElement("div",{className:_e("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});Hfn.displayName="DialogFooter";var ZC=Ec.forwardRef(({className:e,...t},r)=>Ec.createElement(QAe,{ref:r,className:_e("text-lg font-semibold leading-none tracking-tight mt-0",e),...t}));ZC.displayName=QAe.displayName;var XC=Ec.forwardRef(({className:e,...t},r)=>Ec.createElement(eRe,{ref:r,className:_e("text-sm text-muted",e),...t}));XC.displayName=eRe.displayName;var oM=B(Y());var X1=B(Y());var ni=B(Y(),1);function e$(e,[t,r]){return Math.min(r,Math.max(t,e))}function ko(e,t,{checkForDefaultPrevented:r=!0}={}){return function(o){if(e?.(o),r===!1||!o.defaultPrevented)return t?.(o)}}var nM=B(Y(),1);var QC=B(Y(),1),j$t=B(lt(),1);function N$t(e,t=[]){let r=[];function n(i,a){let s=QC.createContext(a),u=r.length;r=[...r,a];function l(d){let{scope:f,children:p,...h}=d,m=f?.[e][u]||s,_=QC.useMemo(()=>h,Object.values(h));return(0,j$t.jsx)(m.Provider,{value:_,children:p})}function c(d,f){let p=f?.[e][u]||s,h=QC.useContext(p);if(h)return h;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${i}\``)}return l.displayName=i+"Provider",[l,c]}let o=()=>{let i=r.map(a=>QC.createContext(a));return function(s){let u=s?.[e]||i;return QC.useMemo(()=>({[`__scope${e}`]:{...s,[e]:u}}),[s,u])}};return o.scopeName=e,[n,Vfn(o,...t)]}function Vfn(...e){let t=e[0];if(e.length===1)return t;let r=()=>{let n=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let a=n.reduce((s,{useScope:u,scopeName:l})=>{let d=u(i)[`__scope${l}`];return{...s,...d}},{});return QC.useMemo(()=>({[`__scope${t.scopeName}`]:a}),[a])}};return r.scopeName=t.scopeName,r}var wie=B(lt(),1);function Sie(e){let t=e+"CollectionProvider",[r,n]=N$t(t),[o,i]=r(t,{collectionRef:{current:null},itemMap:new Map}),a=p=>{let{scope:h,children:m}=p,_=nM.default.useRef(null),g=nM.default.useRef(new Map).current;return(0,wie.jsx)(o,{scope:h
To pick up a draggable item, press the space bar.
While dragging, use the arrow keys to move the item.
Press space again to drop the item in its new position, or press escape to cancel.
`},fhn={onDragStart(e){let{active:t}=e;return"Picked up draggable item "+t.id+"."},onDragOver(e){let{active:t,over:r}=e;return r?"Draggable item "+t.id+" was moved over droppable area "+r.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(e){let{active:t,over:r}=e;return r?"Draggable item "+t.id+" was dropped over droppable area "+r.id:"Draggable item "+t.id+" was dropped."},onDragCancel(e){let{active:t}=e;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function phn(e){let{announcements:t=fhn,container:r,hiddenTextDescribedById:n,screenReaderInstructions:o=dhn}=e,{announce:i,announcement:a}=MUt(),s=nD("DndLiveRegion"),[u,l]=(0,ye.useState)(!1);if((0,ye.useEffect)(()=>{l(!0)},[]),lhn((0,ye.useMemo)(()=>({onDragStart(d){let{active:f}=d;i(t.onDragStart({active:f}))},onDragMove(d){let{active:f,over:p}=d;t.onDragMove&&i(t.onDragMove({active:f,over:p}))},onDragOver(d){let{active:f,over:p}=d;i(t.onDragOver({active:f,over:p}))},onDragEnd(d){let{active:f,over:p}=d;i(t.onDragEnd({active:f,over:p}))},onDragCancel(d){let{active:f,over:p}=d;i(t.onDragCancel({active:f,over:p}))}}),[i,t])),!u)return null;let c=ye.default.createElement(ye.default.Fragment,null,ye.default.createElement(PUt,{id:n,value:o.draggable}),ye.default.createElement(TUt,{id:s,announcement:a}));return r?(0,sD.createPortal)(c,r):c}var nl;(function(e){e.DragStart="dragStart",e.DragMove="dragMove",e.DragEnd="dragEnd",e.DragCancel="dragCancel",e.DragOver="dragOver",e.RegisterDroppable="registerDroppable",e.SetDroppableDisabled="setDroppableDisabled",e.UnregisterDroppable="unregisterDroppable"})(nl||(nl={}));function Fie(){}function JRe(e,t){return(0,ye.useMemo)(()=>({sensor:e,options:t??{}}),[e,t])}function zUt(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return(0,ye.useMemo)(()=>[...t].filter(n=>n!=null),[...t])}var Kg=Object.freeze({x:0,y:0});function HUt(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function VUt(e,t){let{data:{value:r}}=e,{data:{value:n}}=t;return r-n}function hhn(e,t){let{data:{value:r}}=e,{data:{value:n}}=t;return n-r}function IUt(e){let{left:t,top:r,height:n,width:o}=e;return[{x:t,y:r},{x:t+o,y:r},{x:t,y:r+n},{x:t+o,y:r+n}]}function GRe(e,t){if(!e||e.length===0)return null;let[r]=e;return t?r[t]:r}function AUt(e,t,r){return t===void 0&&(t=e.left),r===void 0&&(r=e.top),{x:t+e.width*.5,y:r+e.height*.5}}var KRe=e=>{let{collisionRect:t,droppableRects:r,droppableContainers:n}=e,o=AUt(t,t.left,t.top),i=[];for(let a of n){let{id:s}=a,u=r.get(s);if(u){let l=HUt(AUt(u),o);i.push({id:s,data:{droppableContainer:a,value:l}})}}return i.sort(VUt)},WUt=e=>{let{collisionRect:t,droppableRects:r,droppableContainers:n}=e,o=IUt(t),i=[];for(let a of n){let{id:s}=a,u=r.get(s);if(u){let l=IUt(u),c=o.reduce((f,p,h)=>f+HUt(l[h],p),0),d=Number((c/4).toFixed(4));i.push({id:s,data:{droppableContainer:a,value:d}})}}return i.sort(VUt)};function mhn(e,t){let r=Math.max(t.top,e.top),n=Math.max(t.left,e.left),o=Math.min(t.left+t.width,e.left+e.width),i=Math.min(t.top+t.height,e.top+e.height),a=o-n,s=i-r;if(n<o&&r<i){let u=t.width*t.height,l=e.width*e.height,c=a*s,d=c/(u+l-c);return Number(d.toFixed(4))}return 0}var ghn=e=>{let{collisionRect:t,droppableRects:r,droppableContainers:n}=e,o=[];for(let i of n){let{id:a}=i,s=r.get(a);if(s){let u=mhn(s,t);u>0&&o.push({id:a,data:{droppableContainer:i,value:u}})}}return o.sort(hhn)};function yhn(e,t,r){return{...e,scaleX:t&&r?t.width/r.width:1,scaleY:t&&r?t.height/r.height:1}}function JUt(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:Kg}function bhn(e){return function(r){for(var n=arguments.length,o=new Array(n>1?n-1:0),i=1;i<n;i++)o[i-1]=arguments[i];return o.reduce((a,s)=>({...a,top:a.top+e*s.y,bottom:a.bottom+e*s.y,left:a.left+e*s.x,right:a.right+e*s.x}),{...r})}}var _hn=bhn(1);function vhn(e){if(e.startsWith("matrix3d(")){let t=e.slice(9,-1).split(/, /);return{x:+t[12],y:+t[13],scaleX:+t[0],scaleY:+t[5]}}else if(e.startsWith("matrix(")){let t=e.slice(7,-1).split(/, /);return{x:+t[4],y:+t[5],scaleX:+t[0],scaleY:+t[3]}}return null}fun
2025-01-09 14:41:22 +08:00
/*! Bundled license information:
@langchain/core/dist/utils/fast-json-patch/src/helpers.js:
(*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2017-2022 Joachim Wester
* MIT licensed
*)
@langchain/core/dist/utils/fast-json-patch/src/duplex.js:
(*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2013-2021 Joachim Wester
* MIT license
*)
mustache/mustache.mjs:
(*!
* mustache.js - Logic-less {{mustache}} templates with JavaScript
* http://github.com/janl/mustache.js
*)
2025-03-14 16:09:40 +08:00
react/cjs/react.production.min.js:
(**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
moment/moment.js:
(*! moment.js *)
(*! version : 2.29.4 *)
(*! authors : Tim Wood, Iskren Chernev, Moment.js contributors *)
(*! license : MIT *)
(*! momentjs.com *)
ieee754/index.js:
(*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)
buffer/index.js:
(*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*)
scheduler/cjs/scheduler.production.min.js:
(**
* @license React
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
react-dom/cjs/react-dom.production.min.js:
(**
* @license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
react/cjs/react-jsx-runtime.production.min.js:
(**
* @license React
* react-jsx-runtime.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
tslib/tslib.es6.js:
(*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** *)
safe-buffer/index.js:
(*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
@langchain/core/dist/utils/js-sha1/hash.js:
(*
* [js-sha1]{@link https://github.com/emn178/js-sha1}
*
* @version 0.6.0
* @author Chen, Yi-Cyuan [emn178@gmail.com]
* @copyright Chen, Yi-Cyuan 2014-2017
* @license MIT
*)
crypto-js/ripemd160.js:
(** @preserve
(c) 2012 by Cédric Mesnil. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
crypto-js/mode-ctr-gladman.js:
(** @preserve
* Counter block mode compatible with Dr Brian Gladman fileenc.c
* derived from CryptoJS.mode.CTR
* Jan Hruby jhruby.web@gmail.com
*)
lucide-react/dist/esm/shared/src/utils.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/defaultAttributes.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/Icon.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/createLucideIcon.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/arrow-big-up.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/arrow-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/bot.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/check.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/chevron-down.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/chevron-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/chevron-up.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-help.js:
2025-01-09 14:41:22 +08:00
(**
2025-03-14 16:09:40 +08:00
* @license lucide-react v0.462.0 - ISC
2025-01-09 14:41:22 +08:00
*
2025-03-14 16:09:40 +08:00
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
2025-01-09 14:41:22 +08:00
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/circle-plus.js:
(**
* @license lucide-react v0.462.0 - ISC
2025-01-09 14:41:22 +08:00
*
2025-03-14 16:09:40 +08:00
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
2025-01-09 14:41:22 +08:00
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/circle-stop.js:
(**
* @license lucide-react v0.462.0 - ISC
2025-01-09 14:41:22 +08:00
*
2025-03-14 16:09:40 +08:00
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
2025-01-09 14:41:22 +08:00
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/circle.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
2025-01-09 14:41:22 +08:00
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/cog.js:
2025-01-09 14:41:22 +08:00
(**
2025-03-14 16:09:40 +08:00
* @license lucide-react v0.462.0 - ISC
2025-01-09 14:41:22 +08:00
*
2025-03-14 16:09:40 +08:00
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
2025-01-09 14:41:22 +08:00
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/command.js:
2025-01-09 14:41:22 +08:00
(**
2025-03-14 16:09:40 +08:00
* @license lucide-react v0.462.0 - ISC
2025-01-09 14:41:22 +08:00
*
2025-03-14 16:09:40 +08:00
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
2025-01-09 14:41:22 +08:00
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/copy.js:
2025-01-09 14:41:22 +08:00
(**
2025-03-14 16:09:40 +08:00
* @license lucide-react v0.462.0 - ISC
2025-01-09 14:41:22 +08:00
*
2025-03-14 16:09:40 +08:00
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
2025-01-09 14:41:22 +08:00
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/corner-down-left.js:
2025-01-09 14:41:22 +08:00
(**
2025-03-14 16:09:40 +08:00
* @license lucide-react v0.462.0 - ISC
2025-01-09 14:41:22 +08:00
*
2025-03-14 16:09:40 +08:00
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
2025-01-09 14:41:22 +08:00
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/cpu.js:
2025-01-09 14:41:22 +08:00
(**
2025-03-14 16:09:40 +08:00
* @license lucide-react v0.462.0 - ISC
2025-01-09 14:41:22 +08:00
*
2025-03-14 16:09:40 +08:00
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
2025-01-09 14:41:22 +08:00
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/database.js:
2025-01-09 14:41:22 +08:00
(**
2025-03-14 16:09:40 +08:00
* @license lucide-react v0.462.0 - ISC
2025-01-09 14:41:22 +08:00
*
2025-03-14 16:09:40 +08:00
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/download.js:
(**
* @license lucide-react v0.462.0 - ISC
2025-01-09 14:41:22 +08:00
*
2025-03-14 16:09:40 +08:00
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/ellipsis.js:
(**
* @license lucide-react v0.462.0 - ISC
2025-01-09 14:41:22 +08:00
*
2025-03-14 16:09:40 +08:00
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
2025-01-09 14:41:22 +08:00
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/external-link.js:
2025-01-09 14:41:22 +08:00
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/eye-off.js:
2025-01-09 14:41:22 +08:00
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/eye.js:
2025-01-09 14:41:22 +08:00
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/file-input.js:
2025-01-09 14:41:22 +08:00
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/file-output.js:
2025-01-09 14:41:22 +08:00
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/file-text.js:
2025-01-09 14:41:22 +08:00
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/file.js:
2025-01-09 14:41:22 +08:00
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/folder.js:
2025-01-09 14:41:22 +08:00
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/globe.js:
2025-01-09 14:41:22 +08:00
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/image.js:
2025-01-09 14:41:22 +08:00
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/info.js:
2025-01-09 14:41:22 +08:00
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/key.js:
2025-01-09 14:41:22 +08:00
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/library-big.js:
2025-01-09 14:41:22 +08:00
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/lightbulb.js:
2025-01-09 14:41:22 +08:00
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/loader-circle.js:
2025-01-09 14:41:22 +08:00
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/message-circle-plus.js:
2025-01-09 14:41:22 +08:00
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/move.js:
2025-01-09 14:41:22 +08:00
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/pen-line.js:
2025-01-09 14:41:22 +08:00
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/pencil-line.js:
2025-01-09 14:41:22 +08:00
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/pencil.js:
2025-01-09 14:41:22 +08:00
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/plus.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/refresh-ccw.js:
2025-01-09 14:41:22 +08:00
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/refresh-cw.js:
2025-01-09 14:41:22 +08:00
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/rotate-cw.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/sparkles.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/square-arrow-out-up-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-01-09 14:41:22 +08:00
lucide-react/dist/esm/icons/square-pen.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/tag.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-01-09 14:41:22 +08:00
lucide-react/dist/esm/icons/text-cursor-input.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/trash-2.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/triangle-alert.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/user.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
lucide-react/dist/esm/icons/wrench.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/x.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-01-09 14:41:22 +08:00
lucide-react/dist/esm/lucide-react.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
2025-03-14 16:09:40 +08:00
@google/generative-ai/dist/index.mjs:
(**
* @license
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*)
@google/generative-ai/dist/index.mjs:
(**
* @license
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*)
2025-01-09 14:41:22 +08:00
*/
/* nosourcemap */