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

1738 lines
3.5 MiB
JavaScript
Raw Normal View History

2025-07-05 20:48:33 +08:00
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
2025-07-12 10:26:56 +08:00
var Ier=Object.create;var l2=Object.defineProperty;var Mer=Object.getOwnPropertyDescriptor;var Rer=Object.getOwnPropertyNames;var jer=Object.getPrototypeOf,Ner=Object.prototype.hasOwnProperty;var pUe=t=>{throw TypeError(t)};var Der=(t,e,r)=>e in t?l2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var w=(t,e)=>()=>(t&&(e=t(t=0)),e);var v=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Cf=(t,e)=>{for(var r in e)l2(t,r,{get:e[r],enumerable:!0})},mUe=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Rer(e))!Ner.call(t,o)&&o!==r&&l2(t,o,{get:()=>e[o],enumerable:!(n=Mer(e,o))||n.enumerable});return t};var F=(t,e,r)=>(r=t!=null?Ier(jer(t)):{},mUe(e||!t||!t.__esModule?l2(r,"default",{value:t,enumerable:!0}):r,t)),zl=t=>mUe(l2({},"__esModule",{value:!0}),t);var Cc=(t,e,r)=>Der(t,typeof e!="symbol"?e+"":e,r),Ler=(t,e,r)=>e.has(t)||pUe("Cannot "+r);var hUe=(t,e,r)=>e.has(t)?pUe("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r);var gUe=(t,e,r)=>(Ler(t,e,"access private method"),r);function npe(){if(!bK&&(bK=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!bK))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return bK(Fer)}var bK,Fer,yUe=w(()=>{Fer=new Uint8Array(16)});function bUe(t,e=0){return Oc[t[e+0]]+Oc[t[e+1]]+Oc[t[e+2]]+Oc[t[e+3]]+"-"+Oc[t[e+4]]+Oc[t[e+5]]+"-"+Oc[t[e+6]]+Oc[t[e+7]]+"-"+Oc[t[e+8]]+Oc[t[e+9]]+"-"+Oc[t[e+10]]+Oc[t[e+11]]+Oc[t[e+12]]+Oc[t[e+13]]+Oc[t[e+14]]+Oc[t[e+15]]}var Oc,_Ue=w(()=>{Oc=[];for(let t=0;t<256;++t)Oc.push((t+256).toString(16).slice(1))});var ker,ope,vUe=w(()=>{ker=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ope={randomUUID:ker}});function $er(t,e,r){if(ope.randomUUID&&!e&&!t)return ope.randomUUID();t=t||{};let n=t.random||(t.rng||npe)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){r=r||0;for(let o=0;o<16;++o)e[r+o]=n[o];return e}return bUe(n)}var bC,wUe=w(()=>{vUe();yUe();_Ue();bC=$er});var c2=w(()=>{wUe()});function qer(t){OUe=t}function _K(){return OUe}function ut(t,e){let r=_K(),n=vK({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===LL?void 0:LL].filter(o=>!!o)});t.common.issues.push(n)}function wK(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}function PUe(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r}function Hr(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(a,s)=>{var u,l;let{message:c}=t;return a.code==="invalid_enum_value"?{message:c??s.defaultError}:typeof s.data>"u"?{message:(u=c??n)!==null&&u!==void 0?u:s.defaultError}:a.code!=="invalid_type"?{message:s.defaultError}:{message:(l=c??r)!==null&&l!==void 0?l:s.defaultError}},description:o}}function TUe(t){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),e}function itr(t){return new RegExp(`^${TUe(t)}$`)}function AUe(t){let e=`${EUe}T${TUe(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function atr(t,e){return!!((e==="v4"||!e)&&Xer.test(t)||(e==="v6"||!e)&&etr.test(t))}function str(t,e){if(!Ger.test(t))return!1;try{let[r]=t.split("."),n=r.replace(/-/g,"+").replace(/_/g,"/").pa
2025-07-05 20:48:33 +08:00
=== LangSmith Server Configuration ===
`+JSON.stringify(r,null,2)+`
2025-07-12 10:26:56 +08:00
`),r}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch{console.warn("[WARNING]: LangSmith failed to fetch info on supported operations. Falling back to batch operations and default limits.")}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let e=await this._getBatchSizeLimitBytes();await this.drainAutoBatchQueue(e)}async createRun(e){if(!this._filterForSampling([e]).length)return;let r={...this.headers,"Content-Type":"application/json"},n=e.project_name;delete e.project_name;let o=await this.prepareRunCreateOrUpdateInputs({session_name:n,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&o.trace_id!==void 0&&o.dotted_order!==void 0){this.processRunOperation({action:"create",item:o}).catch(console.error);return}let i=o4e(o),a=await this.caller.call(Vt(this.debug),`${this.apiUrl}/runs`,{method:"POST",headers:r,body:hp(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(a,"create run",!0)}async batchIngestRuns({runCreates:e,runUpdates:r}){if(e===void 0&&r===void 0)return;let n=await Promise.all(e?.map(s=>this.prepareRunCreateOrUpdateInputs(s))??[]),o=await Promise.all(r?.map(s=>this.prepareRunCreateOrUpdateInputs(s))??[]);if(n.length>0&&o.length>0){let s=n.reduce((l,c)=>(c.id&&(l[c.id]=c),l),{}),u=[];for(let l of o)l.id!==void 0&&s[l.id]?s[l.id]={...s[l.id],...l}:u.push(l);n=Object.values(s),o=u}let i={post:n,patch:o};if(!i.post.length&&!i.patch.length)return;let a={post:[],patch:[]};for(let s of["post","patch"]){let u=s,l=i[u].reverse(),c=l.pop();for(;c!==void 0;)a[u].push(c),c=l.pop()}(a.post.length>0||a.patch.length>0)&&await this._postBatchIngestRuns(hp(a))}async _postBatchIngestRuns(e){let r={...this.headers,"Content-Type":"application/json",Accept:"application/json"},n=await this.batchIngestCaller.call(Vt(this.debug),`${this.apiUrl}/runs/batch`,{method:"POST",headers:r,body:e,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(n,"batch create run",!0)}async multipartIngestRuns({runCreates:e,runUpdates:r}){if(e===void 0&&r===void 0)return;let n={},o=[];for(let c of e??[]){let d=await this.prepareRunCreateOrUpdateInputs(c);d.id!==void 0&&d.attachments!==void 0&&(n[d.id]=d.attachments),delete d.attachments,o.push(d)}let i=[];for(let c of r??[])i.push(await this.prepareRunCreateOrUpdateInputs(c));if(o.find(c=>c.trace_id===void 0||c.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(i.find(c=>c.trace_id===void 0||c.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(o.length>0&&i.length>0){let c=o.reduce((f,p)=>(p.id&&(f[p.id]=p),f),{}),d=[];for(let f of i)f.id!==void 0&&c[f.id]?c[f.id]={...c[f.id],...f}:d.push(f);o=Object.values(c),i=d}if(o.length===0&&i.length===0)return;let u=[],l=[];for(let[c,d]of[["post",o],["patch",i]])for(let f of d){let{inputs:p,outputs:m,events:h,attachments:b,...g}=f,y={inputs:p,outputs:m,events:h},S=hp(g);l.push({name:`${c}.${g.id}`,payload:new Blob([S],{type:`application/json; length=${S.length}`})});for(let[x,O]of Object.entries(y)){if(O===void 0)continue;let P=hp(O);l.push({name:`${c}.${g.id}.${x}`,payload:new Blob([P],{type:`application/json; length=${P.length}`})})}if(g.id!==void 0){let x=n[g.id];if(x){delete n[g.id];for(let[O,P]of Object.entries(x)){let E,A;if(Array.isArray(P)?[E,A]=P:(E=P.mimeType,A=P.data),O.includes(".")){console.warn(`Skipping attachment '${O}' for run ${g.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}l.push({name:`attachment.${g.id}.${O}`,payload:new Blob([A],{type:`${E}; length=${A.byteLength}`})})}
2025-07-05 20:48:33 +08:00
`])),o.push(new Blob([`Content-Disposition: form-data; name="${u.name}"\r
`,`Content-Type: ${u.payload.type}\r
\r
`])),o.push(u.payload),o.push(new Blob([`\r
`]));o.push(new Blob([`--${n}--\r
`]));let a=await new Blob(o).arrayBuffer(),s=await this.batchIngestCaller.call(Vt(this.debug),`${this.apiUrl}/runs/multipart`,{method:"POST",headers:{...this.headers,"Content-Type":`multipart/form-data; boundary=${n}`},body:a,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(s,"ingest multipart runs",!0)}catch(n){console.warn(`${n.message.trim()}
2025-07-12 10:26:56 +08:00
Context: ${r}`)}}async updateRun(e,r){Kr(e),r.inputs&&(r.inputs=await this.processInputs(r.inputs)),r.outputs&&(r.outputs=await this.processOutputs(r.outputs));let n={...r,id:e};if(!this._filterForSampling([n],!0).length)return;if(this.autoBatchTracing&&n.trace_id!==void 0&&n.dotted_order!==void 0){if(r.end_time!==void 0&&n.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:n}).catch(console.error);return}else this.processRunOperation({action:"update",item:n}).catch(console.error);return}let o={...this.headers,"Content-Type":"application/json"},i=await this.caller.call(Vt(this.debug),`${this.apiUrl}/runs/${e}`,{method:"PATCH",headers:o,body:hp(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(i,"update run",!0)}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){Kr(e);let n=await this._get(`/runs/${e}`);return r&&n.child_run_ids&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:r,projectOpts:n}){if(r!==void 0){let o;r.session_id?o=r.session_id:n?.projectName?o=(await this.readProject({projectName:n?.projectName})).id:n?.projectId?o=n?.projectId:o=(await this.readProject({projectName:pp("PROJECT")||"default"})).id;let i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${o}/r/${r.id}?poll=true`}else if(e!==void 0){let o=await this.readRun(e);if(!o.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${o.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){let r=await yir(this.listRuns({id:e.child_run_ids})),n={},o={};r.sort((i,a)=>(i?.dotted_order??"").localeCompare(a?.dotted_order??""));for(let i of r){if(i.parent_run_id===null||i.parent_run_id===void 0)throw new Error(`Child run ${i.id} has no parent`);i.parent_run_id in n||(n[i.parent_run_id]=[]),n[i.parent_run_id].push(i),o[i.id]=i}e.child_runs=n[e.id]||[];for(let i in n)i!==e.id&&(o[i].child_runs=n[i]);return e}async*listRuns(e){let{projectId:r,projectName:n,parentRunId:o,traceId:i,referenceExampleId:a,startTime:s,executionOrder:u,isRoot:l,runType:c,error:d,id:f,query:p,filter:m,traceFilter:h,treeFilter:b,limit:g,select:y}=e,S=[];if(r&&(S=Array.isArray(r)?r:[r]),n){let E=Array.isArray(n)?n:[n],A=await Promise.all(E.map(I=>this.readProject({projectName:I}).then(R=>R.id)));S.push(...A)}let x=["app_path","child_run_ids","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],O={session:S.length?S:null,run_type:c,reference_example:a,query:p,filter:m,trace_filter:h,tree_filter:b,execution_order:u,parent_run:o,start_time:s?s.toISOString():null,error:d,id:f,limit:g,trace:i,select:y||x,is_root:l},P=0;for await(let E of this._getCursorPaginatedList("/runs/query",O))if(g){if(P>=g)break;if(E.length+P>g){yield*E.slice(0,g-P);break}P+=E.length,yield*E}else yield*E}async getRunStats({id:e,trace:r,parentRun:n,runType:o,projectNames:i,projectIds:a,referenceExampleIds:s,startTime:u,endTime:l,error:c,query:d,filter:f,traceFilter:p,treeFilter:m,isRoot:h,dataSourceType:b}){let g=a||[];i&&(g=[...a||[],...await Promise.all(i.map(P=>this.readProject({projectName:P}).then(E=>E.id)))]);let S=Object.fromEntries(Object.entries({id:e,trace:r,parent_run:n,run_type:o,session:g,reference_example:s,start_time:u,end_time:l,error:c,query:d,filter:f,trace_filter:p,tree_filter:m,is_root:h,data_source_type:b}).filter(([P,E])=>E!==void 0));return await(await this.caller.call(Vt(this.debug),`${this.apiUrl}/runs/stats`,{method:"POST",headers:this.headers,body:JSON.stringify(S),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json()}async shareRun(e,{shareId:r}={}){let n={run_id:e,share_token:r||as()};Kr(e);let i=await(await this.caller.call(Vt(this.debug),`${this.apiUrl}/runs/${e}/share`,{method:"PUT"
2025-07-05 20:48:33 +08:00
Status: ${i.status}
Message: ${a.detail.join(`
`)}`):new Error(`Failed to list shared examples: ${i.status} ${i.statusText}`);return a.map(s=>({...s,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:r=null,metadata:n=null,upsert:o=!1,projectExtra:i=null,referenceDatasetId:a=null}){let s=o?"?upsert=true":"",u=`${this.apiUrl}/sessions${s}`,l=i||{};n&&(l.metadata=n);let c={name:e,extra:l,description:r};a!==null&&(c.reference_dataset_id=a);let d=await this.caller.call(Vt(this.debug),u,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(c),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await sn(d,"create project"),await d.json()}async updateProject(e,{name:r=null,description:n=null,metadata:o=null,projectExtra:i=null,endTime:a=null}){let s=`${this.apiUrl}/sessions/${e}`,u=i;o&&(u={...u||{},metadata:o});let l={name:r,extra:u,description:n,end_time:a?new Date(a).toISOString():null},c=await this.caller.call(Vt(this.debug),s,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(l),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await sn(c,"update project"),await c.json()}async hasProject({projectId:e,projectName:r}){let n="/sessions",o=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)Kr(e),n+=`/${e}`;else if(r!==void 0)o.append("name",r);else throw new Error("Must provide projectName or projectId");let i=await this.caller.call(Vt(this.debug),`${this.apiUrl}${n}?${o}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});try{let a=await i.json();return i.ok?Array.isArray(a)?a.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:r,includeStats:n}){let o="/sessions",i=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)Kr(e),o+=`/${e}`;else if(r!==void 0)i.append("name",r);else throw new Error("Must provide projectName or projectId");n!==void 0&&i.append("include_stats",n.toString());let a=await this._get(o,i),s;if(Array.isArray(a)){if(a.length===0)throw new Error(`Project[id=${e}, name=${r}] not found`);s=a[0]}else s=a;return s}async getProjectUrl({projectId:e,projectName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either projectName or projectId");let n=await this.readProject({projectId:e,projectName:r}),o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");let n=await this.readDataset({datasetId:e,datasetName:r}),o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let e=new URLSearchParams({limit:"1"});for await(let r of this._getPaginated("/sessions",e))return this._tenantId=r[0].tenant_id,r[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:r,nameContains:n,referenceDatasetId:o,referenceDatasetName:i,referenceFree:a,metadata:s}={}){let u=new URLSearchParams;if(e!==void 0)for(let l of e)u.append("id",l);if(r!==void 0&&u.append("name",r),n!==void 0&&u.append("name_contains",n),o!==void 0)u.append("reference_dataset",o);else if(i!==void 0){let l=await this.readDataset({datasetName:i});u.append("reference_dataset",l.id)}a!==void 0&&u.append("reference_free",a.toString()),s!==void 0&&u.append("metadata",JSON.stringify(s));for await(let l of this._getPaginated("/sessions",u))yield*l}async deleteProject({projectId:e,projectName:r}){let n;if(e===void 0&&r===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?n=(await this.readProject({projectName:r})).id:n=e,Kr(n);let o=await this.caller.call(Vt(this.debug),`${this.apiUrl}/sessions/${n}
2025-07-12 10:26:56 +08:00
`).map(s=>JSON.parse(s))}async*listDatasets({limit:e=100,offset:r=0,datasetIds:n,datasetName:o,datasetNameContains:i,metadata:a}={}){let s="/datasets",u=new URLSearchParams({limit:e.toString(),offset:r.toString()});if(n!==void 0)for(let l of n)u.append("id",l);o!==void 0&&u.append("name",o),i!==void 0&&u.append("name_contains",i),a!==void 0&&u.append("metadata",JSON.stringify(a));for await(let l of this._getPaginated(s,u))yield*l}async updateDataset(e){let{datasetId:r,datasetName:n,...o}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let i=r??(await this.readDataset({datasetName:n})).id;Kr(i);let a=await this.caller.call(Vt(this.debug),`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await sn(a,"update dataset"),await a.json()}async updateDatasetTag(e){let{datasetId:r,datasetName:n,asOf:o,tag:i}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let a=r??(await this.readDataset({datasetName:n})).id;Kr(a);let s=await this.caller.call(Vt(this.debug),`${this.apiUrl}/datasets/${a}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({as_of:typeof o=="string"?o:o.toISOString(),tag:i}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(s,"update dataset tags")}async deleteDataset({datasetId:e,datasetName:r}){let n="/datasets",o=e;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(o=(await this.readDataset({datasetName:r})).id),o!==void 0)Kr(o),n+=`/${o}`;else throw new Error("Must provide datasetName or datasetId");let i=await this.caller.call(Vt(this.debug),this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(i,`delete ${n}`),await i.json()}async indexDataset({datasetId:e,datasetName:r,tag:n}){let o=e;if(!o&&!r)throw new Error("Must provide either datasetName or datasetId");if(o&&r)throw new Error("Must provide either datasetName or datasetId, not both");o||(o=(await this.readDataset({datasetName:r})).id),Kr(o);let i={tag:n},a=await this.caller.call(Vt(this.debug),`${this.apiUrl}/datasets/${o}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(a,"index dataset"),await a.json()}async similarExamples(e,r,n,{filter:o}={}){let i={limit:n,inputs:e};o!==void 0&&(i.filter=o),Kr(r);let a=await this.caller.call(Vt(this.debug),`${this.apiUrl}/datasets/${r}/search`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(i),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await sn(a,"fetch similar examples"),(await a.json()).examples}async createExample(e,r,n){if(a4e(e)&&(r!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let o=r?n?.datasetId:e.dataset_id,i=r?n?.datasetName:e.dataset_name;if(o===void 0&&i===void 0)throw new Error("Must provide either datasetName or datasetId");if(o!==void 0&&i!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");o===void 0&&(o=(await this.readDataset({datasetName:i})).id);let a=(r?n?.createdAt:e.created_at)||new Date,s;a4e(e)?s=e:s={inputs:e,outputs:r,created_at:a?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};let u=await this._uploadExamplesMultipart(o,[s]);return await this.readExample(u.example_ids?.[0]??as())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let y=e,S=y[0].dataset_id,x=y[0].dataset_name;if(S===void 0&&x===void 0)throw new Error("Must provide either datasetName or datasetId");if(S!==void 0&&x!==void 0)throw new
2025-07-05 20:48:33 +08:00
Current tenant: ${n.tenant_handle}
Requested tenant: ${r}`)}async _getLatestCommitHash(e){let r=await this.caller.call(Vt(this.debug),`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),n=await r.json();if(!r.ok){let o=typeof n.detail=="string"?n.detail:JSON.stringify(n.detail),i=new Error(`Error ${r.status}: ${r.statusText}
2025-07-12 10:26:56 +08:00
${o}`);throw i.statusCode=r.status,i}if(n.commits.length!==0)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(e,r){let[n,o,i]=CC(e),a=await this.caller.call(Vt(this.debug),`${this.apiUrl}/likes/${n}/${o}`,{method:"POST",body:JSON.stringify({like:r}),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await sn(a,`${r?"like":"unlike"} prompt`),await a.json()}async _getPromptUrl(e){let[r,n,o]=CC(e);if(await this._currentTenantIsOwner(r)){let i=await this._getSettings();return o!=="latest"?`${this.getHostUrl()}/prompts/${n}/${o.substring(0,8)}?organizationId=${i.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${i.id}`}else return o!=="latest"?`${this.getHostUrl()}/hub/${r}/${n}/${o.substring(0,8)}`:`${this.getHostUrl()}/hub/${r}/${n}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){for await(let r of this._getPaginated(`/commits/${e}/`,new URLSearchParams,n=>n.commits))yield*r}async*listPrompts(e){let r=new URLSearchParams;r.append("sort_field",e?.sortField??"updated_at"),r.append("sort_direction","desc"),r.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&r.append("is_public",e.isPublic.toString()),e?.query&&r.append("query",e.query);for await(let n of this._getPaginated("/repos",r,o=>o.repos))yield*n}async getPrompt(e){let[r,n,o]=CC(e),i=await this.caller.call(Vt(this.debug),`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(i.status===404)return null;await sn(i,"get prompt");let a=await i.json();return a.repo?a.repo:null}async createPrompt(e,r){let n=await this._getSettings();if(r?.isPublic&&!n.tenant_handle)throw new Error(`Cannot create a public prompt without first
2025-07-05 20:48:33 +08:00
creating a LangChain Hub handle.
You can add a handle by creating a public prompt at:
2025-07-12 10:26:56 +08:00
https://smith.langchain.com/prompts`);let[o,i,a]=CC(e);if(!await this._currentTenantIsOwner(o))throw await this._ownerConflictError("create a prompt",o);let s={repo_handle:i,...r?.description&&{description:r.description},...r?.readme&&{readme:r.readme},...r?.tags&&{tags:r.tags},is_public:!!r?.isPublic},u=await this.caller.call(Vt(this.debug),`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(u,"create prompt");let{repo:l}=await u.json();return l}async createCommit(e,r,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[o,i,a]=CC(e),s=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${o}/${i}`):n?.parentCommitHash,u={manifest:JSON.parse(JSON.stringify(r)),parent_commit:s},l=await this.caller.call(Vt(this.debug),`${this.apiUrl}/commits/${o}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(u),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await sn(l,"create commit");let c=await l.json();return this._getPromptUrl(`${o}/${i}${c.commit_hash?`:${c.commit_hash}`:""}`)}async updateExamplesMultipart(e,r=[]){return this._updateExamplesMultipart(e,r)}async _updateExamplesMultipart(e,r=[]){if(!await this._getMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let n=new FormData;for(let s of r){let u=s.id,l={...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split}},c=hp(l),d=new Blob([c],{type:"application/json"});if(n.append(u,d),s.inputs){let f=hp(s.inputs),p=new Blob([f],{type:"application/json"});n.append(`${u}.inputs`,p)}if(s.outputs){let f=hp(s.outputs),p=new Blob([f],{type:"application/json"});n.append(`${u}.outputs`,p)}if(s.attachments)for(let[f,p]of Object.entries(s.attachments)){let m,h;Array.isArray(p)?[m,h]=p:(m=p.mimeType,h=p.data);let b=new Blob([h],{type:`${m}; length=${h.byteLength}`});n.append(`${u}.attachment.${f}`,b)}if(s.attachments_operations){let f=hp(s.attachments_operations),p=new Blob([f],{type:"application/json"});n.append(`${u}.attachments_operations`,p)}}let o=e??r[0]?.dataset_id;return await(await this.caller.call(Vt(this.debug),`${this.apiUrl}/v1/platform/datasets/${o}/examples`,{method:"PATCH",headers:this.headers,body:n})).json()}async uploadExamplesMultipart(e,r=[]){return this._uploadExamplesMultipart(e,r)}async _uploadExamplesMultipart(e,r=[]){if(!await this._getMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let n=new FormData;for(let a of r){let s=(a.id??as()).toString(),u={created_at:a.created_at,...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split},...a.source_run_id&&{source_run_id:a.source_run_id},...a.use_source_run_io&&{use_source_run_io:a.use_source_run_io},...a.use_source_run_attachments&&{use_source_run_attachments:a.use_source_run_attachments}},l=hp(u),c=new Blob([l],{type:"application/json"});if(n.append(s,c),a.inputs){let d=hp(a.inputs),f=new Blob([d],{type:"application/json"});n.append(`${s}.inputs`,f)}if(a.outputs){let d=hp(a.outputs),f=new Blob([d],{type:"application/json"});n.append(`${s}.outputs`,f)}if(a.attachments)for(let[d,f]of Object.entries(a.attachments)){let p,m;Array.isArray(f)?[p,m]=f:(p=f.mimeType,m=f.data);let h=new Blob([m],{type:`${p}; length=${m.byteLength}`});n.append(`${s}.attachment.${d}`,h)}}let o=await this.caller.call(Vt(this.debug),`${this.apiUrl}/v1/platform/datasets/${e}/examples`,{method:"POST",headers:this.headers,body:n});return await sn(o,"upload examples"),await o.json()}async updatePrompt(e,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[n,o]=CC(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("
`));return t},pNn=Symbol.for("langsmith:traceable:root")});var Ype=w(()=>{h4e()});function aG(t,e){return Nir.call(t,e)}function sG(t){if(Array.isArray(t)){let r=new Array(t.length);for(let n=0;n<r.length;n++)r[n]=""+n;return r}if(Object.keys)return Object.keys(t);let e=[];for(let r in t)aG(t,r)&&e.push(r);return e}function Md(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function uG(t){let e=0,r=t.length,n;for(;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}function zb(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function P2(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function iG(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if(iG(t[r]))return!0}else if(typeof t=="object"){let r=sG(t),n=r.length;for(var e=0;e<n;e++)if(iG(t[r[e]]))return!0}}return!1}function g4e(t,e){let r=[t];for(let n in e){let o=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof o<"u"&&r.push(`${n}: ${o}`)}return r.join(`
`)}var Nir,hR,E2=w(()=>{Nir=Object.prototype.hasOwnProperty;hR=class extends Error{constructor(e,r,n,o,i){super(g4e(e,{name:r,index:n,operation:o,tree:i})),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:o}),Object.defineProperty(this,"tree",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.setPrototypeOf(this,new.target.prototype),this.message=g4e(e,{name:r,index:n,operation:o,tree:i})}}});var Zpe={};Cf(Zpe,{JsonPatchError:()=>ss,_areEquals:()=>T2,applyOperation:()=>gR,applyPatch:()=>AE,applyReducer:()=>Fir,deepClone:()=>Dir,getValueByPointer:()=>lG,validate:()=>y4e,validator:()=>cG});function lG(t,e){if(e=="")return t;var r={op:"_get",path:e};return gR(t,r),r.value}function gR(t,e,r=!1,n=!0,o=!0,i=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):cG(e,0)),e.path===""){let a={newDocument:t};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=t,a;if(e.op==="move"||e.op==="copy")return a.newDocument=lG(t,e.from),e.op==="move"&&(a.removed=t),a;if(e.op==="test"){if(a.test=T2(t,e.value),a.test===!1)throw new ss("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return a.newDocument=t,a}else{if(e.op==="remove")return a.removed=t,a.newDocument=null,a;if(e.op==="_get")return e.value=t,a;if(r)throw new ss("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return a}}else{n||(t=Md(t));let s=(e.path||"").split("/"),u=t,l=1,c=s.length,d,f,p;for(typeof r=="function"?p=r:p=cG;;){if(f=s[l],f&&f.indexOf("~")!=-1&&(f=P2(f)),o&&(f=="__proto__"||f=="prototype"&&l>0&&s[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&d===void 0&&(u[f]===void 0?d=s.slice(0,l).join("/"):l==c-1&&(d=e.path),d!==void 0&&p(e,0,t,d)),l++,Array.isArray(u)){if(f==="-")f=u.length;else{if(r&&!uG(f))throw new ss("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,t);uG(f)&&(f=~~f)}if(l>=c){if(r&&e.op==="add"&&f>u.length)throw new ss("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);let m=Lir[e.op].call(e,u,f,t);if(m.test===!1)throw new ss("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return m}}else if(l>=c){let m=VL[e.op].call(e,u,f,t);if(m.test===!1)throw new ss("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return m}if(u=u[f],r&&l<c&&(!u||typeof u!="object"))throw new ss("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function AE(t,e,r,n=!0,o=!0){if(r&&!Array.isArray(e))throw new ss("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=Md(t));let i=new Array(e.length);for(let a=0,s=e.length;a<s;a++)i[a]=gR(t,e[a],r,!0,o,a),t=i[a].newDocument;return i.newDocument=t,i}function Fir(t,e,r){let n=gR(t,e);if(n.test===!1)throw new ss("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function cG(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new ss("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(VL[t.op]){if(typeof t.path!="string")throw new ss("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new ss('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new ss("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)t
2025-07-05 20:48:33 +08:00
2025-07-12 10:26:56 +08:00
${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,r){e.child_runs.push(r)}_addRunToRunMap(e){let r=Zir(e.start_time,e.id,e.execution_order),n={...e};if(n.parent_run_id!==void 0){let o=this.runMap.get(n.parent_run_id);o&&(this._addChildRun(o,n),o.child_execution_order=Math.max(o.child_execution_order,n.child_execution_order),n.trace_id=o.trace_id,o.dotted_order!==void 0&&(n.dotted_order=[o.dotted_order,r].join(".")))}else n.trace_id=n.id,n.dotted_order=r;return this.runMap.set(n.id,n),n}async _endTrace(e){let r=e.parent_run_id!==void 0&&this.runMap.get(e.parent_run_id);r?r.child_execution_order=Math.max(r.child_execution_order,e.child_execution_order):await this.persistRun(e),this.runMap.delete(e.id),await this.onRunUpdate?.(e)}_getExecutionOrder(e){let r=e!==void 0&&this.runMap.get(e);return r?r.child_execution_order+1:1}_createRunForLLMStart(e,r,n,o,i,a,s,u){let l=this._getExecutionOrder(o),c=Date.now(),d=s?{...i,metadata:s}:i,f={id:n,name:u??e.id[e.id.length-1],parent_run_id:o,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{prompts:r},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:a||[]};return this._addRunToRunMap(f)}async handleLLMStart(e,r,n,o,i,a,s,u){let l=this.runMap.get(n)??this._createRunForLLMStart(e,r,n,o,i,a,s,u);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}_createRunForChatModelStart(e,r,n,o,i,a,s,u){let l=this._getExecutionOrder(o),c=Date.now(),d=s?{...i,metadata:s}:i,f={id:n,name:u??e.id[e.id.length-1],parent_run_id:o,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{messages:r},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:a||[]};return this._addRunToRunMap(f)}async handleChatModelStart(e,r,n,o,i,a,s,u){let l=this.runMap.get(n)??this._createRunForChatModelStart(e,r,n,o,i,a,s,u);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}async handleLLMEnd(e,r,n,o,i){let a=this.runMap.get(r);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.outputs=e,a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...i},await this.onLLMEnd?.(a),await this._endTrace(a),a}async handleLLMError(e,r,n,o,i){let a=this.runMap.get(r);if(!a||a?.run_type!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...i},await this.onLLMError?.(a),await this._endTrace(a),a}_createRunForChainStart(e,r,n,o,i,a,s,u){let l=this._getExecutionOrder(o),c=Date.now(),d={id:n,name:u??e.id[e.id.length-1],parent_run_id:o,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:r,execution_order:l,child_execution_order:l,run_type:s??"chain",child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(d)}async handleChainStart(e,r,n,o,i,a,s,u){let l=this.runMap.get(n)??this._createRunForChainStart(e,r,n,o,i,a,s,u);return await this.onRunCreate?.(l),await this.onChainStart?.(l),l}async handleChainEnd(e,r,n,o,i){let a=this.runMap.get(r);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.outputs=ime(e,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=ime(i.inputs,"input")),await this.onChainEnd?.(a),await this._endTrace(a),a}async handleChainError(e,r,n,o,i){let a=this.runMap.get(r);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=ime(i.inputs,"input")),await this.onChainError?.(a),await this._endTrace(a),a}_createRunForToolStart(e,r,n,o,i,a,s){let u=this._getExecutionOrder(o),l=Date.now(),c={id:n,name:s??e.id[e.id.length-1],parent_run_id:o,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{input:r},execution_order:u,ch
2025-07-05 20:48:33 +08:00
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
2025-07-12 10:26:56 +08:00
`,t}var M2=w(()=>{});function RE(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="tool_call")}function U4e(t){return!!(t&&typeof t=="object"&&"toolCall"in t&&t.toolCall!=null&&typeof t.toolCall=="object"&&"id"in t.toolCall&&typeof t.toolCall.id=="string")}var wR,mG=w(()=>{wR=class extends Error{constructor(e,r){super(e),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.output=r}}});function sme(t,e=KL){t=t.trim();let r=t.indexOf("```");if(r===-1)return e(t);let n=t.substring(r+3);n.startsWith(`json
2025-07-05 20:48:33 +08:00
`)?n=n.substring(5):n.startsWith("json")?n=n.substring(4):n.startsWith(`
2025-07-12 10:26:56 +08:00
`)&&(n=n.substring(1));let o=n.indexOf("```"),i=n;return o!==-1&&(i=n.substring(0,o)),e(i.trim())}function KL(t){if(typeof t>"u")return null;try{return JSON.parse(t)}catch{}let e="",r=[],n=!1,o=!1;for(let i of t){if(n)i==='"'&&!o?n=!1:i===`
`&&!o?i="\\n":i==="\\"?o=!o:o=!1;else if(i==='"')n=!0,o=!1;else if(i==="{")r.push("}");else if(i==="[")r.push("]");else if(i==="}"||i==="]")if(r&&r[r.length-1]===i)r.pop();else return null;e+=i}n&&(e+='"');for(let i=r.length-1;i>=0;i-=1)e+=r[i];try{return JSON.parse(e)}catch{return null}}var ume=w(()=>{});function jE(t){return typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"&&"source_type"in t&&(t.source_type==="url"||t.source_type==="base64"||t.source_type==="text"||t.source_type==="id")}function z4e(t){return jE(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}function H4e(t){return jE(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}function V4e(t){if(jE(t)){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url}};if(t.source_type==="base64"){if(!t.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${t.mime_type};base64,${t.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function lme({dataUrl:t,asTypedArray:e=!1}){let r=t.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),n;if(r){n=r[1].toLowerCase();let o=e?Uint8Array.from(atob(r[2]),i=>i.charCodeAt(0)):r[2];return{mime_type:n,data:o}}}function W4e(t,e){if(t.type==="text"){if(!e.fromStandardTextBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardTextBlock\` method.`);return e.fromStandardTextBlock(t)}if(t.type==="image"){if(!e.fromStandardImageBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardImageBlock\` method.`);return e.fromStandardImageBlock(t)}if(t.type==="audio"){if(!e.fromStandardAudioBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardAudioBlock\` method.`);return e.fromStandardAudioBlock(t)}if(t.type==="file"){if(!e.fromStandardFileBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardFileBlock\` method.`);return e.fromStandardFileBlock(t)}throw new Error(`Unable to convert content block type '${t.type}' to provider-specific format: not recognized.`)}var cme=w(()=>{});function Oh(t,e){return typeof t=="string"?t===""?e:typeof e=="string"?t+e:Array.isArray(e)&&e.some(r=>jE(r))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e]:Array.isArray(e)?R2(t,e)??[...t,...e]:e===""?t:Array.isArray(t)&&t.some(r=>jE(r))?[...t,{type:"file",source_type:"text",text:e}]:[...t,{type:"text",text:e}]}function K4e(t,e){return t==="error"||e==="error"?"error":"success"}function Qir(t,e){function r(n,o){if(typeof n!="object"||n===null||n===void 0)return n;if(o>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(a=>r(a,o+1));let i={};for(let a of Object.keys(n))i[a]=r(n[a],o+1);return i}return JSON.stringify(r(t,0),null,2)}function xs(t,e){let r={...t};for(let[n,o]of Object.entries(e))if(r[n]==null)r[n]=o;else{if(o==null)continue;if(typeof r[n]!=typeof o||Array.isArray(r[n])!==Array.isArray(o))throw new Error(`field[${n}] already exists in the message chunk, but with a different type.`);if(typeof r[n]=="string"){if(n==="type")continue;r[n]+=o}else if(typeof r[n]=="object"&&!Array.isArray(r[n]))r[n]=xs(r[n],o);else if(Array.isArray(r[n]))r[n]=R2(r[n],o);else{if(r[n]===o)continue;console.warn(`field[${n}] already exists in this message chunk and value has unsupported type.`)}}return r}function R2(t,e){if(!(t===void 0&&e===void 0)){if(t===void 0||e===void 0)return t||e;{let r=[...t];for(let n of e)if(typeof n=="object"&&"index"in n&&typeof n.index=="number"){let o=r.findIndex(i=>i.index===n.index);o!==-1?r[o]=xs(r[o],n):r.push(n)}else{if(typeof n=="object"&&"text"in n&&n.text==="")continue;r.push(n)}return r}}}function G4e(t,e){if(!t&&!e)throw new Error("Cannot merge two undefined objects.");if(!t||!e)return t||e;if(typeof t!=typeof e)throw new Error(`Cannot merge objects of different types.
2025-07-05 20:48:33 +08:00
Left ${typeof t}
2025-07-12 10:26:56 +08:00
Right ${typeof e}`);if(typeof t=="string"&&typeof e=="string")return t+e;if(Array.isArray(t)&&Array.isArray(e))return R2(t,e);if(typeof t=="object"&&typeof e=="object")return xs(t,e);if(t===e)return t;throw new Error(`Can not merge objects of different types.
2025-07-05 20:48:33 +08:00
Left ${t}
2025-07-12 10:26:56 +08:00
Right ${e}`)}function J4e(t){return typeof t.role=="string"}function Ph(t){return typeof t?._getType=="function"}function dme(t){return Ph(t)&&typeof t.concat=="function"}var Sl,bp,Eh=w(()=>{yR();cme();Sl=class extends gp{get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e=="string"?e:e.type==="text"?e.text:"").join(""):""}getType(){return this._getType()}constructor(e,r){typeof e=="string"&&(e={content:e,additional_kwargs:r,response_metadata:{}}),e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","messages"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"content",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"additional_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.content=e.content,this.additional_kwargs=e.additional_kwargs,this.response_metadata=e.response_metadata,this.id=e.id}toDict(){return{type:this._getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;let r=Qir(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${r}`}};bp=class extends Sl{}});function Y4e(t){return t!=null&&typeof t=="object"&&"lc_direct_tool_output"in t&&t.lc_direct_tool_output===!0}function Z4e(t){let e=[],r=[];for(let n of t)if(n.function){let o=n.function.name;try{let i=JSON.parse(n.function.arguments),a={name:o||"",args:i||{},id:n.id};e.push(a)}catch{r.push({name:o,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[e,r]}var EC,Th,GL=w(()=>{Eh();EC=class extends Sl{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}constructor(e,r,n){typeof e=="string"&&(e={content:e,name:n,tool_call_id:r}),super(e),Object.defineProperty(this,"lc_direct_tool_output",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}_getType(){return"tool"}static isInstance(e){return e._getType()==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},Th=class t extends bp{constructor(e){super(e),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}_getType(){return"tool"}concat(e){return new t({content:Oh(this.content,e.content),additional_kwargs:xs(this.additional_kwargs,e.additional_kwargs),response_metadata:xs(this.response_metadata,e.response_metadata),artifact:G4e(this.artifact,e.artifact)
2025-07-05 20:48:33 +08:00
2025-07-12 10:26:56 +08:00
Please upgrade your packages to versions that set`,"message tool calls. e.g., `yarn add @langchain/anthropic`,","yarn add @langchain/openai`, etc."].join(" "));try{if(o!=null&&i===void 0){let[a,s]=Z4e(o);n.tool_calls=a??[],n.invalid_tool_calls=s??[]}else n.tool_calls=n.tool_calls??[],n.invalid_tool_calls=n.invalid_tool_calls??[]}catch{n.tool_calls=[],n.invalid_tool_calls=[]}}super(n),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof n!="string"&&(this.tool_calls=n.tool_calls??this.tool_calls,this.invalid_tool_calls=n.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=n.usage_metadata}static lc_name(){return"AIMessage"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}};dr=class t extends bp{constructor(e){let r;if(typeof e=="string")r={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0)r={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0};else{let n=[],o=[];for(let i of e.tool_call_chunks){let a={};try{if(a=KL(i.args||"{}"),a===null||typeof a!="object"||Array.isArray(a))throw new Error("Malformed tool call chunk args.");n.push({name:i.name??"",args:a,id:i.id,type:"tool_call"})}catch{o.push({name:i.name,args:i.args,id:i.id,error:"Malformed args.",type:"invalid_tool_call"})}}r={...e,tool_calls:n,invalid_tool_calls:o,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(r),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tool_call_chunks",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_chunks=r.tool_call_chunks??this.tool_call_chunks,this.tool_calls=r.tool_calls??this.tool_calls,this.invalid_tool_calls=r.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=r.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks"}}static lc_name(){return"AIMessageChunk"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){let r={content:Oh(this.content,e.content),additional_kwargs:xs(this.additional_kwargs,e.additional_kwargs),response_metadata:xs(this.response_metadata,e.response_metadata),tool_call_chunks:[],id:this.id??e.id};if(this.tool_call_chunks!==void 0||e.tool_call_chunks!==void 0){let n=R2(this.tool_call_chunks,e.tool_call_chunks);n!==void 0&&n.length>0&&(r.tool_call_chunks=n)}if(this.usage_metadata!==void 0||e.usage_metadata!==void 0){let n={...(this.usage_metadata?.input_token_details?.audio!==void 0||e.usage_metadata?.input_token_details?.audio!==void 0)&&{audio:(this.usage_metadata?.input_token_details?.audio??0)+(e.usage_metadata?.input_token_details?.audio??0)},...(this.usage_metadata?.input_token_details?.cache_read!==void 0||e.usage_metadata?.input_token_details?.cache_read!==void 0)&&{cache_read:(this.usage_metadata?.input_token_details?.cache_read??0)+(e.usage_metadata?.input_token_details?.cache_read??0)},...(this.usage_metadata?.input_token_details?.cache_creation!==void 0||e.usage_metadata?.input_token_details?.cache_creation!==void 0)&&{cache_creation:(this.usage_metadata?.input_token_details?.cache_creation??0)+(e.usage_metadata?.input_token_details?.cache_creation??0)}},o={...(this
2025-07-05 20:48:33 +08:00
2025-07-12 10:26:56 +08:00
Received: ${JSON.stringify(t,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function fy(t){if(typeof t=="string")return new Os(t);if(Ph(t))return t;if(Array.isArray(t)){let[e,r]=t;return pme({type:e,content:r})}else if(J4e(t)){let{role:e,...r}=t;return pme({...r,type:e})}else return pme(t)}function Rf(t,e="Human",r="AI"){let n=[];for(let o of t){let i;if(o._getType()==="human")i=e;else if(o._getType()==="ai")i=r;else if(o._getType()==="system")i="System";else if(o._getType()==="function")i="Function";else if(o._getType()==="tool")i="Tool";else if(o._getType()==="generic")i=o.role;else throw new Error(`Got unsupported message type: ${o._getType()}`);let a=o.name?`${o.name}, `:"",s=typeof o.content=="string"?o.content:JSON.stringify(o.content,null,2);n.push(`${i}: ${a}${s}`)}return n.join(`
`)}function mme(t){let e=t._getType();if(e==="human")return new Mf({...t});if(e==="ai"){let r={...t};return"tool_calls"in r&&(r={...r,tool_call_chunks:r.tool_calls?.map(n=>({...n,type:"tool_call_chunk",index:void 0,args:JSON.stringify(n.args)}))}),new dr({...r})}else{if(e==="system")return new Rd({...t});if(e==="function")return new ym({...t});if(Cs.isInstance(t))return new If({...t});throw new Error("Unknown message type.")}}var NE=w(()=>{M2();mG();SR();Eh();hG();gG();j2();yG();GL()});var hme=w(()=>{eG()});var gme=w(()=>{XK()});var yme,X4e,Q4e=w(()=>{gme();bR();X4e=()=>{if(yme===void 0){let t=ot("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};yme=new mR(t)}return yme}});var JL,e3e=w(()=>{hme();Ype();bR();vR();Q4e();JL=class t extends xh{constructor(e={}){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"langchain_tracer"}),Object.defineProperty(this,"projectName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let{exampleId:r,projectName:n,client:o}=e;this.projectName=n??ot("LANGCHAIN_PROJECT")??ot("LANGCHAIN_SESSION"),this.exampleId=r,this.client=o??X4e();let i=t.getTraceableRunTree();i&&this.updateFromRunTree(i)}async _convertToCreate(e,r=void 0){return{...e,extra:{...e.extra,runtime:await N4e()},child_runs:void 0,session_name:this.projectName,reference_example_id:e.parent_run_id?void 0:r}}async persistRun(e){}async onRunCreate(e){let r=await this._convertToCreate(e,this.exampleId);await this.client.createRun(r)}async onRunUpdate(e){let r={end_time:e.end_time,error:e.error,outputs:e.outputs,events:e.events,inputs:e.inputs,trace_id:e.trace_id,dotted_order:e.dotted_order,parent_run_id:e.parent_run_id,extra:e.extra,session_name:this.projectName};await this.client.updateRun(e.id,r)}getRun(e){return this.runMap.get(e)}updateFromRunTree(e){let r=e,n=new Set;for(;r.parent_run&&!(n.has(r.id)||(n.add(r.id),!r.parent_run));)r=r.parent_run;n.clear();let o=[r];for(;o.length>0;){let i=o.shift();!i||n.has(i.id)||(n.add(i.id),this.runMap.set(i.id,i),i.child_runs&&o.push(...i.child_runs))}this.client=e.client??this.client,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId}convertToRunTree(e){let r={},n=[];for(let[o,i]of this.runMap){let a=new OC({...i,child_runs:[],parent_run:void 0,client:this.client,project_name:this.projectName,reference_example_id:this.exampleId,tracingEnabled:!0});r[o]=a,n.push([o,i.dotted_order])}n.sort((o,i)=>!o[1]||!i[1]?0:o[1].localeCompare(i[1]));for(let[o]of n){let i=this.runMap.get(o),a=r[o];if(!(!i||!a)&&i.parent_run_id){let s=r[i.parent_run_id];s&&(s.child_runs.push(a),a.parent_run=s)}}return r[e]}static getTraceableRunTree(){try{return m4e()}catch{return}}}});var t3e,xR,r3e,DE,N2=w(()=>{t3e=Symbol.for("ls:tracing_async_local_storage"),xR=Symbol.for("lc:context_variables"),r3e=t=>{globalThis[t3e]=t},DE=()=>globalThis[t3e]});function nar(){let t="default"in bG.default?bG.default.default:bG.default;return new t({autoStart:!0,concurrency:1})}function oar(){return typeof D2>"u"&&(D2=nar()),D2}async function Ps(t,e){if(e===!0){let r=DE();r!==void 0?await r.run(void 0,async()=>t()):await t()}else D2=oar(),D2.add(async()=>{let r=DE();r!==void 0?await r.run(void 0,async()=>t()):await t()})}var bG,D2,n3e=w(()=>{bG=F(DK(),1);N2()});var o3e=w(()=>{n3e()});var i3e,a3e=w(()=>{bR();i3e=t=>t!==void 0?t:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(r=>ot(r)==="true")});function bme(t){let e=DE();return e===void 0?void 0:e.getStore()?.[xR]?.[t]}var iar,s3e,u3e=w(()=>{hme();N2();iar=Symbol("lc:configure_hooks"),s3e=()=>bme(iar)||[]});function CR(t){return t?Array.isArray(t)||"name"in t?{callbacks:t}:t:{}}function L2(t){return"name"in t?t:_R.fromMethods(t)}var _me,YL,vme,_G,wme,Sme,Bs,LE=w(()=>{TE();A2();q4e();NE();bR();e3e();o3e();a3e();vR();u3e();_m
2025-07-05 20:48:33 +08:00
]))`;continue}else if(n[u]==="$"){o+=`($|(?=[\r
]))`;continue}}if(r.s&&n[u]==="."){o+=a?`${n[u]}\r
`:`[${n[u]}\r
2025-07-12 10:26:56 +08:00
]`;continue}o+=n[u],n[u]==="\\"?i=!0:a&&n[u]==="]"?a=!1:!a&&n[u]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var qme,my,par,MG=w(()=>{FE();my={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(qme===void 0&&(qme=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),qme),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};par=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function RG(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===de.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:fr(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:fr(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===de.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=IG(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===de.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===de.ZodBranded&&t.keyType._def.type._def.typeName===de.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=TG(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var jG=w(()=>{Td();qs();MG();AG()});function D3e(t,e){if(e.mapStrategy==="record")return RG(t,e);let r=fr(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=fr(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var zme=w(()=>{qs();jG()});function L3e(t){let e=t.values,n=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var Hme=w(()=>{});function F3e(){return{not:{}}}var Vme
`;return e}function X3e(t,e,r){let{firstNode:n,lastNode:o,nodeColors:i,withStyles:a=!0,curveStyle:s="linear",wrapLabelNWords:u=9}=r??{},l=a?`%%{init: {'flowchart': {'curve': '${s}'}}}%%
2025-07-05 20:48:33 +08:00
graph TD;
`:`graph TD;
2025-07-12 10:26:56 +08:00
`;if(a){let p="default",m={[p]:"{0}({1})"};n!==void 0&&(m[n]="{0}([{1}]):::first"),o!==void 0&&(m[o]="{0}([{1}]):::last");for(let[h,b]of Object.entries(t)){let g=b.name.split(":").pop()??"",S=war.some(O=>g.startsWith(O)&&g.endsWith(O))?`<p>${g}</p>`:g;Object.keys(b.metadata??{}).length&&(S+=`<hr/><small><em>${Object.entries(b.metadata??{}).map(([O,P])=>`${O} = ${P}`).join(`
`)}</em></small>`);let x=(m[h]??m[p]).replace("{0}",ihe(h)).replace("{1}",S);l+=` ${x}
2025-07-05 20:48:33 +08:00
`}}let c={};for(let p of e){let m=p.source.split(":"),h=p.target.split(":"),b=m.filter((g,y)=>g===h[y]).join(":");c[b]||(c[b]=[]),c[b].push(p)}let d=new Set;function f(p,m){let h=p.length===1&&p[0].source===p[0].target;if(m&&!h){let b=m.split(":").pop();if(d.has(b))throw new Error(`Found duplicate subgraph '${b}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(b),l+=` subgraph ${b}
2025-07-12 10:26:56 +08:00
`}for(let b of p){let{source:g,target:y,data:S,conditional:x}=b,O="";if(S!==void 0){let P=S,E=P.split(" ");E.length>u&&(P=Array.from({length:Math.ceil(E.length/u)},(A,I)=>E.slice(I*u,(I+1)*u).join(" ")).join("&nbsp;<br>&nbsp;")),O=x?` -. &nbsp;${P}&nbsp; .-> `:` -- &nbsp;${P}&nbsp; --> `}else O=x?" -.-> ":" --> ";l+=` ${ihe(g)}${O}${ihe(y)};
2025-07-05 20:48:33 +08:00
`}for(let b in c)b.startsWith(`${m}:`)&&b!==m&&f(c[b],b);m&&!h&&(l+=` end
2025-07-12 10:26:56 +08:00
`)}f(c[""]??[],"");for(let p in c)!p.includes(":")&&p!==""&&f(c[p],p);return a&&(l+=Sar(i??{})),l}async function Q3e(t,e){let{backgroundColor:r="white"}=e??{},n=btoa(t);r!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));let o=`https://mermaid.ink/img/${n}?bgColor=${r}`,i=await fetch(o);if(!i.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${i.status}`,`Status text: ${i.statusText}`].join(`
`));return await i.blob()}var war,eHe=w(()=>{war=["*","_","`"]});function xar(t,e){if(t!==void 0&&!EE(t))return t;if(q2(e))try{let r=e.getName();return r=r.startsWith("Runnable")?r.slice(8):r,r}catch{return e.getName()}else return e.name??"UnknownSchema"}function Car(t){return q2(t.data)?{type:"runnable",data:{id:t.data.lc_id,name:t.data.getName()}}:{type:"schema",data:{...So(t.data.schema),title:t.data.name}}}function tHe(t,e=[]){let r=new Set(t.edges.filter(o=>!e.includes(o.source)).map(o=>o.target)),n=[];for(let o of Object.values(t.nodes))!e.includes(o.id)&&!r.has(o.id)&&n.push(o);return n.length===1?n[0]:void 0}function rHe(t,e=[]){let r=new Set(t.edges.filter(o=>!e.includes(o.target)).map(o=>o.source)),n=[];for(let o of Object.values(t.nodes))!e.includes(o.id)&&!r.has(o.id)&&n.push(o);return n.length===1?n[0]:void 0}var z2,nHe=w(()=>{Ec();TE();Pme();eHe();z2=class t{constructor(e){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){let e={};return Object.values(this.nodes).forEach((r,n)=>{e[r.id]=EE(r.id)?n:r.id}),{nodes:Object.values(this.nodes).map(r=>({id:e[r.id],...Car(r)})),edges:this.edges.map(r=>{let n={source:e[r.source],target:e[r.target]};return typeof r.data<"u"&&(n.data=r.data),typeof r.conditional<"u"&&(n.conditional=r.conditional),n})}}addNode(e,r,n){if(r!==void 0&&this.nodes[r]!==void 0)throw new Error(`Node with id ${r} already exists`);let o=r??as(),i={id:o,data:e,name:xar(r,e),metadata:n};return this.nodes[o]=i,i}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(r=>r.source!==e.id&&r.target!==e.id)}addEdge(e,r,n,o){if(this.nodes[e.id]===void 0)throw new Error(`Source node ${e.id} not in graph`);if(this.nodes[r.id]===void 0)throw new Error(`Target node ${r.id} not in graph`);let i={source:e.id,target:r.id,data:n,conditional:o};return this.edges.push(i),i}firstNode(){return tHe(this)}lastNode(){return rHe(this)}extend(e,r=""){let n=r;Object.values(e.nodes).map(l=>l.id).every(EE)&&(n="");let i=l=>n?`${n}:${l}`:l;Object.entries(e.nodes).forEach(([l,c])=>{this.nodes[i(l)]={...c,id:i(l)}});let a=e.edges.map(l=>({...l,source:i(l.source),target:i(l.target)}));this.edges=[...this.edges,...a];let s=e.firstNode(),u=e.lastNode();return[s?{id:i(s.id),data:s.data}:void 0,u?{id:i(u.id),data:u.data}:void 0]}trimFirstNode(){let e=this.firstNode();e&&tHe(this,[e.id])&&this.removeNode(e)}trimLastNode(){let e=this.lastNode();e&&rHe(this,[e.id])&&this.removeNode(e)}reid(){let e=Object.fromEntries(Object.values(this.nodes).map(o=>[o.id,o.name])),r=new Map;Object.values(e).forEach(o=>{r.set(o,(r.get(o)||0)+1)});let n=o=>{let i=e[o];return EE(o)&&r.get(i)===1?i:o};return new t({nodes:Object.fromEntries(Object.entries(this.nodes).map(([o,i])=>[n(o),{...i,id:n(o)}])),edges:this.edges.map(o=>({...o,source:n(o.source),target:n(o.target)}))})}drawMermaid(e){let{withStyles:r,curveStyle:n,nodeColors:o={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:i}=e??{},a=this.reid(),s=a.firstNode(),u=a.lastNode();return X3e(a.nodes,a.edges,{firstNode:s?.id,lastNode:u?.id,withStyles:r,curveStyle:n,nodeColors:o,wrapLabelNWords:i})}async drawMermaidPng(e){let r=this.drawMermaid(e);return Q3e(r,{backgroundColor:e?.backgroundColor})}}});function oHe(t){let e=new TextEncoder,r=new ReadableStream({async start(n){for await(let o of t)n.enqueue(e.encode(`event: data
2025-07-05 20:48:33 +08:00
data: ${JSON.stringify(o)}
`));n.enqueue(e.encode(`event: end
2025-07-12 10:26:56 +08:00
`)),n.close()}});return Nd.fromReadableStream(r)}var iHe=w(()=>{Wb()});function ahe(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}function DG(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function*she(t,e){for(;;){let{value:r,done:n}=jd.runWithConfig(bm(t),e.next.bind(e),!0);if(n)break;yield r}}async function*LG(t,e){let r=e[Symbol.asyncIterator]();for(;;){let{value:n,done:o}=await jd.runWithConfig(bm(t),r.next.bind(e),!0);if(o)break;yield n}}var aHe,sHe=w(()=>{ZL();Hb();aHe=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function"});function xl(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function Oar(t){if(oG(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}function IC(t){if(typeof t=="function")return new Nf({func:t});if(Cn.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){let e={};for(let[r,n]of Object.entries(t))e[r]=IC(n);return new kE({steps:e})}else throw new Error(`Expected a Runnable, function or object.
Instead got an unsupported type.`)}function Par(t,e){let r=e.name??t.getName(),n=e.description??e.schema?.description;return e.schema.constructor===Wr.ZodString?new H2({name:r,description:n,schema:Wr.object({input:Wr.string()}).transform(o=>o.input),bound:t}):new H2({name:r,description:n,schema:e.schema,bound:t})}var uhe,Cn,MC,FG,kG,bi,kE,lhe,Nf,$G,eF,BG,H2,Df=w(()=>{Td();uhe=F(EK(),1);TE();Ype();h3e();y3e();yR();Wb();Cme();Hb();QL();_3e();Pme();ZL();nHe();iHe();sHe();mG();Cn=class extends gp{constructor(){super(...arguments),Object.defineProperty(this,"lc_runnable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}getName(e){let r=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${r}${e}`:r}bind(e){return new MC({bound:this,kwargs:e,config:{}})}map(){return new FG({bound:this})}withRetry(e){return new kG({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new MC({bound:this,config:e,kwargs:{}})}withFallbacks(e){let r=Array.isArray(e)?e:e.fallbacks;return new $G({runnable:this,fallbacks:r})}_getOptionsList(e,r=0){if(Array.isArray(e)&&e.length!==r)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${r} inputs`);if(Array.isArray(e))return e.map(un);if(r>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");let n=Object.fromEntries(Object.entries(e).filter(([o])=>o!=="runId"));return Array.from({length:r},(o,i)=>un(i===0?e:n))}return Array.from({length:r},()=>un(e))}async batch(e,r,n){let o=this._getOptionsList(r??{},e.length),i=o[0]?.maxConcurrency??n?.maxConcurrency,a=new _m({maxConcurrency:i,onFailedAttempt:u=>{throw u}}),s=e.map((u,l)=>a.call(async()=>{try{return await this.invoke(u,o[l])}catch(c){if(n?.returnExceptions)return c;throw c}}));return Promise.all(s)}async*_streamIterator(e,r){yield this.invoke(e,r)}async stream(e,r){let n=un(r),o=new AC({generator:this._streamIterator(e,n),config:n});return await o.setup,Nd.fromAsyncGenerator(o)}_separateRunnableConfigFromCallOptions(e){let r;e===void 0?r=un(e):r=un({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});let n={...e};return delete n.callbacks,delete n.tags,delete n.metadata,delete n.runName,delete n.configurable,delete n.recursionLimit,delete n.maxConcurrency,delete n.runId,delete n.timeout,delete n.signal,[r,n]}async _callWithConfig(e,r,n){let o=un(n),a=await(await _p(o))?.handleChainStart(this.toJSON(),xl(r,"input"),o.runId,o?.runType,void 0,void 0,o?.runName??this.getName());delete o.runId;let s;try{let u=e.call(this,r,o,a);s=await Vb(u,n?.signal)}catch(u){throw await a?.handleChainError(u),u}return await a?.handleChainEnd(xl(s,"output")),s}async _batchWithConfig(e,r,n,o){let i=this._getOptionsList(n??{},r.length),a=await Promise.all(i.map(_p)),s=await Promise.all(a.map(async(l,c)=>{let d=await l?.handleChainStart(this.toJSON(),xl(r[c],"input"),i[c].runId,i[c].runType,void 0,void 0,i[c].runName??this.getName());return delete i[c].runId,d})),u;try{let l=e.call(this,r,i,s,o);u=await Vb(l,i?.[0]?.signal)}catch(l){throw await Promise.all(s.map(c=>c?.handleChainError(l))),l}return await Promise.all(s.map(l=>l?.handleChainEnd(xl(u,"output")))),u}async*_transformStreamWithConfig(e,r,n){let o,i=!0,a,s=!0,u=un(n),l=await _p(u);async function*c(){for await(let f of e){if(i)if(o===void 0)o=f;else try{o=Hl(o,f)}catch{o=void 0,i=!1}yield f}}let d;try{let f=await d3e(r.bind(this),c(),async()=>l?.handleChainStart(this.toJSON(),{input:""},u.runId,u.runType,void 0,void 0,u.runName??this.getName()),n?.signal,u);delete u.runId,d=f.setup;let p=d?.handlers.find(g3e),m=f.output;p!==void 0&&d!==void 0&&(m=p.tapOutputIterable(d.runId,m));let h=d?.handlers.find(m3e);h!==void 0&&d!==void 0&&(m=h.tapOutputIterable(d.runId,m));for await(
2025-07-05 20:48:33 +08:00
Known schemas:
- ${Object.keys(n).join(`
2025-07-12 10:26:56 +08:00
- `)}`,new Error(ce)}let oe=`${s}/$ref`,se=oa(t,Pe,r,n,o,i,a,oe,u);if(se.valid||te.push({instanceLocation:a,keyword:"$ref",keywordLocation:oe,error:"A subschema had errors."},...se.errors),r==="4"||r==="7")return{valid:te.length===0,errors:te}}if(Array.isArray(m)){let Re=m.length,Pe=!1;for(let oe=0;oe<Re;oe++)if(c===m[oe]||m[oe]==="integer"&&c==="number"&&t%1===0&&t===t){Pe=!0;break}Pe||te.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m.join('", "')}".`})}else m==="integer"?(c!=="number"||t%1||t!==t)&&te.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m}".`}):m!==void 0&&c!==m&&te.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m}".`});if(h!==void 0&&(c==="object"||c==="array"?RC(t,h)||te.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):t!==h&&te.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),b!==void 0&&(c==="object"||c==="array"?b.some(Re=>RC(t,Re))||te.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`}):b.some(Re=>t===Re)||te.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`})),y!==void 0){let Re=`${s}/not`;oa(t,y,r,n,o,i,a,Re).valid&&te.push({instanceLocation:a,keyword:"not",keywordLocation:Re,error:'Instance matched "not" schema.'})}let et=[];if(S!==void 0){let Re=`${s}/anyOf`,Pe=te.length,oe=!1;for(let se=0;se<S.length;se++){let ce=S[se],Ce=Object.create(u),Je=oa(t,ce,r,n,o,p===!0?i:null,a,`${Re}/${se}`,Ce);te.push(...Je.errors),oe=oe||Je.valid,Je.valid&&et.push(Ce)}oe?te.length=Pe:te.splice(Pe,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:Re,error:"Instance does not match any subschemas."})}if(x!==void 0){let Re=`${s}/allOf`,Pe=te.length,oe=!0;for(let se=0;se<x.length;se++){let ce=x[se],Ce=Object.create(u),Je=oa(t,ce,r,n,o,p===!0?i:null,a,`${Re}/${se}`,Ce);te.push(...Je.errors),oe=oe&&Je.valid,Je.valid&&et.push(Ce)}oe?te.length=Pe:te.splice(Pe,0,{instanceLocation:a,keyword:"allOf",keywordLocation:Re,error:"Instance does not match every subschema."})}if(O!==void 0){let Re=`${s}/oneOf`,Pe=te.length,oe=O.filter((se,ce)=>{let Ce=Object.create(u),Je=oa(t,se,r,n,o,p===!0?i:null,a,`${Re}/${ce}`,Ce);return te.push(...Je.errors),Je.valid&&et.push(Ce),Je.valid}).length;oe===1?te.length=Pe:te.splice(Pe,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:Re,error:`Instance does not match exactly one subschema (${oe} matches).`})}if((c==="object"||c==="array")&&Object.assign(u,...et),P!==void 0){let Re=`${s}/if`;if(oa(t,P,r,n,o,i,a,Re,u).valid){if(E!==void 0){let oe=oa(t,E,r,n,o,i,a,`${s}/then`,u);oe.valid||te.push({instanceLocation:a,keyword:"if",keywordLocation:Re,error:'Instance does not match "then" schema.'},...oe.errors)}}else if(A!==void 0){let oe=oa(t,A,r,n,o,i,a,`${s}/else`,u);oe.valid||te.push({instanceLocation:a,keyword:"if",keywordLocation:Re,error:'Instance does not match "else" schema.'},...oe.errors)}}if(c==="object"){if(g!==void 0)for(let se of g)se in t||te.push({instanceLocation:a,keyword:"required",keywordLocation:`${s}/required`,error:`Instance does not have required property "${se}".`});let Re=Object.keys(t);if(k!==void 0&&Re.length<k&&te.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${k} properties.`}),z!==void 0&&Re.length>z&&te.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${z} properties.`}),V!==void 0){let se=`${s}/propertyNames`;for(let ce in t){let Ce=`${a}/${wm(ce)}`,Je=oa(ce,V,r,n,o,i,Ce,se);Je.valid||te.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:se,error:`Property name "${ce}" does not
2025-07-05 20:48:33 +08:00
"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
\`\`\`json
${JSON.stringify(So(this.schema))}
\`\`\`
2025-07-12 10:26:56 +08:00
`}async parse(e){try{let n=(e.includes("```")?e.trim().split(/```(?:json)?/)[1]:e.trim()).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(o,i)=>`"${i.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await this.schema.parseAsync(JSON.parse(n))}catch(r){throw new vm(`Failed to parse. Text: "${e}". Error: ${r}`,e)}}}});var yhe=w(()=>{Xpe()});var Ac,bhe=w(()=>{$E();yhe();ume();Ac=class extends AR{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}static lc_name(){return"JsonOutputParser"}_diff(e,r){if(r)return e?fG(e,r):[{op:"replace",path:"",value:r}]}async parsePartialResult(e){return sme(e[0].text)}async parse(e){return sme(e,JSON.parse)}getFormatInstructions(){return""}}});var SHe=w(()=>{});var xHe=w(()=>{$E();yhe();SHe()});var CHe=w(()=>{tF();bHe();_He();vHe();wHe();$E();bhe();xHe()});var gy=w(()=>{CHe()});var W2,rF,nF,VG,K2=w(()=>{yR();j2();NE();W2=class extends gp{},rF=class extends W2{static lc_name(){return"StringPromptValue"}constructor(e){super({value:e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.value=e}toString(){return this.value}toChatMessages(){return[new Os(this.value)]}},nF=class extends W2{static lc_name(){return"ChatPromptValue"}constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.messages=e.messages}toString(){return Rf(this.messages)}toChatMessages(){return this.messages}},VG=class extends W2{static lc_name(){return"ImagePromptValue"}constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"imageUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new Os({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}}});var NC,G2=w(()=>{K2();oF();NC=class extends Kb{async formatPromptValue(e){let r=await this.format(e);return new rF(r)}}});function vhe(t){return typeof t=="function"}function ssr(t){return aF(t)?"array":typeof t}function _he(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function OHe(t,e){return t!=null&&typeof t=="object"&&e in t}function usr(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}function csr(t,e){return lsr.call(t,e)}function fsr(t){return!csr(dsr,t)}function msr(t){return String(t).replace(/[&<>"'`=\/]/g,function(r){return psr[r]})}function _sr(t,e){if(!t)return[];var r=!1,n=[],o=[],i=[],a=!1,s=!1,u="",l=0;function c(){if(a&&!s)for(;i.length;)delete o[i.pop()];else i=[];a=!1,s=!1}var d,f,p;function m(A){if(typeof A=="string"&&(A=A.split(gsr,2)),!aF(A)||A.length!==2)throw new Error("Invalid tags: "+A);d=new RegExp(_he(A[0])+"\\s*"),f=new RegExp("\\s*"+_he(A[1])),p=new RegExp("\\s*"+_he("}"+A[1]))}m(e||Ah.tags);for(var h=new Y2(t),b,g,y,S,x,O;!h.eos();){if(b=h.pos,y=h.scanUntil(d),y)for(var P=0,E=y.length;P<E;++P)S=y.charAt(P),fsr(S)?(i.push(o.length),u+=S):(s=!0,r=!0,u+=" "),o.push(["text",S,b,b+1]),b+=1,S===`
`&&(c(),u="",l=0,r=!1);if(!h.scan(d))break;if(a=!0,g=h.scan(bsr)||"name",h.scan(hsr),g==="="?(y=h.scanUntil(PHe),h.scan(PHe),h.scanUntil(f)):g==="{"?(y=h.scanUntil(p),h.scan(ysr),h.scanUntil(f),g="&"):y=h.scanUntil(f),!h.scan(f))throw new Error("Unclosed tag at "+h.pos);if(g==">"?x=[g,y,b,h.pos,u,l,r]:x=[g,y,b,h.pos],l++,o.push(x),g==="#"||g==="^")n.push(x);else if(g==="/"){if(O=n.pop(),!O)throw new Error('Unopened section "'+y+'" at '+b);if(O[1]!==y)throw new Error('Unclosed section "'+O[1]+'" at '+b)}else g==="name"||g==="{"||g==="&"?s=!0:g==="="&&m(y)}if(c(),O=n.pop(),O)throw new Error('Unclosed section "'+O[1]+'" at '+h.pos);return wsr(vsr(o))}function vsr(t){for(var e=[],r,n,o=0,i=t.length;o<i;++o)r=t[o],r&&(r[0]==="text"&&n&&n[0]==="text"?(n[1]+=r[1],n[3]=r[3]):(e.push(r),n=r));return e}function wsr(t){for(var e=[],r=e,n=[],o,i,a=0,s=t.length;a<s;++a)switch(o=t[a],o[0]){case"#":case"^":r.push(o),n.push(o),r=o[4]=[];break;case"/":i=n.pop(),i[5]=o[2],r=n.length>0?n[n.length-1][4]:e;break;default:r.push(o)}return e}function Y2(t){this.string=t,this.tail=t,this.pos=0}function iF(t,e){this.view=t,this.cache={".":this.view},this.parent=e}function Lf(){this.templateCache={_cache:{},set:function(e,r){this._cache[e]=r},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}var asr,aF,lsr,dsr,psr,hsr,gsr,PHe,ysr,bsr,Ah,J2,WG,EHe=w(()=>{asr=Object.prototype.toString,aF=Array.isArray||function(e){return asr.call(e)==="[object Array]"};lsr=RegExp.prototype.test;dsr=/\S/;psr={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};hsr=/\s*/,gsr=/\s+/,PHe=/\s*=/,ysr=/\s*\}/,bsr=/#|\^|\/|>|\{|&|=|!/;Y2.prototype.eos=function(){return this.tail===""};Y2.prototype.scan=function(e){var r=this.tail.match(e);if(!r||r.index!==0)return"";var n=r[0];return this.tail=this.tail.substring(n.length),this.pos+=n.length,n};Y2.prototype.scanUntil=function(e){var r=this.tail.search(e),n;switch(r){case-1:n=this.tail,this.tail="";break;case 0:n="";break;default:n=this.tail.substring(0,r),this.tail=this.tail.substring(r)}return this.pos+=n.length,n};iF.prototype.push=function(e){return new iF(e,this)};iF.prototype.lookup=function(e){var r=this.cache,n;if(r.hasOwnProperty(e))n=r[e];else{for(var o=this,i,a,s,u=!1;o;){if(e.indexOf(".")>0)for(i=o.view,a=e.split("."),s=0;i!=null&&s<a.length;)s===a.length-1&&(u=OHe(i,a[s])||usr(i,a[s])),i=i[a[s++]];else i=o.view[e],u=OHe(o.view,e);if(u){n=i;break}o=o.parent}r[e]=n}return vhe(n)&&(n=n.call(this.view)),n};Lf.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};Lf.prototype.parse=function(e,r){var n=this.templateCache,o=e+":"+(r||Ah.tags).join(":"),i=typeof n<"u",a=i?n.get(o):void 0;return a==null&&(a=_sr(e,r),i&&n.set(o,a)),a};Lf.prototype.render=function(e,r,n,o){var i=this.getConfigTags(o),a=this.parse(e,i),s=r instanceof iF?r:new iF(r,void 0);return this.renderTokens(a,s,n,e,o)};Lf.prototype.renderTokens=function(e,r,n,o,i){for(var a="",s,u,l,c=0,d=e.length;c<d;++c)l=void 0,s=e[c],u=s[0],u==="#"?l=this.renderSection(s,r,n,o,i):u==="^"?l=this.renderInverted(s,r,n,o,i):u===">"?l=this.renderPartial(s,r,n,i):u==="&"?l=this.unescapedValue(s,r):u==="name"?l=this.escapedValue(s,r,i):u==="text"&&(l=this.rawValue(s)),l!==void 0&&(a+=l);return a};Lf.prototype.renderSection=function(e,r,n,o,i){var a=this,s="",u=r.lookup(e[1]);function l(f){return a.render(f,r,n,i)}if(u){if(aF(u))for(var c=0,d=u.length;c<d;++c)s+=this.renderTokens(e[4],r.push(u[c]),n,o,i);else if(typeof u=="object"||typeof u=="string"||typeof u=="number")s+=this.renderTokens(e[4],r.push(u),n,o,i);else if(vhe(u)){if(typeof o!="string")throw new Error("Cannot use higher-order sections without the original template");u=u.call(r.view,o.slice(e[3],e[5]),l),u!=null&&(s+=u)}else s+=this.renderTokens(e[4],r,n,o,i);return s}};Lf.prototype.renderInverted=function(e,r,n,o,i){var a=r.lookup(e[1]);if(!a||aF(a)&&a.length===0)return this.renderTokens(e[4],r,n,o,i)};Lf.prototype.indentPartial=function(e,r,n){for(var o=r.replace(/[^ \t]/g,""),i=e.split(`
2025-07-05 20:48:33 +08:00
`),a=0;a<i.length;a++)i[a].length&&(a>0||!n)&&(i[a]=o+i[a]);return i.join(`
2025-07-12 10:26:56 +08:00
`)};Lf.prototype.renderPartial=function(e,r,n,o){if(n){var i=this.getConfigTags(o),a=vhe(n)?n(e[1]):n[e[1]];if(a!=null){var s=e[6],u=e[5],l=e[4],c=a;u==0&&l&&(c=this.indentPartial(a,l,s));var d=this.parse(c,i);return this.renderTokens(d,r,n,c,o)}}};Lf.prototype.unescapedValue=function(e,r){var n=r.lookup(e[1]);if(n!=null)return n};Lf.prototype.escapedValue=function(e,r,n){var o=this.getConfigEscape(n)||Ah.escape,i=r.lookup(e[1]);if(i!=null)return typeof i=="number"&&o===Ah.escape?String(i):o(i)};Lf.prototype.rawValue=function(e){return e[1]};Lf.prototype.getConfigTags=function(e){return aF(e)?e:e&&typeof e=="object"?e.tags:void 0};Lf.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!aF(e))return e.escape};Ah={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(t){J2.templateCache=t},get templateCache(){return J2.templateCache}},J2=new Lf;Ah.clearCache=function(){return J2.clearCache()};Ah.parse=function(e,r){return J2.parse(e,r)};Ah.render=function(e,r,n,o){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+ssr(e)+'" was given as the first argument for mustache#render(template, view, partials)');return J2.render(e,r,n,o)};Ah.escape=msr;Ah.Scanner=Y2;Ah.Context=iF;Ah.Writer=Lf;WG=Ah});function THe(){WG.escape=t=>t}var Z2,Ssr,KG,xsr,Csr,whe,Osr,Sp,X2,IR,MR=w(()=>{EHe();M2();Z2=t=>{let e=t.split(""),r=[],n=(i,a)=>{for(let s=a;s<e.length;s+=1)if(i.includes(e[s]))return s;return-1},o=0;for(;o<e.length;)if(e[o]==="{"&&o+1<e.length&&e[o+1]==="{")r.push({type:"literal",text:"{"}),o+=2;else if(e[o]==="}"&&o+1<e.length&&e[o+1]==="}")r.push({type:"literal",text:"}"}),o+=2;else if(e[o]==="{"){let i=n("}",o);if(i<0)throw new Error("Unclosed '{' in template.");r.push({type:"variable",name:e.slice(o+1,i).join("")}),o=i+1}else{if(e[o]==="}")throw new Error("Single '}' in template.");{let i=n("{}",o),a=(i<0?e.slice(o):e.slice(o,i)).join("");r.push({type:"literal",text:a}),o=i<0?e.length:i}}return r},Ssr=t=>t.map(e=>e[0]==="name"?{type:"variable",name:e[1].includes(".")?e[1].split(".")[0]:e[1]}:["#","&","^",">"].includes(e[0])?{type:"variable",name:e[1]}:{type:"literal",text:e[1]}),KG=t=>{THe();let e=WG.parse(t);return Ssr(e)},xsr=(t,e)=>Z2(t).reduce((r,n)=>{if(n.type==="variable"){if(n.name in e){let o=typeof e[n.name]=="string"?e[n.name]:JSON.stringify(e[n.name]);return r+o}throw new Error(`(f-string) Missing value for input ${n.name}`)}return r+n.text},""),Csr=(t,e)=>(THe(),WG.render(t,e)),whe={"f-string":xsr,mustache:Csr},Osr={"f-string":Z2,mustache:KG},Sp=(t,e,r)=>{try{return whe[e](t,r)}catch(n){throw ME(n,"INVALID_PROMPT_INPUT")}},X2=(t,e)=>Osr[e](t),IR=(t,e,r)=>{if(!(e in whe)){let n=Object.keys(whe);throw new Error(`Invalid template format. Got \`${e}\`;
should be one of ${n}`)}try{let n=r.reduce((o,i)=>(o[i]="foo",o),{});Array.isArray(t)?t.forEach(o=>{if(o.type==="text")Sp(o.text,e,n);else if(o.type==="image_url")if(typeof o.image_url=="string")Sp(o.image_url,e,n);else{let i=o.image_url.url;Sp(i,e,n)}else throw new Error(`Invalid message template received. ${JSON.stringify(o,null,2)}`)}):Sp(t,e,n)}catch(n){throw new Error(`Invalid prompt schema: ${n.message}`)}}});var She={};Cf(She,{PromptTemplate:()=>Dd});var Dd,sF=w(()=>{G2();MR();Dd=class t extends NC{static lc_name(){return"PromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"additionalContentFields",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e.templateFormat==="mustache"&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),IR(this.template,this.templateFormat,r)}}_getPromptType(){return"prompt"}async format(e){let r=await this.mergePartialAndUserVariables(e);return Sp(this.template,this.templateFormat,r)}static fromExamples(e,r,n,o=`
2025-07-05 20:48:33 +08:00
2025-07-12 10:26:56 +08:00
`,i=""){let a=[i,...e,r].join(o);return new t({inputVariables:n,template:a})}static fromTemplate(e,r){let{templateFormat:n="f-string",...o}=r??{},i=new Set;return X2(e,n).forEach(a=>{a.type==="variable"&&i.add(a.name)}),new t({inputVariables:[...i],templateFormat:n,template:e,...o})}async partial(e){let r=this.inputVariables.filter(i=>!(i in e)),n={...this.partialVariables??{},...e},o={...this,inputVariables:r,partialVariables:n};return new t(o)}serialize(){if(this.outputParser!==void 0)throw new Error("Cannot serialize a prompt template with an output parser");return{_type:this._getPromptType(),input_variables:this.inputVariables,template:this.template,template_format:this.templateFormat}}static async deserialize(e){if(!e.template)throw new Error("Prompt template must have a template");return new t({inputVariables:e.input_variables,template:e.template,templateFormat:e.template_format})}}});var uF,xhe=w(()=>{K2();oF();MR();uF=class t extends Kb{static lc_name(){return"ImagePromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","image"]}),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"additionalContentFields",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.template=e.template,this.templateFormat=e.templateFormat??this.templateFormat,this.validateTemplate=e.validateTemplate??this.validateTemplate,this.additionalContentFields=e.additionalContentFields,this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),IR([{type:"image_url",image_url:this.template}],this.templateFormat,r)}}_getPromptType(){return"prompt"}async partial(e){let r=this.inputVariables.filter(i=>!(i in e)),n={...this.partialVariables??{},...e},o={...this,inputVariables:r,partialVariables:n};return new t(o)}async format(e){let r={};for(let[a,s]of Object.entries(this.template))typeof s=="string"?r[a]=Sp(s,this.templateFormat,e):r[a]=s;let n=e.url||r.url,o=e.detail||r.detail;if(!n)throw new Error("Must provide either an image URL.");if(typeof n!="string")throw new Error("url must be a string.");let i={url:n};return o&&(i.detail=o),i}async formatPromptValue(e){let r=await this.format(e);return new VG(r)}}});function Che(t,e){let r=[];for(let n of Object.values(t))if(typeof n=="string")X2(n,e).forEach(o=>{o.type==="variable"&&r.push(o.name)});else if(Array.isArray(n))for(let o of n)typeof o=="string"?X2(o,e).forEach(i=>{i.type==="variable"&&r.push(i.name)}):typeof o=="object"&&r.push(...Che(o,e));else typeof n=="object"&&n!==null&&r.push(...Che(n,e));return Array.from(new Set(r))}function Ohe(t,e,r){let n={};for(let[o,i]of Object.entries(t))if(typeof i=="string")n[o]=Sp(i,r,e);else if(Array.isArray(i)){let a=[];for(let s of i)typeof s=="string"?a.push(Sp(s,r,e)):typeof s=="object"&&a.push(Ohe(s,e,r));n[o]=a}else typeof i=="object"&&i!==null?n[o]=Ohe(i,e,r):n[o]=i;return n}var Q2,Phe=w(()=>{Df();MR();Q2=class extends Cn{static lc_name(){return"DictPromptTemplate"}constructor(e){let r=e.templateFormat??"f-string",n=Che(e.template,r);super({inputVariables:n,...e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","dict"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"template",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.template=e.template,this.templateFormat=r,this.inputVariables=n}async format(e){return Ohe(this.template,e,this.template
2025-07-05 20:48:33 +08:00
2025-07-12 10:26:56 +08:00
`));throw a.name="InputFormatError",a.lc_error_code=o.lc_error_code,a}return n}},Ehe=class extends e4{constructor(e){"prompt"in e||(e={prompt:e}),super(e),Object.defineProperty(this,"prompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}},t4=class extends Kb{constructor(e){super(e)}async format(e){return(await this.formatPromptValue(e)).toString()}async formatPromptValue(e){let r=await this.formatMessages(e);return new nF(r)}},The=class extends Ehe{static lc_name(){return"ChatMessagePromptTemplate"}constructor(e,r){"prompt"in e||(e={prompt:e,role:r}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}async format(e){return new Cs(await this.prompt.format(e),this.role)}static fromTemplate(e,r,n){return new this(Dd.fromTemplate(e,{templateFormat:n?.templateFormat}),r)}};r4=class extends e4{static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}constructor(e,r){if("prompt"in e||(e={prompt:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts","chat"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"additionalOptions",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"prompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"messageClass",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chatMessageClass",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.prompt=e.prompt,Array.isArray(this.prompt)){let n=[];this.prompt.forEach(o=>{"inputVariables"in o&&(n=n.concat(o.inputVariables))}),this.inputVariables=n}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=r??this.additionalOptions}createMessage(e){let r=this.constructor;if(r._messageClass()){let n=r._messageClass();return new n({content:e})}else if(r.chatMessageClass){let n=r.chatMessageClass();return new n({content:e,role:this.getRoleFromMessageClass(n.lc_name())})}else throw new Error("No message class defined")}getRoleFromMessageClass(e){switch(e){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw new Error("Invalid message class name")}}static fromTemplate(e,r){if(typeof e=="string")return new this(Dd.fromTemplate(e,r));let n=[];for(let o of e)if(typeof o=="string")n.push(Dd.fromTemplate(o,r));else if(o!==null)if(Psr(o)){let i="";typeof o.text=="string"&&(i=o.text??"");let a={...r,additionalContentFields:o};n.push(Dd.fromTemplate(i,a))}else if(Esr(o)){let i=o.image_url??"",a,s=[];if(typeof i=="string"){let u;r?.templateFormat==="mustache"?u=KG(i):u=Z2(i);let l=u.flatMap(c=>c.type==="variable"?[c.name]:[]);if((l?.length??0)>0){if(l.length>1)throw new Error(`Only one format variable allowed per image template.
2025-07-05 20:48:33 +08:00
Got: ${l}
2025-07-12 10:26:56 +08:00
From: ${i}`);s=[l[0]]}else s=[];i={url:i},a=new uF({template:i,inputVariables:s,templateFormat:r?.templateFormat,additionalContentFields:o})}else if(typeof i=="object"){if("url"in i){let u;r?.templateFormat==="mustache"?u=KG(i.url):u=Z2(i.url),s=u.flatMap(l=>l.type==="variable"?[l.name]:[])}else s=[];a=new uF({template:i,inputVariables:s,templateFormat:r?.templateFormat,additionalContentFields:o})}else throw new Error("Invalid image template");n.push(a)}else typeof o=="object"&&n.push(new Q2({template:o,templateFormat:r?.templateFormat}));return new this({prompt:n,additionalOptions:r})}async format(e){if(this.prompt instanceof NC){let r=await this.prompt.format(e);return this.createMessage(r)}else{let r=[];for(let n of this.prompt){let o={};if(!("inputVariables"in n))throw new Error(`Prompt ${n} does not have inputVariables defined.`);for(let i of n.inputVariables)o||(o={[i]:e[i]}),o={...o,[i]:e[i]};if(n instanceof NC){let i=await n.format(o),a;"additionalContentFields"in n&&(a=n.additionalContentFields),r.push({...a,type:"text",text:i})}else if(n instanceof uF){let i=await n.format(o),a;"additionalContentFields"in n&&(a=n.additionalContentFields),r.push({...a,type:"image_url",image_url:i})}else if(n instanceof Q2){let i=await n.format(o),a;"additionalContentFields"in n&&(a=n.additionalContentFields),r.push({...a,...i})}}return this.createMessage(r)}}async formatMessages(e){return[await this.format(e)]}},Jb=class extends r4{static _messageClass(){return Os}static lc_name(){return"HumanMessagePromptTemplate"}},Ahe=class extends r4{static _messageClass(){return gn}static lc_name(){return"AIMessagePromptTemplate"}},BE=class extends r4{static _messageClass(){return TC}static lc_name(){return"SystemMessagePromptTemplate"}};xp=class t extends t4{static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}constructor(e){if(super(e),Object.defineProperty(this,"promptMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),e.templateFormat==="mustache"&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){let r=new Set;for(let s of this.promptMessages)if(!(s instanceof Sl))for(let u of s.inputVariables)r.add(u);let n=this.inputVariables,o=new Set(this.partialVariables?n.concat(Object.keys(this.partialVariables)):n),i=new Set([...o].filter(s=>!r.has(s)));if(i.size>0)throw new Error(`Input variables \`${[...i]}\` are not used in any of the prompt messages.`);let a=new Set([...r].filter(s=>!o.has(s)));if(a.size>0)throw new Error(`Input variables \`${[...a]}\` are used in prompt messages but not in the prompt template.`)}}_getPromptType(){return"chat"}async _parseImagePrompts(e,r){if(typeof e.content=="string")return e;let n=await Promise.all(e.content.map(async o=>{if(o.type!=="image_url")return o;let i="";typeof o.image_url=="string"?i=o.image_url:i=o.image_url.url;let s=await Dd.fromTemplate(i,{templateFormat:this.templateFormat}).format(r);return typeof o.image_url!="string"&&"url"in o.image_url?o.image_url.url=s:o.image_url=s,o}));return e.content=n,e}async formatMessages(e){let r=await this.mergePartialAndUserVariables(e),n=[];for(let o of this.promptMessages)if(o instanceof Sl)n.push(await this._parseImagePrompts(o,r));else{let i=o.inputVariables.reduce((s,u)=>{if(!(u in r)&&!(Isr(o)&&o.optional))throw ME(new Error(`Missing value for input variable \`${u.toString()}\``),"INVALID_PROMPT_INPUT");return s[u]=r[u],s},{}),a=await o.formatMessages(i);n=n.concat(a)}return n}async partial(e){let r=this.inputVariables.filter(i=>!(i in e)),n={...this.partialVariables??{},...e},o={...this,inputVariables:r,partialVariables:n};return new t(o)}static fromTemplate(e,r){let n=Dd.fromTemplate(e,r),o=new Jb({prompt:n});return this.fromMessages([o])}static fromMessages(e,r){let n=e.reduce((a,s)=>a.concat(s instanceof t?s.promptMessages:[Asr(s,r)]),[]
2025-07-05 20:48:33 +08:00
2025-07-12 10:26:56 +08:00
`}),Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.assign(this,e),this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),IR(this.prefix+this.suffix,this.templateFormat,r)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async partial(e){let r=this.inputVariables.filter(i=>!(i in e)),n={...this.partialVariables??{},...e},o={...this,inputVariables:r,partialVariables:n};return new t(o)}async format(e){let r=await this.mergePartialAndUserVariables(e),n=await this.getExamples(r),o=await Promise.all(n.map(a=>this.examplePrompt.format(a))),i=[this.prefix,...o,this.suffix].join(this.exampleSeparator);return Sp(i,this.templateFormat,r)}serialize(){if(this.exampleSelector||!this.examples)throw new Error("Serializing an example selector is not currently supported");if(this.outputParser!==void 0)throw new Error("Serializing an output parser is not currently supported");return{_type:this._getPromptType(),input_variables:this.inputVariables,example_prompt:this.examplePrompt.serialize(),example_separator:this.exampleSeparator,suffix:this.suffix,prefix:this.prefix,template_format:this.templateFormat,examples:this.examples}}static async deserialize(e){let{example_prompt:r}=e;if(!r)throw new Error("Missing example prompt");let n=await Dd.deserialize(r),o;if(Array.isArray(e.examples))o=e.examples;else throw new Error("Invalid examples format. Only list or string are supported.");return new t({inputVariables:e.input_variables,examplePrompt:n,examples:o,exampleSeparator:e.example_separator,prefix:e.prefix,suffix:e.suffix,templateFormat:e.template_format})}},Mhe=class t extends t4{_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"examples",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleSelector",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"examplePrompt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"suffix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"exampleSeparator",{enumerable:!0,configurable:!0,writable:!0,value:`
2025-07-05 20:48:33 +08:00
`}),Object.defineProperty(this,"prefix",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(this,"templateFormat",{enumerable:!0,configurable:!0,writable:!0,value:"f-string"}),Object.defineProperty(this,"validateTemplate",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.examples=e.examples,this.examplePrompt=e.examplePrompt,this.exampleSeparator=e.exampleSeparator??`
2025-07-12 10:26:56 +08:00
`,this.exampleSelector=e.exampleSelector,this.prefix=e.prefix??"",this.suffix=e.suffix??"",this.templateFormat=e.templateFormat??"f-string",this.validateTemplate=e.validateTemplate??!0,this.examples!==void 0&&this.exampleSelector!==void 0)throw new Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw new Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),IR(this.prefix+this.suffix,this.templateFormat,r)}}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw new Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(e){let r=await this.mergePartialAndUserVariables(e),n=await this.getExamples(r);n=n.map(i=>{let a={};return this.examplePrompt.inputVariables.forEach(s=>{a[s]=i[s]}),a});let o=[];for(let i of n){let a=await this.examplePrompt.formatMessages(i);o.push(...a)}return o}async format(e){let r=await this.mergePartialAndUserVariables(e),n=await this.getExamples(r),i=(await Promise.all(n.map(s=>this.examplePrompt.formatMessages(s)))).flat().map(s=>s.content),a=[this.prefix,...i,this.suffix].join(this.exampleSeparator);return Sp(a,this.templateFormat,r)}async partial(e){let r=this.inputVariables.filter(i=>!(i in e)),n={...this.partialVariables??{},...e},o={...this,inputVariables:r,partialVariables:n};return new t(o)}}});var Kb,oF=w(()=>{Df();Kb=class extends Cn{get lc_attributes(){return{partialVariables:void 0}}constructor(e){super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompts",this._getPromptType()]}),Object.defineProperty(this,"inputVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputParser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"partialVariables",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let{inputVariables:r}=e;if(r.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,e)}async mergePartialAndUserVariables(e){let r=this.partialVariables??{},n={};for(let[i,a]of Object.entries(r))typeof a=="string"?n[i]=a:n[i]=await a();return{...n,...e}}async invoke(e,r){let n={...this.metadata,...r?.metadata},o=[...this.tags??[],...r?.tags??[]];return this._callWithConfig(i=>this.formatPromptValue(i),e,{...r,tags:o,metadata:n,runType:"prompt"})}serialize(){throw new Error("Use .toJSON() instead")}static async deserialize(e){switch(e._type){case"prompt":{let{PromptTemplate:r}=await Promise.resolve().then(()=>(sF(),She));return r.deserialize(e)}case void 0:{let{PromptTemplate:r}=await Promise.resolve().then(()=>(sF(),She));return r.deserialize({...e,_type:"prompt"})}case"few_shot":{let{FewShotPromptTemplate:r}=await Promise.resolve().then(()=>(Rhe(),AHe));return r.deserialize(e)}default:throw new Error(`Invalid prompt type in config: ${e._type}`)}}}});var IHe=w(()=>{oF();n4()});var MHe=w(()=>{});var RHe=w(()=>{n4()});var jHe=w(()=>{oF();n4();Rhe();IHe();sF();MHe();G2();MR();xhe();RHe();Phe()});var qE=w(()=>{jHe()});var Sm=w(()=>{dhe()});var jhe,Nhe=w(()=>{jhe=t=>t.map(e=>e.pageContent).join(`
2025-07-05 20:48:33 +08:00
2025-07-12 10:26:56 +08:00
`)});var NHe=w(()=>{Nhe()});function Ih(t,e){let r=`atom${++Msr}`,n={toString(){return(Sa.env?Sa.env.MODE:void 0)!=="production"&&this.debugLabel?r+":"+this.debugLabel:r}};return typeof t=="function"?n.read=t:(n.init=t,n.read=Rsr,n.write=jsr),e&&(n.write=e),n}function Rsr(t){return t(this)}function jsr(t,e,r){return e(this,typeof r=="function"?r(t(this)):r)}var Sa,Msr,DHe,Dhe,Lhe,JG,khe,Nsr,Dsr,$he,LHe,GG,$He,FHe,lF,Fhe,Lsr,Fsr,kHe,UE,BHe,cF,o4,qHe,Bhe=w(()=>{Sa={},Msr=0;DHe=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,Dhe=t=>"init"in t,Lhe=t=>!!t.write,JG=new WeakMap,khe=t=>{var e;return $he(t)&&!((e=JG.get(t))!=null&&e[1])},Nsr=(t,e)=>{let r=JG.get(t);if(r)r[1]=!0,r[0].forEach(n=>n(e));else if((Sa.env?Sa.env.MODE:void 0)!=="production")throw new Error("[Bug] cancelable promise not found")},Dsr=t=>{if(JG.has(t))return;let e=[new Set,!1];JG.set(t,e);let r=()=>{e[1]=!0};t.then(r,r),t.onCancel=n=>{e[0].add(n)}},$he=t=>typeof t?.then=="function",LHe=t=>"v"in t||"e"in t,GG=t=>{if("e"in t)throw t.e;if((Sa.env?Sa.env.MODE:void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},$He=(t,e,r)=>{r.p.has(t)||(r.p.add(t),e.then(()=>{r.p.delete(t)},()=>{r.p.delete(t)}))},FHe=(t,e,r,n,o)=>{var i;if((Sa.env?Sa.env.MODE:void 0)!=="production"&&n===e)throw new Error("[Bug] atom cannot depend on itself");r.d.set(n,o.n),khe(r.v)&&$He(e,r.v,o),(i=o.m)==null||i.t.add(e),t&&Lsr(t,n,e)},lF=()=>[new Map,new Map,new Set],Fhe=(t,e,r)=>{t[0].has(e)||t[0].set(e,new Set),t[1].set(e,r)},Lsr=(t,e,r)=>{let n=t[0].get(e);n&&n.add(r)},Fsr=(t,e)=>t[0].get(e),kHe=(t,e)=>{t[2].add(e)},UE=t=>{let e,r=!1,n=o=>{try{o()}catch(i){r||(e=i,r=!0)}};for(;t[1].size||t[2].size;){t[0].clear();let o=new Set(t[1].values());t[1].clear();let i=new Set(t[2]);t[2].clear(),o.forEach(a=>{var s;return(s=a.m)==null?void 0:s.l.forEach(n)}),i.forEach(n)}if(r)throw e},BHe=(...[t,e,r,n])=>{let o;(Sa.env?Sa.env.MODE:void 0)!=="production"&&(o=new Set);let i=(S,x,O)=>{let P="v"in x,E=x.v,A=khe(x.v)?x.v:null;if($he(O)){Dsr(O);for(let I of x.d.keys())$He(S,O,t(I));x.v=O,delete x.e}else x.v=O,delete x.e;(!P||!Object.is(E,x.v))&&(++x.n,A&&Nsr(A,O))},a=(S,x,O)=>{var P;let E=t(x);if(LHe(E)&&(E.m&&!O?.has(x)||Array.from(E.d).every(([$,k])=>a(S,$,O).n===k)))return E;E.d.clear();let A=!0,I=$=>{if(DHe(x,$)){let z=t($);if(!LHe(z))if(Dhe($))i($,z,$.init);else throw new Error("no atom init");return GG(z)}let k=a(S,$,O);try{return GG(k)}finally{if(A)FHe(S,x,E,$,k);else{let z=lF();FHe(z,x,E,$,k),p(z,x,E),UE(z)}}},R,N,j={get signal(){return R||(R=new AbortController),R.signal},get setSelf(){return(Sa.env?Sa.env.MODE:void 0)!=="production"&&!Lhe(x)&&console.warn("setSelf function cannot be used with read-only atom"),!N&&Lhe(x)&&(N=(...$)=>{if((Sa.env?Sa.env.MODE:void 0)!=="production"&&A&&console.warn("setSelf function cannot be called in sync"),!A)return f(x,...$)}),N}};try{let $=e(x,I,j);if(i(x,E,$),$he($)){(P=$.onCancel)==null||P.call($,()=>R?.abort());let k=()=>{if(E.m){let z=lF();p(z,x,E),UE(z)}};$.then(k,k)}return E}catch($){return delete E.v,E.e=$,++E.n,E}finally{A=!1}},s=S=>GG(a(void 0,S)),u=(S,x,O)=>{var P,E;let A=new Map;for(let I of((P=O.m)==null?void 0:P.t)||[])A.set(I,t(I));for(let I of O.p)A.set(I,t(I));return(E=Fsr(S,x))==null||E.forEach(I=>{A.set(I,t(I))}),A};function l(S,x,O){let P=[],E=new Set,A=new Set,I=[[x,O]];for(;I.length>0;){let[R,N]=I[I.length-1];if(A.has(R)){I.pop();continue}if(E.has(R)){P.push([R,N,N.n]),A.add(R),I.pop();continue}E.add(R);for(let[j,$]of u(S,R,N))R!==j&&!E.has(j)&&I.push([j,$])}return[P,A]}let c=(S,x,O)=>{let[P,E]=l(S,x,O),A=new Set([x]);for(let I=P.length-1;I>=0;--I){let[R,N,j]=P[I],$=!1;for(let k of N.d.keys())if(k!==R&&A.has(k)){$=!0;break}$&&(a(S,R,E),p(S,R,N),j!==N.n&&(Fhe(S,R,N),A.add(R))),E.delete(R)}},d=(S,x,...O)=>{let P=!0,E=I=>GG(a(S,I)),A=(I,...R)=>{let N=t(I);try{if(DHe(x,I)){if(!Dhe(I))throw new Error("atom not writable");let j=N.n,$=R[0];i(I,N,$),p(S,I,N),j!==N.n&&(Fhe(S,I,N),c(S,I,N));return}else return d(S,I,...R)}finally{P||UE(S)}};try{return r(x,E,A,...O)}finally{P=!1}},f=(S,...x)=>{let O=lF();tr
2025-07-05 20:48:33 +08:00
<user_custom_instructions>
${t}
2025-07-12 10:26:56 +08:00
</user_custom_instructions>`:e}function rur(t){return t.activeModels=oVe(t.activeModels,Zb),t.activeEmbeddingModels=oVe(t.activeEmbeddingModels,jR),t}function kr(t){return`${t.name}|${t.provider}`}function oVe(t,e){let r=new Map;return e.filter(n=>n.core).forEach(n=>{r.set(kr(n),{...n})}),t.forEach(n=>{let o=kr(n),i=r.get(o);if(i){let a=e.find(s=>s.name===n.name&&s.provider===n.provider);a?r.set(o,{...a,...n,isBuiltIn:!0,believerExclusive:a.believerExclusive}):r.set(o,{...n,isBuiltIn:i.isBuiltIn})}else r.set(o,n)}),Array.from(r.values())}var ls,RR,nr=w(()=>{u4();c2();$r();ls=cF(),RR=Ih(Ic)});function ie(...t){ue().debug&&console.log(...t)}function fe(...t){ue().debug&&console.error(...t)}function Mh(...t){ue().debug&&console.warn(...t)}var yo=w(()=>{nr()});var cVe=v((Ghe,fF)=>{(function(t,e){typeof Ghe=="object"&&typeof fF<"u"?fF.exports=e():typeof define=="function"&&define.amd?define(e):t.moment=e()})(Ghe,function(){"use strict";var t;function e(){return t.apply(null,arguments)}function r(_){t=_}function n(_){return _ instanceof Array||Object.prototype.toString.call(_)==="[object Array]"}function o(_){return _!=null&&Object.prototype.toString.call(_)==="[object Object]"}function i(_,C){return Object.prototype.hasOwnProperty.call(_,C)}function a(_){if(Object.getOwnPropertyNames)return Object.getOwnPropertyNames(_).length===0;var C;for(C in _)if(i(_,C))return!1;return!0}function s(_){return _===void 0}function u(_){return typeof _=="number"||Object.prototype.toString.call(_)==="[object Number]"}function l(_){return _ instanceof Date||Object.prototype.toString.call(_)==="[object Date]"}function c(_,C){var T=[],M,L=_.length;for(M=0;M<L;++M)T.push(C(_[M],M));return T}function d(_,C){for(var T in C)i(C,T)&&(_[T]=C[T]);return i(C,"toString")&&(_.toString=C.toString),i(C,"valueOf")&&(_.valueOf=C.valueOf),_}function f(_,C,T,M){return Vqe(_,C,T,M,!0).utc()}function p(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidEra:null,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],era:null,meridiem:null,rfc2822:!1,weekdayMismatch:!1}}function m(_){return _._pf==null&&(_._pf=p()),_._pf}var h;Array.prototype.some?h=Array.prototype.some:h=function(_){var C=Object(this),T=C.length>>>0,M;for(M=0;M<T;M++)if(M in C&&_.call(this,C[M],M,C))return!0;return!1};function b(_){if(_._isValid==null){var C=m(_),T=h.call(C.parsedDateParts,function(L){return L!=null}),M=!isNaN(_._d.getTime())&&C.overflow<0&&!C.empty&&!C.invalidEra&&!C.invalidMonth&&!C.invalidWeekday&&!C.weekdayMismatch&&!C.nullInput&&!C.invalidFormat&&!C.userInvalidated&&(!C.meridiem||C.meridiem&&T);if(_._strict&&(M=M&&C.charsLeftOver===0&&C.unusedTokens.length===0&&C.bigHour===void 0),Object.isFrozen==null||!Object.isFrozen(_))_._isValid=M;else return M}return _._isValid}function g(_){var C=f(NaN);return _!=null?d(m(C),_):m(C).userInvalidated=!0,C}var y=e.momentProperties=[],S=!1;function x(_,C){var T,M,L,Z=y.length;if(s(C._isAMomentObject)||(_._isAMomentObject=C._isAMomentObject),s(C._i)||(_._i=C._i),s(C._f)||(_._f=C._f),s(C._l)||(_._l=C._l),s(C._strict)||(_._strict=C._strict),s(C._tzm)||(_._tzm=C._tzm),s(C._isUTC)||(_._isUTC=C._isUTC),s(C._offset)||(_._offset=C._offset),s(C._pf)||(_._pf=m(C)),s(C._locale)||(_._locale=C._locale),Z>0)for(T=0;T<Z;T++)M=y[T],L=C[M],s(L)||(_[M]=L);return _}function O(_){x(this,_),this._d=new Date(_._d!=null?_._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),S===!1&&(S=!0,e.updateOffset(this),S=!1)}function P(_){return _ instanceof O||_!=null&&_._isAMomentObject!=null}function E(_){e.suppressDeprecationWarnings===!1&&typeof console<"u"&&console.warn&&console.warn("Deprecation warning: "+_)}function A(_,C){var T=!0;return d(function(){if(e.deprecationHandler!=null&&e.deprecationHandler(null,_),T){var M=[],L,Z,he,tr=arguments.length;for(Z=0;Z<tr;Z++){if(L="",typeof arguments[Z]=="object"){L+=`
2025-07-05 20:48:33 +08:00
[`+Z+"] ";for(he in arguments[0])i(arguments[0],he)&&(L+=he+": "+arguments[0][he]+", ");L=L.slice(0,-2)}else L=arguments[Z];M.push(L)}E(_+`
Arguments: `+Array.prototype.slice.call(M).join("")+`
2025-07-12 10:26:56 +08:00
`+new Error().stack),T=!1}return C.apply(this,arguments)},C)}var I={};function R(_,C){e.deprecationHandler!=null&&e.deprecationHandler(_,C),I[_]||(E(C),I[_]=!0)}e.suppressDeprecationWarnings=!1,e.deprecationHandler=null;function N(_){return typeof Function<"u"&&_ instanceof Function||Object.prototype.toString.call(_)==="[object Function]"}function j(_){var C,T;for(T in _)i(_,T)&&(C=_[T],N(C)?this[T]=C:this["_"+T]=C);this._config=_,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)}function $(_,C){var T=d({},_),M;for(M in C)i(C,M)&&(o(_[M])&&o(C[M])?(T[M]={},d(T[M],_[M]),d(T[M],C[M])):C[M]!=null?T[M]=C[M]:delete T[M]);for(M in _)i(_,M)&&!i(C,M)&&o(_[M])&&(T[M]=d({},T[M]));return T}function k(_){_!=null&&this.set(_)}var z;Object.keys?z=Object.keys:z=function(_){var C,T=[];for(C in _)i(_,C)&&T.push(C);return T};var V={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"};function Q(_,C,T){var M=this._calendar[_]||this._calendar.sameElse;return N(M)?M.call(C,T):M}function J(_,C,T){var M=""+Math.abs(_),L=C-M.length,Z=_>=0;return(Z?T?"+":"":"-")+Math.pow(10,Math.max(0,L)).toString().substr(1)+M}var D=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,B=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,q={},K={};function H(_,C,T,M){var L=M;typeof M=="string"&&(L=function(){return this[M]()}),_&&(K[_]=L),C&&(K[C[0]]=function(){return J(L.apply(this,arguments),C[1],C[2])}),T&&(K[T]=function(){return this.localeData().ordinal(L.apply(this,arguments),_)})}function ee(_){return _.match(/\[[\s\S]/)?_.replace(/^\[|\]$/g,""):_.replace(/\\/g,"")}function U(_){var C=_.match(D),T,M;for(T=0,M=C.length;T<M;T++)K[C[T]]?C[T]=K[C[T]]:C[T]=ee(C[T]);return function(L){var Z="",he;for(he=0;he<M;he++)Z+=N(C[he])?C[he].call(L,_):C[he];return Z}}function W(_,C){return _.isValid()?(C=Y(C,_.localeData()),q[C]=q[C]||U(C),q[C](_)):_.localeData().invalidDate()}function Y(_,C){var T=5;function M(L){return C.longDateFormat(L)||L}for(B.lastIndex=0;T>=0&&B.test(_);)_=_.replace(B,M),B.lastIndex=0,T-=1;return _}var ae={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"};function Oe(_){var C=this._longDateFormat[_],T=this._longDateFormat[_.toUpperCase()];return C||!T?C:(this._longDateFormat[_]=T.match(D).map(function(M){return M==="MMMM"||M==="MM"||M==="DD"||M==="dddd"?M.slice(1):M}).join(""),this._longDateFormat[_])}var le="Invalid date";function Be(){return this._invalidDate}var ze="%d",rt=/\d{1,2}/;function cr(_){return this._ordinal.replace("%d",_)}var Sn={future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",w:"a week",ww:"%d weeks",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function je(_,C,T,M){var L=this._relativeTime[T];return N(L)?L(_,C,T,M):L.replace(/%d/i,_)}function mt(_,C){var T=this._relativeTime[_>0?"future":"past"];return N(T)?T(C):T.replace(/%s/i,C)}var ht={};function ft(_,C){var T=_.toLowerCase();ht[T]=ht[T+"s"]=ht[C]=_}function te(_){return typeof _=="string"?ht[_]||ht[_.toLowerCase()]:void 0}function et(_){var C={},T,M;for(M in _)i(_,M)&&(T=te(M),T&&(C[T]=_[M]));return C}var Re={};function Pe(_,C){Re[_]=C}function oe(_){var C=[],T;for(T in _)i(_,T)&&C.push({unit:T,priority:Re[T]});return C.sort(function(M,L){return M.priority-L.priority}),C}function se(_){return _%4===0&&_%100!==0||_%400===0}function ce(_){return _<0?Math.ceil(_)||0:Math.floor(_)}function Ce(_){var C=+_,T=0;return C!==0&&isFinite(C)&&(T=ce(C)),T}function Je(_,C){return function(T){return T!=null?(ea(this,_,T),e.updateOffset(this,C),this):ir(this,_)}}function ir(_,C){return _.isValid()?_._d["get"+(_._isUTC?"UTC":"")+C]():NaN}function ea(_,C,T){_.isValid()&&!isNaN(T)&&(C==="FullYear"&&se(_.year())
2025-07-05 20:48:33 +08:00
${t?.cause?"more message: "+t.cause.message:""}
2025-07-12 10:26:56 +08:00
${e?t.stack:""}`:JSON.stringify(t)}function l4(t,e){let r={...t};return e.forEach(n=>{delete r[n]}),r}function tJ(t,e){let[r,n]=t.split("|"),o=e.find(i=>i.name===r&&i.provider===n);if(!o)throw new Error(`No model configuration found for: ${t}`);return o}function Xb(t){let e=gF[t];return{...e,label:e.label||t}}function kf(t,e){let r=gF[t]?.label||t;return r+(e?.believerExclusive&&r==="Copilot Plus"?"(Believer)":"")}async function c4(t,e=!1){let r=app.workspace.getMostRecentLeaf();if(!r){new Rh.Notice("No active leaf found.");return}if(r.view instanceof Rh.MarkdownView||(r=app.workspace.getLeaf(!1),await r.setViewState({type:"markdown",state:r.view.getState()})),!(r.view instanceof Rh.MarkdownView)){new Rh.Notice("Failed to open a markdown view.");return}let n=r.view.editor,o=n.getCursor("from"),i=n.getCursor("to"),a=kR(t);e?n.replaceRange(a,o,i):n.replaceRange(a,i),new Rh.Notice("Message inserted into the active note.")}function rJ(t,e){let r;return(...n)=>{clearTimeout(r),r=setTimeout(()=>t(...n),e)}}function nJ(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let o=0;o<3;o++){if(r[o]>n[o])return!0;if(r[o]<n[o])return!1}return!1}async function vVe(){try{return{version:(await(0,Rh.requestUrl)({url:"https://api.github.com/repos/logancyang/obsidian-copilot/releases/latest",method:"GET"})).json.tag_name.replace("v",""),error:null}}catch(t){return{version:null,error:t instanceof Error?t.message:"Failed to check for updates"}}}function FR(t){if(typeof t=="string")return t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4");let e=t.modelName||t.model||"";return e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4")}function oJ(t,e="system"){return FR(t)?"human":e}function nge(){let t=["3rd party (openai-format)","ollama","lm-studio","azure openai","copilot-plus","copilot-plus-jina"];return Object.entries(gF).filter(([e])=>!t.includes(e)).map(([e])=>e)}function hF(t,e){let r=!!nge().find(i=>i===t.provider),n=Qb[t.provider],o=!t.apiKey&&!e[n];return r&&o?{hasApiKey:!1,errorNotice:`Please configure API Key for ${t.name} in settings first.
Path: Settings > copilot plugin > Basic Tab > Set Keys`}:{hasApiKey:!0}}function sur(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>e.text).join(""):String(t||"")}function kR(t){let r=sur(t).replace(/<think>[\s\S]*?<\/think>/g,"");return r=r.replace(/<think>[\s\S]*$/g,""),r.trim()}function wVe(){return crypto.randomUUID()}async function yy(t){let e=console.warn;try{return console.warn=function(...r){if(!(r[0]?.includes&&(r[0].includes("Failed to calculate number of tokens")||r[0].includes("Unknown model"))))return e.apply(console,r)},await t()}finally{console.warn=e}}var Zhe,Rh,Jhe,Xhe,our,iur,mVe,Vl,tge,yn=w(()=>{Fd();$r();yo();Zhe=F(cVe()),Rh=require("obsidian"),Jhe={INVALID_LICENSE_KEY_USER:"Invalid Copilot Plus license key. Please check your license key in settings.",UNKNOWN_ERROR:"An unknown error occurred",REQUEST_FAILED:t=>`Request failed, status ${t}`};Xhe=(t,e)=>{let r=t.getMarkdownFiles();if(e==="/")return r;let n=e.toLowerCase().replace(/^\/|\/$/g,"");return r.filter(o=>{let a=o.path.toLowerCase().split("/"),s=n.split("/"),u=0;for(let l of s){for(;u<a.length&&a[u]!==l;)u++;if(u>=a.length)return!1}return!0})};our=t=>t.last.bound.modelName||t.last.bound.model,iur=t=>t.last.bound.retriever!==void 0,mVe=t=>our(t)||iur(t),Vl=(t,e="local")=>{let r=(0,Zhe.default)(t);return e==="utc"&&r.utc(),{fileName:r.format("YYYYMMDD_HHmmss"),display:r.format("YYYY/MM/DD HH:mm:ss"),epoch:r.valueOf()}};tge=/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|shorts\/)|youtu\.be\/)([^\s&]+)/});var yF,oge,d4,Fd=w(()=>{gy();qE();Sm();NHe();yn();yF=class yF{static createNewLLMChain(e){let{llm:r,memory:n,prompt:o,abortController:i}=e,a=r.bind({signal:i?.signal}),s=bi.from([{input:u=>u.input,memory:()=>n.loadMemoryVariables({})},{input:u=>u.input,history:u=>u.memory.history},o,a]);return yF.instances.set("llm_chain",s),console.log("New LLM chain created."),s}static getLLMChainFromMap(e){let r=yF.instances.get("llm_chain");return r||(r=yF.createNewLLMChain(e)),r}static createConversationalRetrievalChain(e,r,n){let{llm:o,retriever:i,systemMessage:a}=e,u=Dd.fromTemplate(`Given the following conversation and a follow up question,
2025-07-05 20:48:33 +08:00
summarize the conversation as context and keep the follow up question unchanged, in its original language.
If the follow up question is unrelated to its preceding messages, return this follow up question directly.
If it is related, then combine the summary and the follow up question to construct a standalone question.
Make sure to keep any [[]] wrapped note titles in the question unchanged.
Chat History:
{chat_history}
Follow Up Input: {question}
Standalone question:`),c=Dd.fromTemplate(`{system_message}
Answer the question with as detailed as possible based only on the following context:
{context}
Question: {question}
`),d=b=>b.map(y=>`Human: ${y[0]}
Assistant: ${y[1]}`).join(`
2025-07-12 10:26:56 +08:00
`),f=bi.from([{question:b=>(n&&console.log("Input Question: ",b.question),b.question),chat_history:b=>{let g=d(b.chat_history);return n&&console.log("Formatted Chat History: ",g),g}},u,o,new HG,b=>{let g=kR(b);return n&&console.log("Standalone Question: ",g),g}]),p=async b=>(r(b),jhe(b)),m=bi.from([{context:i.pipe(p),question:new go,system_message:()=>a},c,o]);return f.pipe(m)}};yF.instances=new Map;oge=yF,d4=oge});var f4=w(()=>{});var VE,Es,Pi,e_,SVe,xVe,uVe,lVe,p4,iJ,OVe,ige,PVe,age,sge,t_,FC,jh,LC,WE,Zb,HE,jR,Yhe,gF,Qb,EVe,Br,uge,Nh,Ic,Dh,$r=w(()=>{c2();Fd();f4();VE="https://api.brevilabs.com/v1",Es="copilot-chat-view",Pi="user",e_="ai",SVe="copilot-conversations",xVe="copilot-custom-prompts",uVe=`You are Obsidian Copilot, a helpful assistant that integrates AI to Obsidian note-taking.
2025-07-05 20:48:33 +08:00
1. Never mention that you do not have access to something. Always rely on the user provided context.
2. Always answer to the best of your knowledge. If you are unsure about something, say so and ask the user to provide more context.
3. If the user mentions "note", it most likely means an Obsidian note in the vault, not the generic meaning of a note.
4. If the user mentions "@vault", it means the user wants you to search the Obsidian vault for information relevant to the query. The search results will be provided to you in the context along with the user query, read it carefully and answer the question based on the information provided. If there's no relevant information in the vault, just say so.
5. If the user mentions any other tool with the @ symbol, check the context for their results. If nothing is found, just ignore the @ symbol in the query.
6. Always use $'s instead of \\[ etc. for LaTeX equations.
7. When showing note titles, use [[title]] format and do not wrap them in \` \`.
8. When showing **Obsidian internal** image links, use ![[link]] format and do not wrap them in \` \`.
9. When showing **web** image links, use ![link](url) format and do not wrap them in \` \`.
10. When generating a table, use compact formatting without excessive whitespace.
11. Always respond in the language of the user's query.
12. Do NOT mention the additional context provided such as getCurrentTime and getTimeRangeMs if it's irrelevant to the user message.
2025-07-12 10:26:56 +08:00
13. If the user mentions "tags", it most likely means tags in Obsidian note properties.`,lVe=`Return the new note content or canvas JSON in a special JSON format.
2025-07-05 20:48:33 +08:00
# Steps to find the the target notes
1. Extract the target note information from user message and find out the note path from the context below.
2. If target note is not specified, use the <active_note> as the target note.
3. If still failed to find the target note or the note path, ask the user to specify the target note.
# JSON Format
Provide the content in JSON format and wrap it in a code block with the following structure:
For a single markdown file:
\`\`\`json
{
"type": "composer",
"path": "path/to/file.md",
"content": "The FULL CONTENT of the md note goes here"
}
\`\`\`
For a canvas file:
\`\`\`json
{
"type": "composer",
"path": "path/to/file.canvas",
"canvas_json": {
"nodes": [
{
"id": "1",
"type": "text",
"text": "Hello, world!",
"x": 0,
"y": 0,
"width": 200,
"height": 50
}
],
"edges": [
{
"id": "e1-2",
"fromNode": "1",
"toNode": "2",
"label": "connects to"
}
]
}
}
\`\`\`
# Important
* ALL JSON objects must be complete and valid - ensure all arrays and objects have matching closing brackets
* For canvas files, both 'nodes' and 'edges' arrays must be properly closed with ]
* Properly escape all special characters in the content field, especially backticks and quotes
* Prefer to create new files in existing folders or root folder unless the user's request specifies otherwise
* File paths must end with a .md or .canvas extension
* When generating changes on multiple files, output multiple JSON objects
* Each JSON object must be parseable independently
* For canvas files:
- Every node must have: id, type, x, y, width, height
- Every edge must have: id, fromNode, toNode
- All IDs must be unique
2025-07-12 10:26:56 +08:00
- Edge fromNode and toNode must reference existing node IDs`,p4="note_context",iJ=`Copilot index does not exist. Please index your vault first!
2025-07-05 20:48:33 +08:00
1. Set a working embedding model in QA settings. If it's not a local model, don't forget to set the API key.
2025-07-12 10:26:56 +08:00
2. Click 'Refresh Index for Vault' and wait for indexing to complete. If you encounter the rate limiting error, please turn your request per second down in QA setting.`,OVe=6e3,ige=.4,PVe=.4,age=15,sge=448e3,t_={DEFAULT:"",READING_FILES:"Reading files",SEARCHING_WEB:"Searching the web",READING_FILE_TREE:"Reading file tree"},FC={SETTINGS:"settings",EXPIRED_MODAL:"expired_modal",CHAT_MODE_SELECT:"chat_mode_select",MODE_SELECT_TOOLTIP:"mode_select_tooltip"},jh={MAX_TOKENS:6e3,TEMPERATURE:.1},LC=(m=>(m.OPENAI="openai",m.OPENAI_FORMAT="3rd party (openai-format)",m.AZURE_OPENAI="azure openai",m.ANTHROPIC="anthropic",m.COHEREAI="cohereai",m.GOOGLE="google",m.XAI="xai",m.OPENROUTERAI="openrouterai",m.GROQ="groq",m.OLLAMA="ollama",m.LM_STUDIO="lm-studio",m.COPILOT_PLUS="copilot-plus",m.MISTRAL="mistralai",m.DEEPSEEK="deepseek",m))(LC||{}),WE={reasoning:"This model supports general reasoning tasks.",vision:"This model supports image inputs.",websearch:"This model can access the internet."},Zb=[{name:"copilot-plus-flash",provider:"copilot-plus",enabled:!0,isBuiltIn:!0,core:!0,plusExclusive:!0,projectEnabled:!1,capabilities:["vision"]},{name:"google/gemini-2.5-flash-lite-preview-06-17",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"google/gemini-2.5-flash",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"google/gemini-2.5-pro",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-4.1",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-4.1-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-4.1-nano",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"o4-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["reasoning"]},{name:"claude-sonnet-4-20250514",provider:"anthropic",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"claude-3-7-sonnet-latest",provider:"anthropic",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"claude-3-5-sonnet-latest",provider:"anthropic",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"claude-3-5-haiku-latest",provider:"anthropic",enabled:!0,isBuiltIn:!0},{name:"grok-3-beta",provider:"xai",enabled:!0,isBuiltIn:!0},{name:"grok-3-mini-beta",provider:"xai",enabled:!0,isBuiltIn:!0},{name:"gemini-2.5-flash",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gemini-2.5-pro",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"command-r",provider:"cohereai",enabled:!0,isBuiltIn:!0},{name:"command-r-plus",provider:"cohereai",enabled:!0,isBuiltIn:!0},{name:"azure-openai",provider:"azure openai",enabled:!0,isBuiltIn:!0},{name:"deepseek-chat",provider:"deepseek",enabled:!0,isBuiltIn:!0},{name:"deepseek-reasoner",provider:"deepseek",enabled:!0,isBuiltIn:!0,capabilities:["reasoning"]}],HE=(l=>(l.OPENAI="openai",l.COHEREAI="cohereai",l.GOOGLE="google",l.AZURE_OPENAI="azure openai",l.OLLAMA="ollama",l.LM_STUDIO="lm-studio",l.OPENAI_FORMAT="3rd party (openai-format)",l.COPILOT_PLUS="copilot-plus",l.COPILOT_PLUS_JINA="copilot-plus-jina",l))(HE||{}),jR=[{name:"copilot-plus-small",provider:"copilot-plus",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,plusExclusive:!0},{name:"copilot-plus-large",provider:"copilot-plus-jina",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,plusExclusive:!0,believerExclusive:!0,dimensions:1024},{name:"copilot-plus-multilingual",provider:"copilot-plus-jina",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,plusExclusive:!0,dimensions:512},{name:"text-embedding-3-small",provider:"openai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0},{name:"text-embedding-3-large",provider:"openai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"embed-multilingual-light-v3.0",provider:"cohereai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{n
`+Fge+t}var kge=!1;function $ge(t,e){if(!t||kge)return"";kge=!0;var r=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(e)if(e=function(){throw Error()},Object.defineProperty(e.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(e,[])}catch(l){var n=l}Reflect.construct(t,[],e)}else{try{e.call()}catch(l){n=l}t.call(e.prototype)}else{try{throw Error()}catch(l){n=l}t()}}catch(l){if(l&&n&&typeof l.stack=="string"){for(var o=l.stack.split(`
2025-07-05 20:48:33 +08:00
`),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=`
2025-07-12 10:26:56 +08:00
`+o[a].replace(" at new "," at ");return t.displayName&&u.includes("<anonymous>")&&(u=u.replace("<anonymous>",t.displayName)),u}while(1<=a&&0<=s);break}}}finally{kge=!1,Error.prepareStackTrace=r}return(t=t?t.displayName||t.name:"")?E4(t):""}function Gur(t){switch(t.tag){case 5:return E4(t.type);case 16:return E4("Lazy");case 13:return E4("Suspense");case 19:return E4("SuspenseList");case 0:case 2:case 15:return t=$ge(t.type,!1),t;case 11:return t=$ge(t.type.render,!1),t;case 1:return t=$ge(t.type,!0),t;default:return""}}function lye(t){if(t==null)return null;if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case EF:return"Fragment";case PF:return"Portal";case aye:return"Profiler";case ebe:return"StrictMode";case sye:return"Suspense";case uye:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case A6e:return(t.displayName||"Context")+".Consumer";case T6e:return(t._context.displayName||"Context")+".Provider";case tbe:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case rbe:return e=t.displayName||null,e!==null?e:lye(t.type)||"Memo";case ZE:e=t._payload,t=t._init;try{return lye(t(e))}catch{}}return null}function Jur(t){var e=t.type;switch(t.tag){case 24:return"Cache";case 9:return(e.displayName||"Context")+".Consumer";case 10:return(e._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return t=e.render,t=t.displayName||t.name||"",e.displayName||(t!==""?"ForwardRef("+t+")":"ForwardRef");case 7:return"Fragment";case 5:return e;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return lye(e);case 8:return e===ebe?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e}return null}function dT(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function M6e(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function Yur(t){var e=M6e(t)?"checked":"value",r=Object.getOwnPropertyDescriptor(t.constructor.prototype,e),n=""+t[e];if(!t.hasOwnProperty(e)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var o=r.get,i=r.set;return Object.defineProperty(t,e,{configurable:!0,get:function(){return o.call(this)},set:function(a){n=""+a,i.call(this,a)}}),Object.defineProperty(t,e,{enumerable:r.enumerable}),{getValue:function(){return n},setValue:function(a){n=""+a},stopTracking:function(){t._valueTracker=null,delete t[e]}}}}function xJ(t){t._valueTracker||(t._valueTracker=Yur(t))}function R6e(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var r=e.getValue(),n="";return t&&(n=M6e(t)?t.checked?"true":"false":t.value),t=n,t!==r?(e.setValue(t),!0):!1}function ZJ(t){if(t=t||(typeof document<"u"?document:void 0),typeof t>"u")return null;try{return t.activeElement||t.body}catch{return t.body}}function cye(t,e){var r=e.checked;return $a({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??t._wrapperState.initialChecked})}function x8e(t,e){var r=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;r=dT(e.value!=null?e.value:r),t._wrapperState={initialChecked:n,initialValue:r,controlled:e.type==="checkbox"||e.type==="radio"?e.checked!=null:e.value!=null}}function j6e(t,e){e=e.checked,e!=null&&Qye(t,"checked",e,!1)}function dye(t,e){j6e(t,e);var r=dT(e.value),n=e.type;if(r!=null)n==="number"?(r===0&&t.value===""||t.value!=r)&&(t.value=""+r):t.value!==""+r&&(t.value=""+r);else if(n==="submit"||n==="reset"){t.removeAttribute("value");return}e.hasOwnProperty("value")?fye(t,e.type,r):e.hasOwnProperty("defaultValue")&&fye(t,e.type,dT(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}function C
`).replace(ocr,"")}function DJ(t,e,r){if(e=G8e(e),G8e(t)!==e&&r)throw Error(qe(425))}function i7(){}var Pye=null,Eye=null;function Tye(t,e){return t==="textarea"||t==="noscript"||typeof e.children=="string"||typeof e.children=="number"||typeof e.dangerouslySetInnerHTML=="object"&&e.dangerouslySetInnerHTML!==null&&e.dangerouslySetInnerHTML.__html!=null}var Aye=typeof setTimeout=="function"?setTimeout:void 0,icr=typeof clearTimeout=="function"?clearTimeout:void 0,J8e=typeof Promise=="function"?Promise:void 0,acr=typeof queueMicrotask=="function"?queueMicrotask:typeof J8e<"u"?function(t){return J8e.resolve(null).then(t).catch(scr)}:Aye;function scr(t){setTimeout(function(){throw t})}function Jge(t,e){var r=e,n=0;do{var o=r.nextSibling;if(t.removeChild(r),o&&o.nodeType===8)if(r=o.data,r==="/$"){if(n===0){t.removeChild(o),V4(e);return}n--}else r!=="$"&&r!=="$?"&&r!=="$!"||n++;r=o}while(r);V4(e)}function aT(t){for(;t!=null;t=t.nextSibling){var e=t.nodeType;if(e===1||e===3)break;if(e===8){if(e=t.data,e==="$"||e==="$!"||e==="$?")break;if(e==="/$")return null}}return t}function Y8e(t){t=t.previousSibling;for(var e=0;t;){if(t.nodeType===8){var r=t.data;if(r==="$"||r==="$!"||r==="$?"){if(e===0)return t;e--}else r==="/$"&&e++}t=t.previousSibling}return null}var XF=Math.random().toString(36).slice(2),s_="__reactFiber$"+XF,Y4="__reactProps$"+XF,VC="__reactContainer$"+XF,Iye="__reactEvents$"+XF,ucr="__reactListeners$"+XF,lcr="__reactHandles$"+XF;function GR(t){var e=t[s_];if(e)return e;for(var r=t.parentNode;r;){if(e=r[VC]||r[s_]){if(r=e.alternate,e.child!==null||r!==null&&r.child!==null)for(t=Y8e(t);t!==null;){if(r=t[s_])return r;t=Y8e(t)}return e}t=r,r=t.parentNode}return null}function i3(t){return t=t[s_]||t[VC],!t||t.tag!==5&&t.tag!==6&&t.tag!==13&&t.tag!==3?null:t}function MF(t){if(t.tag===5||t.tag===6)return t.stateNode;throw Error(qe(33))}function O7(t){return t[Y4]||null}var Mye=[],RF=-1;function mT(t){return{current:t}}function aa(t){0>RF||(t.current=Mye[RF],Mye[RF]=null,RF--)}function zi(t,e){RF++,Mye[RF]=t.current,t.current=e}var fT={},Ud=mT(fT),Ap=mT(!1),QR=fT;function VF(t,e){var r=t.type.contextTypes;if(!r)return fT;var n=t.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===e)return n.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in r)o[i]=e[i];return n&&(t=t.stateNode,t.__reactInternalMemoizedUnmaskedChildContext=e,t.__reactInternalMemoizedMaskedChildContext=o),o}function Ip(t){return t=t.childContextTypes,t!=null}function a7(){aa(Ap),aa(Ud)}function Z8e(t,e,r){if(Ud.current!==fT)throw Error(qe(168));zi(Ud,e),zi(Ap,r)}function w5e(t,e,r){var n=t.stateNode;if(e=e.childContextTypes,typeof n.getChildContext!="function")return r;n=n.getChildContext();for(var o in n)if(!(o in e))throw Error(qe(108,Jur(t)||"Unknown",o));return $a({},r,n)}function s7(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||fT,QR=Ud.current,zi(Ud,t),zi(Ap,Ap.current),!0}function X8e(t,e,r){var n=t.stateNode;if(!n)throw Error(qe(169));r?(t=w5e(t,e,QR),n.__reactInternalMemoizedMergedChildContext=t,aa(Ap),aa(Ud),zi(Ud,t)):aa(Ap),zi(Ap,r)}var BC=null,P7=!1,Yge=!1;function S5e(t){BC===null?BC=[t]:BC.push(t)}function ccr(t){P7=!0,S5e(t)}function hT(){if(!Yge&&BC!==null){Yge=!0;var t=0,e=_i;try{var r=BC;for(_i=1;t<r.length;t++){var n=r[t];do n=n(!0);while(n!==null)}BC=null,P7=!1}catch(o){throw BC!==null&&(BC=BC.slice(t+1)),K6e(obe,hT),o}finally{_i=e,Yge=!1}}return null}var jF=[],NF=0,u7=null,l7=0,$h=[],Bh=0,e1=null,qC=1,UC="";function WR(t,e){jF[NF++]=l7,jF[NF++]=u7,u7=t,l7=e}function x5e(t,e,r){$h[Bh++]=qC,$h[Bh++]=UC,$h[Bh++]=e1,e1=t;var n=qC;t=UC;var o=32-Cy(n)-1;n&=~(1<<o),r+=1;var i=32-Cy(e)+o;if(30<i){var a=o-o%5;i=(n&(1<<a)-1).toString(32),n>>=a,o-=a,qC=1<<32-Cy(e)+o|r<<o|n,UC=i+t}else qC=1<<i|r<<o|n,UC=t}function pbe(t){t.return!==null&&(WR(t,1),x5e(t,1,0))}function mbe(t){for(;t===u7;)u7=jF[--NF],jF[NF]=null,l7=jF[--NF],jF[NF]=null;for(;t===e1;)e1=$h[--Bh],$h[Bh]=null,UC=$h[--Bh],$h[Bh]=null,qC=$h[--Bh],$h[Bh]=null}var Om=null,Cm=null,Ca=!1,xy=null;function C5e(t,e){var r=qh(5,null,null,0);r.elementT
2025-07-05 20:48:33 +08:00
Error generating stack: `+i.message+`
2025-07-12 10:26:56 +08:00
`+i.stack}return{value:t,source:e,stack:o,digest:null}}function tye(t,e,r){return{value:t,source:null,stack:r??null,digest:e??null}}function Fye(t,e){try{console.error(e.value)}catch(r){setTimeout(function(){throw r})}}var _cr=typeof WeakMap=="function"?WeakMap:Map;function X5e(t,e,r){r=zC(-1,r),r.tag=3,r.payload={element:null};var n=e.value;return r.callback=function(){y7||(y7=!0,Kye=n),Fye(t,e)},r}function Q5e(t,e,r){r=zC(-1,r),r.tag=3;var n=t.type.getDerivedStateFromError;if(typeof n=="function"){var o=e.value;r.payload=function(){return n(o)},r.callback=function(){Fye(t,e)}}var i=t.stateNode;return i!==null&&typeof i.componentDidCatch=="function"&&(r.callback=function(){Fye(t,e),typeof n!="function"&&(uT===null?uT=new Set([this]):uT.add(this));var a=e.stack;this.componentDidCatch(e.value,{componentStack:a!==null?a:""})}),r}function u6e(t,e,r){var n=t.pingCache;if(n===null){n=t.pingCache=new _cr;var o=new Set;n.set(e,o)}else o=n.get(e),o===void 0&&(o=new Set,n.set(e,o));o.has(r)||(o.add(r),t=jcr.bind(null,t,e,r),e.then(t,t))}function l6e(t){do{var e;if((e=t.tag===13)&&(e=t.memoizedState,e=e!==null?e.dehydrated!==null:!0),e)return t;t=t.return}while(t!==null);return null}function c6e(t,e,r,n,o){return(t.mode&1)===0?(t===e?t.flags|=65536:(t.flags|=128,r.flags|=131072,r.flags&=-52805,r.tag===1&&(r.alternate===null?r.tag=17:(e=zC(-1,1),e.tag=2,sT(r,e,1))),r.lanes|=1),t):(t.flags|=65536,t.lanes=o,t)}var vcr=GC.ReactCurrentOwner,Tp=!1;function $f(t,e,r,n){e.child=t===null?M5e(e,null,r,n):KF(e,t.child,r,n)}function d6e(t,e,r,n,o){r=r.render;var i=e.ref;return UF(e,o),n=Obe(t,e,r,n,i,o),r=Pbe(),t!==null&&!Tp?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,KC(t,e,o)):(Ca&&r&&pbe(e),e.flags|=1,$f(t,e,n,o),e.child)}function f6e(t,e,r,n,o){if(t===null){var i=r.type;return typeof i=="function"&&!Lbe(i)&&i.defaultProps===void 0&&r.compare===null&&r.defaultProps===void 0?(e.tag=15,e.type=i,eWe(t,e,i,n,o)):(t=YJ(r.type,null,n,e,e.mode,o),t.ref=e.ref,t.return=e,e.child=t)}if(i=t.child,(t.lanes&o)===0){var a=i.memoizedProps;if(r=r.compare,r=r!==null?r:K4,r(a,n)&&t.ref===e.ref)return KC(t,e,o)}return e.flags|=1,t=cT(i,n),t.ref=e.ref,t.return=e,e.child=t}function eWe(t,e,r,n,o){if(t!==null){var i=t.memoizedProps;if(K4(i,n)&&t.ref===e.ref)if(Tp=!1,e.pendingProps=n=i,(t.lanes&o)!==0)(t.flags&131072)!==0&&(Tp=!0);else return e.lanes=t.lanes,KC(t,e,o)}return kye(t,e,r,n,o)}function tWe(t,e,r){var n=e.pendingProps,o=n.children,i=t!==null?t.memoizedState:null;if(n.mode==="hidden")if((e.mode&1)===0)e.memoizedState={baseLanes:0,cachePool:null,transitions:null},zi(FF,xm),xm|=r;else{if((r&1073741824)===0)return t=i!==null?i.baseLanes|r:r,e.lanes=e.childLanes=1073741824,e.memoizedState={baseLanes:t,cachePool:null,transitions:null},e.updateQueue=null,zi(FF,xm),xm|=t,null;e.memoizedState={baseLanes:0,cachePool:null,transitions:null},n=i!==null?i.baseLanes:r,zi(FF,xm),xm|=n}else i!==null?(n=i.baseLanes|r,e.memoizedState=null):n=r,zi(FF,xm),xm|=n;return $f(t,e,o,r),e.child}function rWe(t,e){var r=e.ref;(t===null&&r!==null||t!==null&&t.ref!==r)&&(e.flags|=512,e.flags|=2097152)}function kye(t,e,r,n,o){var i=Ip(r)?QR:Ud.current;return i=VF(e,i),UF(e,o),r=Obe(t,e,r,n,i,o),n=Pbe(),t!==null&&!Tp?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,KC(t,e,o)):(Ca&&n&&pbe(e),e.flags|=1,$f(t,e,r,o),e.child)}function p6e(t,e,r,n,o){if(Ip(r)){var i=!0;s7(e)}else i=!1;if(UF(e,o),e.stateNode===null)KJ(t,e),A5e(e,r,n),Lye(e,r,n,o),n=!0;else if(t===null){var a=e.stateNode,s=e.memoizedProps;a.props=s;var u=a.context,l=r.contextType;typeof l=="object"&&l!==null?l=zh(l):(l=Ip(r)?QR:Ud.current,l=VF(e,l));var c=r.getDerivedStateFromProps,d=typeof c=="function"||typeof a.getSnapshotBeforeUpdate=="function";d||typeof a.UNSAFE_componentWillReceiveProps!="function"&&typeof a.componentWillReceiveProps!="function"||(s!==n||u!==l)&&o6e(e,a,n,l),XE=!1;var f=e.memoizedState;a.state=f,f7(e,n,a,o),u=e.memoizedState,s!==n||f!==u||Ap.current||XE?(typeof c=="function"&&(Dye(e,r,c,n),u=e.memoizedState),(s=XE||n6e(e,r,s,n,f,u,l))?(d||typeof a.UNSAFE_componentWillMount!="funct
`)}});var WQe=v(CY=>{"use strict";Object.defineProperty(CY,"__esModule",{value:!0});CY.CohereTimeoutError=void 0;var i_e=class t extends Error{constructor(){super("Timeout"),Object.setPrototypeOf(this,t.prototype)}};CY.CohereTimeoutError=i_e});var As=v(sk=>{"use strict";Object.defineProperty(sk,"__esModule",{value:!0});sk.CohereTimeoutError=sk.CohereError=void 0;var hfr=VQe();Object.defineProperty(sk,"CohereError",{enumerable:!0,get:function(){return hfr.CohereError}});var gfr=WQe();Object.defineProperty(sk,"CohereTimeoutError",{enumerable:!0,get:function(){return gfr.CohereTimeoutError}})});var KQe=v(g_=>{"use strict";var yfr=g_&&g_.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),bfr=g_&&g_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),_fr=g_&&g_.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&yfr(e,t,r);return bfr(e,t),e};Object.defineProperty(g_,"__esModule",{value:!0});g_.BadRequestError=void 0;var vfr=_fr(As()),a_e=class t extends vfr.CohereError{constructor(e){super({message:"BadRequestError",statusCode:400,body:e}),Object.setPrototypeOf(this,t.prototype)}};g_.BadRequestError=a_e});var GQe=v(y_=>{"use strict";var wfr=y_&&y_.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Sfr=y_&&y_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),xfr=y_&&y_.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&wfr(e,t,r);return Sfr(e,t),e};Object.defineProperty(y_,"__esModule",{value:!0});y_.UnauthorizedError=void 0;var Cfr=xfr(As()),s_e=class t extends Cfr.CohereError{constructor(e){super({message:"UnauthorizedError",statusCode:401,body:e}),Object.setPrototypeOf(this,t.prototype)}};y_.UnauthorizedError=s_e});var JQe=v(b_=>{"use strict";var Ofr=b_&&b_.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Pfr=b_&&b_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Efr=b_&&b_.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Ofr(e,t,r);return Pfr(e,t),e};Object.defineProperty(b_,"__esModule",{value:!0});b_.ForbiddenError=void 0;var Tfr=Efr(As()),u_e=class t extends Tfr.CohereError{constructor(e){super({message:"ForbiddenError",statusCode:403,body:e}),Object.setPrototypeOf(this,t.prototype)}};b_.ForbiddenError=u_e});var YQe=v(__=>{"use strict";var Afr=__&&__.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),Ifr=__&&__.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Mfr=__&&__.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Afr(e,t,r);r
`));return r(o)}});var Oot,Cmr,Omr,Pmr,Emr,Tmr,Pot=w(()=>{Oot=async t=>{let e=t?.Bucket||"";if(typeof t.Bucket=="string"&&(t.Bucket=e.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),Tmr(e)){if(t.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!Emr(e)||e.indexOf(".")!==-1&&!String(t.Endpoint).startsWith("http:")||e.toLowerCase()!==e||e.length<3)&&(t.ForcePathStyle=!0);return t.DisableMultiRegionAccessPoints&&(t.disableMultiRegionAccessPoints=!0,t.DisableMRAP=!0),t},Cmr=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,Omr=/(\d+\.){3}\d+/,Pmr=/\.\./,Emr=t=>Cmr.test(t)&&!Omr.test(t)&&!Pmr.test(t),Tmr=t=>{let[e,r,n,,,o]=t.split(":"),i=e==="arn"&&t.split(":").length>=6,a=!!(i&&r&&n&&o);if(i&&!a)throw new Error(`Invalid ARN: ${t} was an invalid ARN.`);return a}});var Eot=w(()=>{Pot()});var Tot,Aot=w(()=>{Tot=(t,e,r)=>{let n=async()=>{let o=r[t]??r[e];return typeof o=="function"?o():o};return t==="credentialScope"||e==="CredentialScope"?async()=>{let o=typeof r.credentials=="function"?await r.credentials():r.credentials;return o?.credentialScope??o?.CredentialScope}:t==="accountId"||e==="AccountId"?async()=>{let o=typeof r.credentials=="function"?await r.credentials():r.credentials;return o?.accountId??o?.AccountId}:t==="endpoint"||e==="endpoint"?async()=>{let o=await n();if(o&&typeof o=="object"){if("url"in o)return o.url.href;if("hostname"in o){let{protocol:i,hostname:a,port:s,path:u}=o;return`${i}//${a}${s?":"+s:""}${u}`}}return o}:n}});var Iot,Mot=w(()=>{Iot=async t=>{}});function Rot(t){let e={};if(t=t.replace(/^\?/,""),t)for(let r of t.split("&")){let[n,o=null]=r.split("=");n=decodeURIComponent(n),o&&(o=decodeURIComponent(o)),n in e?Array.isArray(e[n])?e[n].push(o):e[n]=[e[n],o]:e[n]=o}return e}var jot=w(()=>{});var TT,fZ=w(()=>{jot();TT=t=>{if(typeof t=="string")return TT(new URL(t));let{hostname:e,pathname:r,port:n,protocol:o,search:i}=t,a;return i&&(a=Rot(i)),{hostname:e,port:n?parseInt(n):void 0,protocol:o,path:r,query:a}}});var pZ,mZ=w(()=>{fZ();pZ=t=>typeof t=="object"?"url"in t?TT(t.url):t:TT(t)});var Not,Amr,eve=w(()=>{Eot();Aot();Mot();mZ();Not=async(t,e,r,n)=>{if(!r.endpoint){let a=await Iot(r.serviceId||"");a&&(r.endpoint=()=>Promise.resolve(pZ(a)))}let o=await Amr(t,e,r);if(typeof r.endpointProvider!="function")throw new Error("config.endpointProvider is not set.");return r.endpointProvider(o,n)},Amr=async(t,e,r)=>{let n={},o=e?.getEndpointParameterInstructions?.()||{};for(let[i,a]of Object.entries(o))switch(a.type){case"staticContextParams":n[i]=a.value;break;case"contextParams":n[i]=t[a.name];break;case"clientContextParams":case"builtInParams":n[i]=await Tot(a.name,i,r)();break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(a))}return Object.keys(o).length===0&&Object.assign(n,r),String(r.serviceId).toLowerCase()==="s3"&&await Oot(n),n}});var Dot=w(()=>{eve();mZ()});var Lot,tve=w(()=>{jy();eve();Lot=({config:t,instructions:e})=>(r,n)=>async o=>{let i=await Not(o.input,{getEndpointParameterInstructions(){return e}},{...t},n);n.endpointV2=i,n.authSchemes=i.properties?.authSchemes;let a=n.authSchemes?.[0];if(a){n.signing_region=a.signingRegion,n.signing_service=a.signingName;let u=A_(n)?.selectedHttpAuthScheme?.httpAuthOption;u&&(u.signingProperties=Object.assign(u.signingProperties||{},{signing_region:a.signingRegion,signingRegion:a.signingRegion,signing_service:a.signingName,signingName:a.signingName,signingRegionSet:a.signingRegionSet},a.properties))}return r({...o})}});var Fot,rve=w(()=>{Fot=(t,e)=>r=>async n=>{let{response:o}=await r(n);try{let i=await e(o,t);return{response:o,output:i}}catch(i){if(Object.defineProperty(i,"$response",{value:o}),!("$metadata"in i)){let a="Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";i.message+=`
`+a,typeof i.$responseBodyText<"u"&&i.$response&&(i.$response.body=i.$responseBodyText)}throw i}}});var kot,nve=w(()=>{kot=(t,e)=>(r,n)=>async o=>{let i=n.endpointV2?.url&&t.urlParser?async()=>t.urlParser(n.endpointV2.url):t.endpoint;if(!i)throw new Error("No valid endpoint provider available.");let a=await e(o.input,{...t,endpoint:i});return r({...o,request:a})}});function Nt(t,e,r){return{applyToStack:n=>{n.add(Fot(t,r),Imr),n.add(kot(t,e),U3)}}}var Imr,U3,$ot=w(()=>{rve();nve();Imr={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},U3={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});var to=w(()=>{rve();$ot();nve()});var ove,Dt,Bot=w(()=>{to();tve();ove={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:U3.name},Dt=(t,e)=>({applyToStack:r=>{r.addRelativeTo(Lot({config:t,instructions:e}),ove)}})});var hZ,qot=w(()=>{jy();mZ();hZ=t=>{let e=t.tls??!0,{endpoint:r}=t,n=r!=null?async()=>pZ(await zd(r)()):void 0;return{...t,endpoint:n,tls:e,isCustomEndpoint:!!r,useDualstackEndpoint:zd(t.useDualstackEndpoint??!1),useFipsEndpoint:zd(t.useFipsEndpoint??!1)}}});var Uot=w(()=>{});var zn=w(()=>{Dot();tve();Bot();qot();Uot()});var Mmr,gZ,zot=w(()=>{zn();dZ();Mmr={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:ove.name},gZ=(t,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:r})=>({applyToStack:n=>{n.addRelativeTo(Q_e(t,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:r}),Mmr)}})});var PXn,Hot=w(()=>{to();dZ();PXn={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:U3.name}});var Vot=w(()=>{dZ();zot();Hot()});var Wot=w(()=>{});var Kot=w(()=>{Wot()});var Got=w(()=>{Hs()});var Jot=w(()=>{});var Yot=w(()=>{});function Rmr(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return{...e,[r]:Array.isArray(n)?[...n]:n}},{})}var E1,Zot=w(()=>{E1=class t{constructor(e){this.method=e.method||"GET",this.hostname=e.hostname||"localhost",this.port=e.port,this.query=e.query||{},this.headers=e.headers||{},this.body=e.body,this.protocol=e.protocol?e.protocol.slice(-1)!==":"?`${e.protocol}:`:e.protocol:"https:",this.path=e.path?e.path.charAt(0)!=="/"?`/${e.path}`:e.path:"/",this.username=e.username,this.password=e.password,this.fragment=e.fragment}static clone(e){let r=new t({...e,headers:{...e.headers}});return r.query&&(r.query=Rmr(r.query)),r}static isInstance(e){if(!e)return!1;let r=e;return"method"in r&&"protocol"in r&&"hostname"in r&&"path"in r&&typeof r.query=="object"&&typeof r.headers=="object"}clone(){return t.clone(this)}}});var Xot=w(()=>{});var Qot=w(()=>{});var eit=w(()=>{});var z3=w(()=>{Kot();Got();Jot();Yot();Zot();Xot();Qot();eit()});var jmr,Nmr,tit,ive=w(()=>{z3();Hs();jy();jmr=t=>e=>{throw e},Nmr=(t,e)=>{},tit=t=>(e,r)=>async n=>{if(!E1.isInstance(n.request))return e(n);let i=A_(r).selectedHttpAuthScheme;if(!i)throw new Error("No HttpAuthScheme was selected: unable to sign request");let{httpAuthOption:{signingProperties:a={}},identity:s,signer:u}=i,l=await e({...n,request:await u.sign(n.request,s,a)}).catch((u.errorHandler||jmr)(a));return(u.successHandler||Nmr)(l.response,a),l}});var Ny,I_,H3,yZ=w(()=>{(function(t){t.STANDARD="standard",t.ADAPTIVE="adaptive"})(Ny||(Ny={}));I_=3,H3=Ny.STANDARD});var rit,nit,oit,iit,ait=w(()=>{rit=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],nit=["TimeoutError","RequestTimeout","RequestTimeoutException"],oit=[500,502,503,504],iit=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"]});var Dmr,pk,bZ,sit,V3=w(()=>{ait();Dmr=t=>t.$metadata?.clockSkewCorrected,pk=t=>t.$metadata?.httpStatusCo
If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body`);return o.stream()};return Object.assign(t,{transformToByteArray:r,transformToString:async o=>{let i=await r();if(o==="base64")return jT(i);if(o==="hex")return fat(i);if(o===void 0||o==="utf8"||o==="utf-8")return PZ(i);if(typeof TextDecoder=="function")return new TextDecoder(o).decode(i);throw new Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(e)throw new Error(mat);if(e=!0,hat(t))return n(t);if(Cve(t))return t;throw new Error(`Cannot transform payload to web stream, got ${t}`)}})},hat=t=>typeof Blob=="function"&&t instanceof Blob});var bat=w(()=>{});var _at=w(()=>{});var Pve=w(()=>{wve();Kit();yat();bat();_at();Ove()});var DT,vat=w(()=>{Pve();DT=async(t=new Uint8Array,e)=>{if(t instanceof Uint8Array)return dO.mutate(t);if(!t)return dO.mutate(new Uint8Array);let r=e.streamCollector(t);return dO.mutate(await r)}});var Ot,Eve,wat=w(()=>{mve();Hs();Ot=class{constructor(){this.middlewareStack=yk()}static classBuilder(){return new Eve}resolveMiddlewareWithContext(e,r,n,{middlewareFn:o,clientName:i,commandName:a,inputFilterSensitiveLog:s,outputFilterSensitiveLog:u,smithyContext:l,additionalContext:c,CommandCtor:d}){for(let b of o.bind(this)(d,e,r,n))this.middlewareStack.use(b);let f=e.concat(this.middlewareStack),{logger:p}=r,m={logger:p,clientName:i,commandName:a,inputFilterSensitiveLog:s,outputFilterSensitiveLog:u,[dk]:{commandInstance:this,...l},...c},{requestHandler:h}=r;return f.resolve(b=>h.handle(b.request,n||{}),m)}},Eve=class{constructor(){this._init=()=>{},this._ep={},this._middlewareFn=()=>[],this._commandName="",this._clientName="",this._additionalContext={},this._smithyContext={},this._inputFilterSensitiveLog=e=>e,this._outputFilterSensitiveLog=e=>e,this._serializer=null,this._deserializer=null}init(e){this._init=e}ep(e){return this._ep=e,this}m(e){return this._middlewareFn=e,this}s(e,r,n={}){return this._smithyContext={service:e,operation:r,...n},this}c(e={}){return this._additionalContext=e,this}n(e,r){return this._clientName=e,this._commandName=r,this}f(e=n=>n,r=n=>n){return this._inputFilterSensitiveLog=e,this._outputFilterSensitiveLog=r,this}ser(e){return this._serializer=e,this}de(e){return this._deserializer=e,this}build(){let e=this,r;return r=class extends Ot{static getEndpointParameterInstructions(){return e._ep}constructor(...[n]){super(),this.serialize=e._serializer,this.deserialize=e._deserializer,this.input=n??{},e._init(this)}resolveMiddleware(n,o,i){return this.resolveMiddlewareWithContext(n,o,i,{CommandCtor:r,middlewareFn:e._middlewareFn,clientName:e._clientName,commandName:e._commandName,inputFilterSensitiveLog:e._inputFilterSensitiveLog,outputFilterSensitiveLog:e._outputFilterSensitiveLog,smithyContext:e._smithyContext,additionalContext:e._additionalContext})}}}}});var TZ,Sat=w(()=>{TZ="***SensitiveInformation***"});var AZ,xat=w(()=>{AZ=(t,e)=>{for(let r of Object.keys(t)){let n=t[r],o=async function(a,s,u){let l=new n(a);if(typeof s=="function")this.send(l,s);else if(typeof u=="function"){if(typeof s!="object")throw new Error(`Expected http options but got ${typeof s}`);this.send(l,s||{},u)}else return this.send(l,s)},i=(r[0].toLowerCase()+r.slice(1)).replace(/Command$/,"");e.prototype[i]=o}}});var j1,Umr,Cat,zmr,Oat,Pat,Eat,Tve,Hmr,vk,ln,Tat,Aat,Vmr,Y3,Z3,Ave,Iat,Mat,Rat,Ive=w(()=>{j1=t=>{if(t!=null){if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return String(e)!==String(t)&&Rat.warn(Mat(`Expected number but observed string: ${t}`)),e}if(typeof t=="number")return t;throw new TypeError(`Expected number, got ${typeof t}: ${t}`)}},Umr=Math.ceil(34028234663852886e22),Cat=t=>{let e=j1(t);if(e!==void 0&&!Number.isNaN(e)&&e!==1/0&&e!==-1/0&&Math.abs(e)>Umr)throw new TypeError(`Expected 32-bit float, got ${t}`);return e},zmr=t=>{if(t!=null){if(Number.isInteger(t)&&!Number.isNaN(t))return t;throw new TypeError(`Expected integer, got ${typeof t}: ${t}`)}},Oat=t=>Tve(t,32),Pat=t=>Tve(t,16),E
2025-07-05 20:48:33 +08:00
`).slice(0,5).filter(e=>!e.includes("stackTraceWarning")).join(`
2025-07-12 10:26:56 +08:00
`),Rat={warn:console.warn}});var Wmr,Kmr,jat,Gmr,Nat,vro,wro,Sro,IZ,Dat,xro,Jmr,Ymr,Zmr,N1,Xmr,Qmr,Mve,Lat=w(()=>{Ive();Wmr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Kmr=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),jat=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=Kmr.exec(t);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");let[r,n,o,i,a,s,u,l]=e,c=Ave(Mve(n)),d=N1(o,"month",1,12),f=N1(i,"day",1,31);return Dat(c,d,f,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l})},Gmr=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),Nat=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=Gmr.exec(t);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");let[r,n,o,i,a,s,u,l,c]=e,d=Ave(Mve(n)),f=N1(o,"month",1,12),p=N1(i,"day",1,31),m=Dat(d,f,p,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l});return c.toUpperCase()!="Z"&&m.setTime(m.getTime()-Qmr(c)),m},vro=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),wro=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),Sro=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/),IZ=t=>{if(t==null)return;let e;if(typeof t=="number")e=t;else if(typeof t=="string")e=Tat(t);else if(typeof t=="object"&&t.tag===1)e=t.value;else throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(e)||e===1/0||e===-1/0)throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(e*1e3))},Dat=(t,e,r,n)=>{let o=e-1;return Ymr(t,o,r),new Date(Date.UTC(t,o,r,N1(n.hours,"hour",0,23),N1(n.minutes,"minute",0,59),N1(n.seconds,"seconds",0,60),Xmr(n.fractionalMilliseconds)))},xro=50*365*24*60*60*1e3,Jmr=[31,28,31,30,31,30,31,31,30,31,30,31],Ymr=(t,e,r)=>{let n=Jmr[e];if(e===1&&Zmr(t)&&(n=29),r>n)throw new TypeError(`Invalid day for ${Wmr[e]} in ${t}: ${r}`)},Zmr=t=>t%4===0&&(t%100!==0||t%400===0),N1=(t,e,r,n)=>{let o=Iat(Mve(t));if(o<r||o>n)throw new TypeError(`${e} must be between ${r} and ${n}, inclusive`);return o},Xmr=t=>t==null?0:Aat("0."+t)*1e3,Qmr=t=>{let e=t[0],r=1;if(e=="+")r=1;else if(e=="-")r=-1;else throw new TypeError(`Offset direction, ${e}, must be "+" or "-"`);let n=Number(t.substring(1,3)),o=Number(t.substring(4,6));return r*(n*60+o)*60*1e3},Mve=t=>{let e=0;for(;e<t.length-1&&t.charAt(e)==="0";)e++;return e===0?t:t.slice(e)}});var wk,qa,Rve=w(()=>{wk=class t extends Error{constructor(e){super(e.message),Object.setPrototypeOf(this,t.prototype),this.name=e.name,this.$fault=e.$fault,this.$metadata=e.$metadata}},qa=(t,e={})=>{Object.entries(e).filter(([,n])=>n!==void 0).forEach(([n,o])=>{(t[n]==null||t[n]==="")&&(t[n]=o)});let r=t.message||t.Message||"UnknownError";return t.message=r,delete t.Message,t}});var ehr,MZ,thr,Fat=w(()=>{Rve();ehr=({output:t,parsedBody:e,exceptionCtor:r,errorCode:n})=>{let o=thr(t),i=o.httpStatusCode?o.httpStatusCode+"":void 0,a=new r({name:e?.code||e?.Code||n||i||"UnknownError",$fault:"client",$metadata:o});throw qa(a,e)},MZ=t=>({output:e,parsedBody:r,errorCode:n})=>{ehr({output:e,parsedBody:r,exceptionCtor:t,errorCode:n})},thr=t=>({httpStatusCode:t.statusCode,requestId:t.headers["x-amzn-requestid"]??t.headers["x-amzn-request-id"]??t.headers["x-amz-request-id"],extendedRequestId:t.headers["x-amz-id-2"],cfId:t.headers["x-amz-cf-id"]})});var RZ,kat=w(()=>{RZ=t=>{switch(t){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":retu
`);return this.signString(m,{signingDate:n,signingRegion:s,signingService:a})}async signMessage(e,{signingDate:r=new Date,signingRegion:n,signingService:o}){return this.signEvent({headers:this.headerFormatter.format(e.message.headers),payload:e.message.body},{signingDate:r,signingRegion:n,signingService:o,priorSignature:e.priorSignature}).then(a=>({message:e.message,signature:a}))}async signString(e,{signingDate:r=new Date,signingRegion:n,signingService:o}={}){let i=await this.credentialProvider();this.validateResolvedCredentials(i);let a=n??await this.regionProvider(),{shortDate:s}=JZ(r),u=new this.sha256(await this.getSigningKey(i,a,s,o));return u.update(kT(e)),Dy(await u.digest())}async signRequest(e,{signingDate:r=new Date,signableHeaders:n,unsignableHeaders:o,signingRegion:i,signingService:a}={}){let s=await this.credentialProvider();this.validateResolvedCredentials(s);let u=i??await this.regionProvider(),l=GZ(e),{longDate:c,shortDate:d}=JZ(r),f=VZ(d,u,a??this.service);l.headers[Jve]=c,s.sessionToken&&(l.headers[aut]=s.sessionToken);let p=await iH(l,this.sha256);!wut(oH,l.headers)&&this.applyChecksum&&(l.headers[oH]=p);let m=WZ(l,o,n),h=await this.getSignature(c,f,this.getSigningKey(s,u,d,a),this.createCanonicalRequest(l,m,p));return l.headers[Gve]=`${zZ} Credential=${s.accessKeyId}/${f}, SignedHeaders=${Out(m)}, Signature=${h}`,l}createCanonicalRequest(e,r,n){let o=Object.keys(r).sort();return`${e.method}
2025-07-05 20:48:33 +08:00
${this.getCanonicalPath(e)}
2025-07-12 10:26:56 +08:00
${ewe(e)}
2025-07-05 20:48:33 +08:00
${o.map(i=>`${i}:${r[i]}`).join(`
`)}
${o.join(";")}
2025-07-12 10:26:56 +08:00
${n}`}async createStringToSign(e,r,n){let o=new this.sha256;o.update(kT(n));let i=await o.digest();return`${zZ}
2025-07-05 20:48:33 +08:00
${e}
${r}
2025-07-12 10:26:56 +08:00
${Dy(i)}`}getCanonicalPath({path:e}){if(this.uriEscapePath){let r=[];for(let i of e.split("/"))i?.length!==0&&i!=="."&&(i===".."?r.pop():r.push(i));let n=`${e?.startsWith("/")?"/":""}${r.join("/")}${r.length>0&&e?.endsWith("/")?"/":""}`;return Yh(n).replace(/%2F/g,"/")}return e}async getSignature(e,r,n,o){let i=await this.createStringToSign(e,r,o),a=new this.sha256(await n);return a.update(kT(i)),Dy(await a.digest())}getSigningKey(e,r,n,o){return hut(this.sha256,e,n,r,o||this.service)}validateResolvedCredentials(e){if(typeof e!="object"||typeof e.accessKeyId!="string"||typeof e.secretAccessKey!="string")throw new Error("Resolved credential object is not valid")}},JZ=t=>{let e=xut(t).replace(/[\-:]/g,"");return{longDate:e,shortDate:e.slice(0,8)}},Out=t=>Object.keys(t).sort().join(";")});var Eut=w(()=>{Put();Qve();twe();rwe();iwe();awe();Xve()});var YZ,Tut=w(()=>{LT();Eut();YZ=t=>{let e;t.credentials&&(e=pst(t.credentials,fst,Fve)),e||(t.credentialDefaultProvider?e=Ck(t.credentialDefaultProvider(Object.assign({},t,{parentClientConfig:t}))):e=async()=>{throw new Error("`credentials` is missing")});let{signingEscapePath:r=!0,systemClockOffset:n=t.systemClockOffset||0,sha256:o}=t,i;return t.signer?i=Ck(t.signer):t.regionInfoProvider?i=()=>Ck(t.region)().then(async a=>[await t.regionInfoProvider(a,{useFipsEndpoint:await t.useFipsEndpoint(),useDualstackEndpoint:await t.useDualstackEndpoint()})||{},a]).then(([a,s])=>{let{signingRegion:u,signingService:l}=a;t.signingRegion=t.signingRegion||u||s,t.signingName=t.signingName||l||t.serviceId;let c={...t,credentials:e,region:t.signingRegion,service:t.signingName,sha256:o,uriEscapePath:r},d=t.signerConstructor||aH;return new d(c)}):i=async a=>{a=Object.assign({},{name:"sigv4",signingName:t.signingName||t.defaultSigningName,signingRegion:await Ck(t.region)(),properties:{}},a);let s=a.signingRegion,u=a.signingName;t.signingRegion=t.signingRegion||s,t.signingName=t.signingName||u||t.serviceId;let l={...t,credentials:e,region:t.signingRegion,service:t.signingName,sha256:o,uriEscapePath:r},c=t.signerConstructor||aH;return new c(l)},{...t,systemClockOffset:n,signingEscapePath:r,credentials:e,signer:i}}});var Aut=w(()=>{Gst();Jst();Tut()});var Iut=w(()=>{Aut()});var Mut=w(()=>{});var Rut=w(()=>{ar()});var ZZ,swe=w(()=>{ar();ZZ=(t,e)=>DT(t,e).then(r=>e.utf8Encoder(r))});var Is,jut,Nut,Dut=w(()=>{swe();Is=(t,e)=>ZZ(t,e).then(r=>{if(r.length)try{return JSON.parse(r)}catch(n){throw n?.name==="SyntaxError"&&Object.defineProperty(n,"$responseBodyText",{value:r}),n}return{}}),jut=async(t,e)=>{let r=await Is(t,e);return r.message=r.message??r.Message,r},Nut=(t,e)=>{let r=(i,a)=>Object.keys(i).find(s=>s.toLowerCase()===a.toLowerCase()),n=i=>{let a=i;return typeof a=="number"&&(a=a.toString()),a.indexOf(",")>=0&&(a=a.split(",")[0]),a.indexOf(":")>=0&&(a=a.split(":")[0]),a.indexOf("#")>=0&&(a=a.split("#")[1]),a},o=r(t.headers,"x-amzn-errortype");if(o!==void 0)return n(t.headers[o]);if(e.code!==void 0)return n(e.code);if(e.__type!==void 0)return n(e.__type)}});var XZ=v(fO=>{"use strict";var Lut=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",whr=Lut+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",Fut="["+Lut+"]["+whr+"]*",Shr=new RegExp("^"+Fut+"$"),xhr=function(t,e){let r=[],n=e.exec(t);for(;n;){let o=[];o.startIndex=e.lastIndex-n[0].length;let i=n.length;for(let a=0;a<i;a++)o.push(n[a]);r.push(o),n=e.exec(t)}return r},Chr=function(t){let e=Shr.exec(t);return!(e===null||typeof e>"u")};fO.isExist=function(t){return typeof t<"u"};fO.isEmptyObject=function(t){return Object.keys(t).length===0};fO.merge=function(t,e,r){if(e){let n=Object.keys(e),o=n.length;for(let i=0;i<o;i++)r==="strict"?t[n[i]]=[e[n[i]]]:t[n[i]]=e[n[i]]}};fO.getValue=function(t){return fO.isExist(t)?t:""};fO.isName=Chr;fO.getAllMatches=xhr;fO.nameRegexp=Fut});var lwe=v(Uut=>{"use strict";var uwe=XZ(),Ohr={allowBooleanAttributes:!1,unpairedTags:[]};Uut.validate=function(t,e){e=Object.assign({},Ohr,e);let r=[],n=!1,
`&&t[i]!=="\r";i++)u+=t[i];if(u=u.trim(),u[u.length-1]==="/"&&(u=u.substring(0,u.length-1),i--),!jhr(u)){let d;return u.trim().length===0?d="Invalid space after '<'.":d="Tag '"+u+"' is an invalid name.",Ms("InvalidTag",d,zf(t,i))}let l=Thr(t,i);if(l===!1)return Ms("InvalidAttr","Attributes for '"+u+"' have open quote.",zf(t,i));let c=l.value;if(i=l.index,c[c.length-1]==="/"){let d=i-c.length;c=c.substring(0,c.length-1);let f=qut(c,e);if(f===!0)n=!0;else return Ms(f.err.code,f.err.msg,zf(t,d+f.err.line))}else if(s)if(l.tagClosed){if(c.trim().length>0)return Ms("InvalidTag","Closing tag '"+u+"' can't have attributes or invalid starting.",zf(t,a));if(r.length===0)return Ms("InvalidTag","Closing tag '"+u+"' has not been opened.",zf(t,a));{let d=r.pop();if(u!==d.tagName){let f=zf(t,d.tagStartPos);return Ms("InvalidTag","Expected closing tag '"+d.tagName+"' (opened in line "+f.line+", col "+f.col+") instead of closing tag '"+u+"'.",zf(t,a))}r.length==0&&(o=!0)}}else return Ms("InvalidTag","Closing tag '"+u+"' doesn't have proper closing.",zf(t,i));else{let d=qut(c,e);if(d!==!0)return Ms(d.err.code,d.err.msg,zf(t,i-c.length+d.err.line));if(o===!0)return Ms("InvalidXml","Multiple possible root nodes found.",zf(t,i));e.unpairedTags.indexOf(u)!==-1||r.push({tagName:u,tagStartPos:a}),n=!0}for(i++;i<t.length;i++)if(t[i]==="<")if(t[i+1]==="!"){i++,i=But(t,i);continue}else if(t[i+1]==="?"){if(i=$ut(t,++i),i.err)return i}else break;else if(t[i]==="&"){let d=Mhr(t,i);if(d==-1)return Ms("InvalidChar","char '&' is not expected.",zf(t,i));i=d}else if(o===!0&&!kut(t[i]))return Ms("InvalidXml","Extra text at the end",zf(t,i));t[i]==="<"&&i--}}else{if(kut(t[i]))continue;return Ms("InvalidChar","char '"+t[i]+"' is not expected.",zf(t,i))}if(n){if(r.length==1)return Ms("InvalidTag","Unclosed tag '"+r[0].tagName+"'.",zf(t,r[0].tagStartPos));if(r.length>0)return Ms("InvalidXml","Invalid '"+JSON.stringify(r.map(i=>i.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return Ms("InvalidXml","Start tag expected.",1);return!0};function kut(t){return t===" "||t===" "||t===`
`||t==="\r"}function $ut(t,e){let r=e;for(;e<t.length;e++)if(t[e]=="?"||t[e]==" "){let n=t.substr(r,e-r);if(e>5&&n==="xml")return Ms("InvalidXml","XML declaration allowed only at the start of the document.",zf(t,e));if(t[e]=="?"&&t[e+1]==">"){e++;break}else continue}return e}function But(t,e){if(t.length>e+5&&t[e+1]==="-"&&t[e+2]==="-"){for(e+=3;e<t.length;e++)if(t[e]==="-"&&t[e+1]==="-"&&t[e+2]===">"){e+=2;break}}else if(t.length>e+8&&t[e+1]==="D"&&t[e+2]==="O"&&t[e+3]==="C"&&t[e+4]==="T"&&t[e+5]==="Y"&&t[e+6]==="P"&&t[e+7]==="E"){let r=1;for(e+=8;e<t.length;e++)if(t[e]==="<")r++;else if(t[e]===">"&&(r--,r===0))break}else if(t.length>e+9&&t[e+1]==="["&&t[e+2]==="C"&&t[e+3]==="D"&&t[e+4]==="A"&&t[e+5]==="T"&&t[e+6]==="A"&&t[e+7]==="["){for(e+=8;e<t.length;e++)if(t[e]==="]"&&t[e+1]==="]"&&t[e+2]===">"){e+=2;break}}return e}var Phr='"',Ehr="'";function Thr(t,e){let r="",n="",o=!1;for(;e<t.length;e++){if(t[e]===Phr||t[e]===Ehr)n===""?n=t[e]:n!==t[e]||(n="");else if(t[e]===">"&&n===""){o=!0;break}r+=t[e]}return n!==""?!1:{value:r,index:e,tagClosed:o}}var Ahr=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function qut(t,e){let r=uwe.getAllMatches(t,Ahr),n={};for(let o=0;o<r.length;o++){if(r[o][1].length===0)return Ms("InvalidAttr","Attribute '"+r[o][2]+"' has no space in starting.",sH(r[o]));if(r[o][3]!==void 0&&r[o][4]===void 0)return Ms("InvalidAttr","Attribute '"+r[o][2]+"' is without value.",sH(r[o]));if(r[o][3]===void 0&&!e.allowBooleanAttributes)return Ms("InvalidAttr","boolean attribute '"+r[o][2]+"' is not allowed.",sH(r[o]));let i=r[o][2];if(!Rhr(i))return Ms("InvalidAttr","Attribute '"+i+"' is an invalid name.",sH(r[o]));if(!n.hasOwnProperty(i))n[i]=1;else return Ms("InvalidAttr","Attribute '"+i+"' is repeated.",sH(r[o]))}return!0}function Ihr(t,e){let r=/\d/;for(t[e]==="x"&&(e++,r=/[\da-fA-F]/);e<t.length;e++){if(t[e]===";")return e;if(!t[e].match(r))break}return-1}function Mhr(t,e){if(e++,t[e]===";")return-1;if(t[e]==="#")return e++,Ihr(t,e);let r=0;for(;e<t.length;e++,r++)if(!(t[e].match(/\w/)&&r<20)){if(t[e]===";")break;return-1}return e}function Ms(t,e,r){return{err:{code:t,msg:e,line:r.line||r,col:r.col}}}function Rhr(t){return uwe.isName(t)}function jhr(t){return uwe.isName(t)}function zf(t,e){let r=t.substring(0,e).split(/\r?\n/);return{line:r.length,col:r[r.length-1].length+1}}function sH(t){return t.startIndex+t[1].length}});var Hut=v(cwe=>{var zut={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,r){return t}},Nhr=function(t){return Object.assign({},zut,t)};cwe.buildOptions=Nhr;cwe.defaultOptions=zut});var Wut=v((Kao,Vut)=>{"use strict";var dwe=class{constructor(e){this.tagname=e,this.child=[],this[":@"]={}}add(e,r){e==="__proto__"&&(e="#__proto__"),this.child.push({[e]:r})}addChild(e){e.tagname==="__proto__"&&(e.tagname="#__proto__"),e[":@"]&&Object.keys(e[":@"]).length>0?this.child.push({[e.tagname]:e.child,":@":e[":@"]}):this.child.push({[e.tagname]:e.child})}};Vut.exports=dwe});var Gut=v((Gao,Kut)=>{var Dhr=XZ();function Lhr(t,e){let r={};if(t[e+3]==="O"&&t[e+4]==="C"&&t[e+5]==="T"&&t[e+6]==="Y"&&t[e+7]==="P"&&t[e+8]==="E"){e=e+9;let n=1,o=!1,i=!1,a="";for(;e<t.length;e++)if(t[e]==="<"&&!i){if(o&&$hr(t,e))e+=7,[entityName,val,e]=Fhr(t,e+1),val.indexOf("&")===-1&&(r[zhr(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(o&&Bhr(t,e))e+=8;else if(o&&qhr(t,e))e+=8;else if(o&&Uhr(t,e))e+=9;else if(khr)i=!0;else throw new Error("Invalid DOCTYPE");n++,a=""}else if(t[e]===">"){if(i?t[e-1]==="-"&&t[e-2]==="-"&&(i=!1,n--):n--,n===0)brea
`);let e=new uH("!xml"),r=e,n="",o="";for(let i=0;i<t.length;i++)if(t[i]==="<")if(t[i+1]==="/"){let s=F1(t,">",i,"Closing Tag is not closed."),u=t.substring(i+2,s).trim();if(this.options.removeNSPrefix){let d=u.indexOf(":");d!==-1&&(u=u.substr(d+1))}this.options.transformTagName&&(u=this.options.transformTagName(u)),r&&(n=this.saveTextToParentTag(n,r,o));let l=o.substring(o.lastIndexOf(".")+1);if(u&&this.options.unpairedTags.indexOf(u)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${u}>`);let c=0;l&&this.options.unpairedTags.indexOf(l)!==-1?(c=o.lastIndexOf(".",o.lastIndexOf(".")-1),this.tagsNodeStack.pop()):c=o.lastIndexOf("."),o=o.substring(0,c),r=this.tagsNodeStack.pop(),n="",i=s}else if(t[i+1]==="?"){let s=pwe(t,i,!1,"?>");if(!s)throw new Error("Pi Tag is not closed.");if(n=this.saveTextToParentTag(n,r,o),!(this.options.ignoreDeclaration&&s.tagName==="?xml"||this.options.ignorePiTags)){let u=new uH(s.tagName);u.add(this.options.textNodeName,""),s.tagName!==s.tagExp&&s.attrExpPresent&&(u[":@"]=this.buildAttributesMap(s.tagExp,o,s.tagName)),this.addChild(r,u,o)}i=s.closeIndex+1}else if(t.substr(i+1,3)==="!--"){let s=F1(t,"-->",i+4,"Comment is not closed.");if(this.options.commentPropName){let u=t.substring(i+4,s-2);n=this.saveTextToParentTag(n,r,o),r.add(this.options.commentPropName,[{[this.options.textNodeName]:u}])}i=s}else if(t.substr(i+1,2)==="!D"){let s=Jhr(t,i);this.docTypeEntities=s.entities,i=s.i}else if(t.substr(i+1,2)==="!["){let s=F1(t,"]]>",i,"CDATA is not closed.")-2,u=t.substring(i+9,s);n=this.saveTextToParentTag(n,r,o);let l=this.parseTextData(u,r.tagname,o,!0,!1,!0,!0);l==null&&(l=""),this.options.cdataPropName?r.add(this.options.cdataPropName,[{[this.options.textNodeName]:u}]):r.add(this.options.textNodeName,l),i=s+2}else{let s=pwe(t,i,this.options.removeNSPrefix),u=s.tagName,l=s.rawTagName,c=s.tagExp,d=s.attrExpPresent,f=s.closeIndex;this.options.transformTagName&&(u=this.options.transformTagName(u)),r&&n&&r.tagname!=="!xml"&&(n=this.saveTextToParentTag(n,r,o,!1));let p=r;if(p&&this.options.unpairedTags.indexOf(p.tagname)!==-1&&(r=this.tagsNodeStack.pop(),o=o.substring(0,o.lastIndexOf("."))),u!==e.tagname&&(o+=o?"."+u:u),this.isItStopNode(this.options.stopNodes,o,u)){let m="";if(c.length>0&&c.lastIndexOf("/")===c.length-1)u[u.length-1]==="/"?(u=u.substr(0,u.length-1),o=o.substr(0,o.length-1),c=u):c=c.substr(0,c.length-1),i=s.closeIndex;else if(this.options.unpairedTags.indexOf(u)!==-1)i=s.closeIndex;else{let b=this.readStopNodeData(t,l,f+1);if(!b)throw new Error(`Unexpected end of ${l}`);i=b.i,m=b.tagContent}let h=new uH(u);u!==c&&d&&(h[":@"]=this.buildAttributesMap(c,o,u)),m&&(m=this.parseTextData(m,u,o,!0,d,!0,!0)),o=o.substr(0,o.lastIndexOf(".")),h.add(this.options.textNodeName,m),this.addChild(r,h,o)}else{if(c.length>0&&c.lastIndexOf("/")===c.length-1){u[u.length-1]==="/"?(u=u.substr(0,u.length-1),o=o.substr(0,o.length-1),c=u):c=c.substr(0,c.length-1),this.options.transformTagName&&(u=this.options.transformTagName(u));let m=new uH(u);u!==c&&d&&(m[":@"]=this.buildAttributesMap(c,o,u)),this.addChild(r,m,o),o=o.substr(0,o.lastIndexOf("."))}else{let m=new uH(u);this.tagsNodeStack.push(r),u!==c&&d&&(m[":@"]=this.buildAttributesMap(c,o,u)),this.addChild(r,m,o),r=m}n="",i=f}}else n+=t[i];return e.child};function ngr(t,e,r){let n=this.options.updateTag(e.tagname,r,e[":@"]);n===!1||(typeof n=="string"&&(e.tagname=n),t.addChild(e))}var ogr=function(t){if(this.options.processEntities){for(let e in this.docTypeEntities){let r=this.docTypeEntities[e];t=t.replace(r.regx,r.val)}for(let e in this.lastEntities){let r=this.lastEntities[e];t=t.replace(r.regex,r.val)}if(this.options.htmlEntities)for(let e in this.htmlEntities){let r=this.htmlEntities[e];t=t.replace(r.regex,r.val)}t=t.replace(this.ampEntity.regex,this.ampEntity.val)}return t};function igr(t,e,r,n){return t&&(n===void 0&&(n=Object.keys(e.child).length===0),t=this.parseTextData(t,e.tagname,r,!1,e[":@"]?Object.keys(e[":@"]).length!==0:!1,n),t!==void 0&&t!==""&&e.add(this.options.textNodeName,t),t=""),t}function agr(t,e,r){let n="*
`;function bgr(t,e){let r="";return e.format&&e.indentBy.length>0&&(r=ygr),alt(t,e,"",r)}function alt(t,e,r,n){let o="",i=!1;for(let a=0;a<t.length;a++){let s=t[a],u=_gr(s);if(u===void 0)continue;let l="";if(r.length===0?l=u:l=`${r}.${u}`,u===e.textNodeName){let m=s[u];vgr(l,e)||(m=e.tagValueProcessor(u,m),m=slt(m,e)),i&&(o+=n),o+=m,i=!1;continue}else if(u===e.cdataPropName){i&&(o+=n),o+=`<![CDATA[${s[u][0][e.textNodeName]}]]>`,i=!1;continue}else if(u===e.commentPropName){o+=n+`<!--${s[u][0][e.textNodeName]}-->`,i=!0;continue}else if(u[0]==="?"){let m=ilt(s[":@"],e),h=u==="?xml"?"":n,b=s[u][0][e.textNodeName];b=b.length!==0?" "+b:"",o+=h+`<${u}${b}${m}?>`,i=!0;continue}let c=n;c!==""&&(c+=e.indentBy);let d=ilt(s[":@"],e),f=n+`<${u}${d}`,p=alt(s[u],e,l,c);e.unpairedTags.indexOf(u)!==-1?e.suppressUnpairedNode?o+=f+">":o+=f+"/>":(!p||p.length===0)&&e.suppressEmptyNode?o+=f+"/>":p&&p.endsWith(">")?o+=f+`>${p}${n}</${u}>`:(o+=f+">",p&&n!==""&&(p.includes("/>")||p.includes("</"))?o+=n+e.indentBy+p+n:o+=p,o+=`</${u}>`),i=!0}return o}function _gr(t){let e=Object.keys(t);for(let r=0;r<e.length;r++){let n=e[r];if(t.hasOwnProperty(n)&&n!==":@")return n}}function ilt(t,e){let r="";if(t&&!e.ignoreAttributes)for(let n in t){if(!t.hasOwnProperty(n))continue;let o=e.attributeValueProcessor(n,t[n]);o=slt(o,e),o===!0&&e.suppressBooleanAttributes?r+=` ${n.substr(e.attributeNamePrefix.length)}`:r+=` ${n.substr(e.attributeNamePrefix.length)}="${o}"`}return r}function vgr(t,e){t=t.substr(0,t.length-e.textNodeName.length-1);let r=t.substr(t.lastIndexOf(".")+1);for(let n in e.stopNodes)if(e.stopNodes[n]===t||e.stopNodes[n]==="*."+r)return!0;return!1}function slt(t,e){if(t&&t.length>0&&e.processEntities)for(let r=0;r<e.entities.length;r++){let n=e.entities[r];t=t.replace(n.regex,n.val)}return t}ult.exports=bgr});var dlt=v((eso,clt)=>{"use strict";var wgr=llt(),Sgr={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function $T(t){this.options=Object.assign({},Sgr,t),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=Ogr),this.processTextOrObjNode=xgr,this.options.format?(this.indentate=Cgr,this.tagEndChar=`>
2025-07-05 20:48:33 +08:00
`,this.newLine=`
2025-07-12 10:26:56 +08:00
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}$T.prototype.build=function(t){return this.options.preserveOrder?wgr(t,this.options):(Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t}),this.j2x(t,0).val)};$T.prototype.j2x=function(t,e){let r="",n="";for(let o in t)if(Object.prototype.hasOwnProperty.call(t,o))if(typeof t[o]>"u")this.isAttribute(o)&&(n+="");else if(t[o]===null)this.isAttribute(o)?n+="":o[0]==="?"?n+=this.indentate(e)+"<"+o+"?"+this.tagEndChar:n+=this.indentate(e)+"<"+o+"/"+this.tagEndChar;else if(t[o]instanceof Date)n+=this.buildTextValNode(t[o],o,"",e);else if(typeof t[o]!="object"){let i=this.isAttribute(o);if(i)r+=this.buildAttrPairStr(i,""+t[o]);else if(o===this.options.textNodeName){let a=this.options.tagValueProcessor(o,""+t[o]);n+=this.replaceEntitiesValue(a)}else n+=this.buildTextValNode(t[o],o,"",e)}else if(Array.isArray(t[o])){let i=t[o].length,a="",s="";for(let u=0;u<i;u++){let l=t[o][u];if(!(typeof l>"u"))if(l===null)o[0]==="?"?n+=this.indentate(e)+"<"+o+"?"+this.tagEndChar:n+=this.indentate(e)+"<"+o+"/"+this.tagEndChar;else if(typeof l=="object")if(this.options.oneListGroup){let c=this.j2x(l,e+1);a+=c.val,this.options.attributesGroupName&&l.hasOwnProperty(this.options.attributesGroupName)&&(s+=c.attrStr)}else a+=this.processTextOrObjNode(l,o,e);else if(this.options.oneListGroup){let c=this.options.tagValueProcessor(o,l);c=this.replaceEntitiesValue(c),a+=c}else a+=this.buildTextValNode(l,o,"",e)}this.options.oneListGroup&&(a=this.buildObjectNode(a,o,s,e)),n+=a}else if(this.options.attributesGroupName&&o===this.options.attributesGroupName){let i=Object.keys(t[o]),a=i.length;for(let s=0;s<a;s++)r+=this.buildAttrPairStr(i[s],""+t[o][i[s]])}else n+=this.processTextOrObjNode(t[o],o,e);return{attrStr:r,val:n}};$T.prototype.buildAttrPairStr=function(t,e){return e=this.options.attributeValueProcessor(t,""+e),e=this.replaceEntitiesValue(e),this.options.suppressBooleanAttributes&&e==="true"?" "+t:" "+t+'="'+e+'"'};function xgr(t,e,r){let n=this.j2x(t,r+1);return t[this.options.textNodeName]!==void 0&&Object.keys(t).length===1?this.buildTextValNode(t[this.options.textNodeName],e,n.attrStr,r):this.buildObjectNode(n.val,e,n.attrStr,r)}$T.prototype.buildObjectNode=function(t,e,r,n){if(t==="")return e[0]==="?"?this.indentate(n)+"<"+e+r+"?"+this.tagEndChar:this.indentate(n)+"<"+e+r+this.closeTag(e)+this.tagEndChar;{let o="</"+e+this.tagEndChar,i="";return e[0]==="?"&&(i="?",o=""),(r||r==="")&&t.indexOf("<")===-1?this.indentate(n)+"<"+e+r+i+">"+t+o:this.options.commentPropName!==!1&&e===this.options.commentPropName&&i.length===0?this.indentate(n)+`<!--${t}-->`+this.newLine:this.indentate(n)+"<"+e+r+i+this.tagEndChar+t+this.indentate(n)+o}};$T.prototype.closeTag=function(t){let e="";return this.options.unpairedTags.indexOf(t)!==-1?this.options.suppressUnpairedNode||(e="/"):this.options.suppressEmptyNode?e="/":e=`></${t}`,e};$T.prototype.buildTextValNode=function(t,e,r,n){if(this.options.cdataPropName!==!1&&e===this.options.cdataPropName)return this.indentate(n)+`<![CDATA[${t}]]>`+this.newLine;if(this.options.commentPropName!==!1&&e===this.options.commentPropName)return this.indentate(n)+`<!--${t}-->`+this.newLine;if(e[0]==="?")return this.indentate(n)+"<"+e+r+"?"+this.tagEndChar;{let o=this.options.tagValueProcessor(e,t);return o=this.replaceEntitiesValue(o),o===""?this.indentate(n)+"<"+e+r+this.closeTag(e)+this.tagEndChar:this.indentate(n)+"<"+e+r+">"+o+"</"+e+this.tagEndChar}};$T.prototype.replaceEntitiesValue=function(t){if(t&&t.length>0&&this.options.processEntities)for(let e=0;e<this.options.entities.length;e++){let r=this.options.entities[e];t=t.replace(r.regex,r.val)}return t};function Cgr(t){return this.options.indentBy.repeat(t)}function Ogr(t){return t.startsWith(this.options.attributeNamePrefix)&&t!==this.options.textNodeName?t.substr(this.attrPrefixLen):!1}clt.exports=$T});var plt=v((tso,flt)=>{"use strict";var Pgr=lwe(),Egr=olt(),Tgr=dlt();flt.exports={XMLParser:Egr,XMLValidator:Pgr,XMLBuilder:Tgr}});v
2025-07-05 20:48:33 +08:00
`)?"":void 0});n.addEntity("#xD","\r"),n.addEntity("#10",`
2025-07-12 10:26:56 +08:00
`);let o;try{o=n.parse(r,!0)}catch(u){throw u&&typeof u=="object"&&Object.defineProperty(u,"$responseBodyText",{value:r}),u}let i="#text",a=Object.keys(o)[0],s=o[a];return s[i]&&(s[a]=s[i],delete s[i]),Nve(s)}return{}}),hlt=async(t,e)=>{let r=await R_(t,e);return r.Error&&(r.Error.message=r.Error.message??r.Error.Message),r}});var ylt=w(()=>{Mut();Rut();Dut();glt()});var k1=w(()=>{Rst();Iut();ylt()});function Agr(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"cognito-identity",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function QZ(t){return{schemeId:"smithy.api#noAuth"}}var blt,_lt,vlt,gwe=w(()=>{k1();jy();blt=async(t,e,r)=>({operation:A_(e).operation,region:await zd(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});_lt=t=>{let e=[];switch(t.operation){case"GetCredentialsForIdentity":{e.push(QZ(t));break}case"GetId":{e.push(QZ(t));break}case"GetOpenIdToken":{e.push(QZ(t));break}case"UnlinkIdentity":{e.push(QZ(t));break}default:e.push(Agr(t))}return e},vlt=t=>({...YZ(t)})});var wlt,Cr,ua=w(()=>{wlt=t=>({...t,useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"cognito-identity"}),Cr={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}});var xlt,Slt=w(()=>{xlt={name:"@aws-sdk/client-cognito-identity",description:"AWS SDK for JavaScript Cognito Identity Client for Node.js, Browser and React Native",version:"3.645.0",scripts:{build:"concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'","build:cjs":"node ../../scripts/compilation/inline client-cognito-identity","build:es":"tsc -p tsconfig.es.json","build:include:deps":"lerna run --scope $npm_package_name --include-dependencies build","build:types":"tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4",clean:"rimraf ./dist-* && rimraf *.tsbuildinfo","extract:docs":"api-extractor run --local","generate:client":"node ../../scripts/generate-clients/single-service --solo cognito-identity","test:e2e":"ts-mocha test/**/*.ispec.ts && karma start karma.conf.js"},main:"./dist-cjs/index.js",types:"./dist-types/index.d.ts",module:"./dist-es/index.js",sideEffects:!1,dependencies:{"@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/client-sso-oidc":"3.645.0","@aws-sdk/client-sts":"3.645.0","@aws-sdk/core":"3.635.0","@aws-sdk/credential-provider-node":"3.645.0","@aws-sdk/middleware-host-header":"3.620.0","@aws-sdk/middleware-logger":"3.609.0","@aws-sdk/middleware-recursion-detection":"3.620.0","@aws-sdk/middleware-user-agent":"3.645.0","@aws-sdk/region-config-resolver":"3.614.0","@aws-sdk/types":"3.609.0","@aws-sdk/util-endpoints":"3.645.0","@aws-sdk/util-user-agent-browser":"3.609.0","@aws-sdk/util-user-agent-node":"3.614.0","@smithy/config-resolver":"^3.0.5","@smithy/core":"^2.4.0","@smithy/fetch-http-handler":"^3.2.4","@smithy/hash-node":"^3.0.3","@smithy/invalid-dependency":"^3.0.3","@smithy/middleware-content-length":"^3.0.5","@smithy/middleware-endpoint":"^3.1.0","@smithy/middleware-retry":"^3.0.15","@smithy/middleware-serde":"^3.0.3","@smithy/middleware-stack":"^3.0.3","@smithy/node-config-provider":"^3.1.4","@smithy/node-http-handler":"^3.1.4","@smithy/protocol-http":"^4.1.0","@smithy/smithy-client":"^3.2.0","@smithy/types":"^3.3.0","@smithy/url-parser":"^3.0.3","@smithy/util-base64":"^3.0.0","@smithy/util-body-length-browser":"^3.0.0","@smithy/util-body-length-node":"^3.0.0","@smithy/util-defaults-mode-browser":"^3.0.15","@smithy/util-defaults-mode-node":"^3.0.15","@smithy/util-endpoints":"^2.0.5","@smithy/util-middleware":"^3.0.3","@smithy/util-retry":"^3.0.3","@smithy/util-utf8":"^3.0.0",tslib:"^2.6.2"},devDependencies:{"@aws-sdk/client-iam":"3.645.0","@tsconfig/node16":"16.1.3","@types/chai":"^4.2.11","@types/mocha":"^8.0.4","@types/node":"^16.18.96",concurrently:"7.0.0","downlevel-d
2025-07-05 20:48:33 +08:00
- loopback CIDR 127.0.0.0/8 or [::1/128]
- ECS container host 169.254.170.2
2025-07-12 10:26:56 +08:00
- EKS container host 169.254.170.23 or [fd00:ec2::23]`,{logger:e})}}});var Udt=w(()=>{});var zdt=w(()=>{Udt()});var Hdt=w(()=>{Hs()});var Vdt=w(()=>{});var Wdt=w(()=>{});function pyr(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return{...e,[r]:Array.isArray(n)?[...n]:n}},{})}var VX,Kdt=w(()=>{VX=class t{constructor(e){this.method=e.method||"GET",this.hostname=e.hostname||"localhost",this.port=e.port,this.query=e.query||{},this.headers=e.headers||{},this.body=e.body,this.protocol=e.protocol?e.protocol.slice(-1)!==":"?`${e.protocol}:`:e.protocol:"https:",this.path=e.path?e.path.charAt(0)!=="/"?`/${e.path}`:e.path:"/",this.username=e.username,this.password=e.password,this.fragment=e.fragment}static clone(e){let r=new t({...e,headers:{...e.headers}});return r.query&&(r.query=pyr(r.query)),r}static isInstance(e){if(!e)return!1;let r=e;return"method"in r&&"protocol"in r&&"hostname"in r&&"path"in r&&typeof r.query=="object"&&typeof r.headers=="object"}clone(){return t.clone(this)}}});var Gdt=w(()=>{});var Jdt=w(()=>{});var Ydt=w(()=>{});var Zdt=w(()=>{zdt();Hdt();Vdt();Wdt();Kdt();Gdt();Jdt();Ydt()});function Xdt(t){return new VX({protocol:t.protocol,hostname:t.hostname,port:Number(t.port),path:t.pathname,query:Array.from(t.searchParams.entries()).reduce((e,[r,n])=>(e[r]=n,e),{}),fragment:t.hash})}async function Qdt(t,e){let n=await gat(t.body).transformToString();if(t.statusCode===200){let o=JSON.parse(n);if(typeof o.AccessKeyId!="string"||typeof o.SecretAccessKey!="string"||typeof o.Token!="string"||typeof o.Expiration!="string")throw new Tl("HTTP credential provider response not of the required format, an object matching: { AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }",{logger:e});return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,sessionToken:o.Token,expiration:jat(o.Expiration)}}if(t.statusCode>=400&&t.statusCode<500){let o={};try{o=JSON.parse(n)}catch{}throw Object.assign(new Tl(`Server responded with status: ${t.statusCode}`,{logger:e}),{Code:o.Code,Message:o.Message})}throw new Tl(`Server responded with status: ${t.statusCode}`,{logger:e})}var eft=w(()=>{sO();Zdt();ar();Pve()});var tft,rft=w(()=>{tft=(t,e,r)=>async()=>{for(let n=0;n<e;++n)try{return await t()}catch{await new Promise(i=>setTimeout(i,r))}return await t()}});var d0e,nft=w(()=>{J3();sO();qdt();eft();rft();d0e=(t={})=>{t.logger?.debug("@aws-sdk/credential-provider-http - fromHttp");let e,r=t.credentialsFullUri;if(r)e=r;else throw new Tl("No HTTP credential provider host provided.",{logger:t.logger});let n=new URL(e);Bdt(n,t.logger);let o=new NT;return tft(async()=>{let i=Xdt(n);t.authorizationToken&&(i.headers.Authorization=t.authorizationToken);let a=await o.handle(i);return Qdt(a.response)},t.maxRetries??3,t.timeout??1e3)}});var oft=w(()=>{nft()});function myr(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sts",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function ift(t){return{schemeId:"smithy.api#noAuth"}}var aft,sft,hyr,uft,f0e=w(()=>{k1();jy();fH();aft=async(t,e,r)=>({operation:A_(e).operation,region:await zd(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});sft=t=>{let e=[];switch(t.operation){case"AssumeRoleWithSAML":{e.push(ift(t));break}case"AssumeRoleWithWebIdentity":{e.push(ift(t));break}default:e.push(myr(t))}return e},hyr=t=>({...t,stsClientCtor:Zh}),uft=t=>{let e=hyr(t);return{...YZ(e)}}});var lft,Vd,L_=w(()=>{lft=t=>({...t,useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,useGlobalEndpoint:t.useGlobalEndpoint??!1,defaultSigningName:"sts"}),Vd={UseGlobalEndpoint:{type:"builtInParams",name:"useGlobalEndpoint"},UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}});var dft,cft=w(()=>{dft={name:"@aws-sdk/client-sts",description:"AWS SDK for JavaScript Sts Client for Node.js, Browse
`);return this.signString(m,{signingDate:n,signingRegion:s,signingService:a})}async signMessage(e,{signingDate:r=new Date,signingRegion:n,signingService:o}){return this.signEvent({headers:this.headerMarshaller.format(e.message.headers),payload:e.message.body},{signingDate:r,signingRegion:n,signingService:o,priorSignature:e.priorSignature}).then(a=>({message:e.message,signature:a}))}async signString(e,{signingDate:r=new Date,signingRegion:n,signingService:o}={}){let i=await this.credentialProvider();this.validateResolvedCredentials(i);let a=n??await this.regionProvider(),{shortDate:s}=zQ(r),u=new this.sha256(await this.getSigningKey(i,a,s,o));return u.update((0,LH.toUint8Array)(e)),(0,qQ.toHex)(await u.digest())}async signRequest(e,{signingDate:r=new Date,signableHeaders:n,unsignableHeaders:o,signingRegion:i,signingService:a}={}){let s=await this.credentialProvider();this.validateResolvedCredentials(s);let u=i??await this.regionProvider(),l=(0,lyt.prepareRequest)(e),{longDate:c,shortDate:d}=zQ(r),f=(0,UQ.createScope)(d,u,a??this.service);l.headers[Bc.AMZ_DATE_HEADER]=c,s.sessionToken&&(l.headers[Bc.TOKEN_HEADER]=s.sessionToken);let p=await(0,ZSe.getPayloadHash)(l,this.sha256);!(0,jvr.hasHeader)(Bc.SHA256_HEADER,l.headers)&&this.applyChecksum&&(l.headers[Bc.SHA256_HEADER]=p);let m=(0,uyt.getCanonicalHeaders)(l,o,n),h=await this.getSignature(c,f,this.getSigningKey(s,u,d,a),this.createCanonicalRequest(l,m,p));return l.headers[Bc.AUTH_HEADER]=`${Bc.ALGORITHM_IDENTIFIER} Credential=${s.accessKeyId}/${f}, SignedHeaders=${cyt(m)}, Signature=${h}`,l}createCanonicalRequest(e,r,n){let o=Object.keys(r).sort();return`${e.method}
2025-07-05 20:48:33 +08:00
${this.getCanonicalPath(e)}
2025-07-12 10:26:56 +08:00
${(0,Rvr.getCanonicalQuery)(e)}
2025-07-05 20:48:33 +08:00
${o.map(i=>`${i}:${r[i]}`).join(`
`)}
${o.join(";")}
2025-07-12 10:26:56 +08:00
${n}`}async createStringToSign(e,r,n){let o=new this.sha256;o.update((0,LH.toUint8Array)(n));let i=await o.digest();return`${Bc.ALGORITHM_IDENTIFIER}
2025-07-05 20:48:33 +08:00
${e}
${r}
2025-07-12 10:26:56 +08:00
${(0,qQ.toHex)(i)}`}getCanonicalPath({path:e}){if(this.uriEscapePath){let r=[];for(let i of e.split("/"))i?.length!==0&&i!=="."&&(i===".."?r.pop():r.push(i));let n=`${e?.startsWith("/")?"/":""}${r.join("/")}${r.length>0&&e?.endsWith("/")?"/":""}`;return encodeURIComponent(n).replace(/%2F/g,"/")}return e}async getSignature(e,r,n,o){let i=await this.createStringToSign(e,r,o),a=new this.sha256(await n);return a.update((0,LH.toUint8Array)(i)),(0,qQ.toHex)(await a.digest())}getSigningKey(e,r,n,o){return(0,UQ.getSigningKey)(this.sha256,e,n,r,o||this.service)}validateResolvedCredentials(e){if(typeof e!="object"||typeof e.accessKeyId!="string"||typeof e.secretAccessKey!="string")throw new Error("Resolved credential object is not valid")}};HQ.SignatureV4=XSe;var zQ=t=>{let e=(0,Dvr.iso8601)(t).replace(/[\-:]/g,"");return{longDate:e,shortDate:e.slice(0,8)}},cyt=t=>Object.keys(t).sort().join(";")});var pyt=v(jp=>{"use strict";Object.defineProperty(jp,"__esModule",{value:!0});jp.prepareRequest=jp.moveHeadersToQuery=jp.getPayloadHash=jp.getCanonicalQuery=jp.getCanonicalHeaders=void 0;var fyt=(V1(),zl(H1));fyt.__exportStar(dyt(),jp);var Lvr=HSe();Object.defineProperty(jp,"getCanonicalHeaders",{enumerable:!0,get:function(){return Lvr.getCanonicalHeaders}});var Fvr=WSe();Object.defineProperty(jp,"getCanonicalQuery",{enumerable:!0,get:function(){return Fvr.getCanonicalQuery}});var kvr=KSe();Object.defineProperty(jp,"getPayloadHash",{enumerable:!0,get:function(){return kvr.getPayloadHash}});var $vr=JSe();Object.defineProperty(jp,"moveHeadersToQuery",{enumerable:!0,get:function(){return $vr.moveHeadersToQuery}});var Bvr=YSe();Object.defineProperty(jp,"prepareRequest",{enumerable:!0,get:function(){return Bvr.prepareRequest}});fyt.__exportStar(USe(),jp)});var myt=v(QSe=>{"use strict";Object.defineProperty(QSe,"__esModule",{value:!0});var qvr=(V1(),zl(H1));qvr.__exportStar(pyt(),QSe)});var Va=v((Z_o,hyt)=>{"use strict";hyt.exports={ArrayIsArray(t){return Array.isArray(t)},ArrayPrototypeIncludes(t,e){return t.includes(e)},ArrayPrototypeIndexOf(t,e){return t.indexOf(e)},ArrayPrototypeJoin(t,e){return t.join(e)},ArrayPrototypeMap(t,e){return t.map(e)},ArrayPrototypePop(t,e){return t.pop(e)},ArrayPrototypePush(t,e){return t.push(e)},ArrayPrototypeSlice(t,e,r){return t.slice(e,r)},Error,FunctionPrototypeCall(t,e,...r){return t.call(e,...r)},FunctionPrototypeSymbolHasInstance(t,e){return Function.prototype[Symbol.hasInstance].call(t,e)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(t,e){return Object.defineProperties(t,e)},ObjectDefineProperty(t,e,r){return Object.defineProperty(t,e,r)},ObjectGetOwnPropertyDescriptor(t,e){return Object.getOwnPropertyDescriptor(t,e)},ObjectKeys(t){return Object.keys(t)},ObjectSetPrototypeOf(t,e){return Object.setPrototypeOf(t,e)},Promise,PromisePrototypeCatch(t,e){return t.catch(e)},PromisePrototypeThen(t,e,r){return t.then(e,r)},PromiseReject(t){return Promise.reject(t)},PromiseResolve(t){return Promise.resolve(t)},ReflectApply:Reflect.apply,RegExpPrototypeTest(t,e){return t.test(e)},SafeSet:Set,String,StringPrototypeSlice(t,e,r){return t.slice(e,r)},StringPrototypeToLowerCase(t){return t.toLowerCase()},StringPrototypeToUpperCase(t){return t.toUpperCase()},StringPrototypeTrim(t){return t.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(t,e,r){return t.set(e,r)},Boolean,Uint8Array}});var Zk=v((X_o,VQ)=>{"use strict";var{AbortController:gyt,AbortSignal:Uvr}=typeof self<"u"?self:typeof window<"u"?window:void 0;VQ.exports=gyt;VQ.exports.AbortSignal=Uvr;VQ.exports.default=gyt});var FH=v((Q_o,exe)=>{"use strict";var Xk=typeof Reflect=="object"?Reflect:null,yyt=Xk&&typeof Xk.apply=="function"?Xk.a
`;super(r),this.name="AggregateError",this.errors=e}};rxe.exports={AggregateError:txe,kEmptyObject:Object.freeze({}),once(t){let e=!1;return function(...r){e||(e=!0,t.apply(this,r))}},createDeferredPromise:function(){let t,e;return{promise:new Promise((n,o)=>{t=n,e=o}),resolve:t,reject:e}},promisify(t){return new Promise((e,r)=>{t((n,...o)=>n?r(n):e(...o))})},debuglog(){return function(){}},format(t,...e){return t.replace(/%([sdifj])/g,function(...[r,n]){let o=e.shift();return n==="f"?o.toFixed(6):n==="j"?JSON.stringify(o):n==="s"&&typeof o=="object"?`${o.constructor!==Object?o.constructor.name:""} {}`.trim():o.toString()})},inspect(t){switch(typeof t){case"string":if(t.includes("'"))if(t.includes('"')){if(!t.includes("`")&&!t.includes("${"))return`\`${t}\``}else return`"${t}"`;return`'${t}'`;case"number":return isNaN(t)?"NaN":Object.is(t,-0)?String(t):t;case"bigint":return`${String(t)}n`;case"boolean":case"undefined":return String(t);case"object":return"{}"}},types:{isAsyncFunction(t){return t instanceof ewr},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:twr,deprecate(t,e){return t},addAbortListener:FH().addAbortListener||function(e,r){if(e===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);Tyt(e,"signal"),rwr(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[Yvr]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[Zvr](){var o;(o=n)===null||o===void 0||o()}}},AbortSignalAny:Xvr.any||function(e){if(e.length===1)return e[0];let r=new Qvr,n=()=>r.abort();return e.forEach(o=>{Tyt(o,"signals"),o.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{e.forEach(o=>o.removeEventListener("abort",n))},{once:!0}),r.signal}};rxe.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var Kf=v((tvo,Myt)=>{"use strict";var{format:nwr,inspect:GQ,AggregateError:owr}=Gd(),iwr=globalThis.AggregateError||owr,awr=Symbol("kIsNodeError"),swr=["string","function","number","object","Function","Object","boolean","bigint","symbol"],uwr=/^([A-Z][a-z0-9]*)+$/,lwr="__node_internal_",JQ={};function Y1(t,e){if(!t)throw new JQ.ERR_INTERNAL_ASSERTION(e)}function Ayt(t){let e="",r=t.length,n=t[0]==="-"?1:0;for(;r>=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function cwr(t,e,r){if(typeof e=="function")return Y1(e.length<=r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${e.length}).`),e(...r);let n=(e.match(/%[dfijoOs]/g)||[]).length;return Y1(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:nwr(e,...r)}function qc(t,e,r){r||(r=Error);class n extends r{constructor(...i){super(cwr(t,e,i))}toString(){return`${this.name} [${t}]: ${this.message}`}}Object.defineProperties(n.prototype,{name:{value:r.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${t}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),n.prototype.code=t,n.prototype[awr]=!0,JQ[t]=n}function Iyt(t){let e=lwr+t.name;return Object.defineProperty(t,"name",{value:e}),t}function dwr(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new iwr([e,t],e.message);return r.code=e.code,r}return t||e}var nxe=class extends Error{constructor(e="The operation was aborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new JQ.ERR_INVALID_ARG_TYPE("options","Object",r);super(e,r),this.code="ABORT_ERR",this.name="AbortError"}};qc("ERR_ASSERTION","%s",Error);qc("ERR_INVALID_ARG_TYPE",(t,e,r)=>{Y1(typeof t=="string","'name' must be a string"),Array.isArray(e)||(e=[e]);let n="The ";t.endsWith(" argument")?n+=`${t} `:n+=`"${t}" ${t.includes(".")?"property":"argument"} `,n+="must be ";let o=[],i=[],a=[];for(let u of e)Y1(typeof u=="string","All expected entries have to be of type string"),swr.includes(u)?o.push(u.toLowerCase()):uwr.test(u)?i.push(u):(Y1(u!=="object",'The value "object" should be written as "Object"'),a.push(u));if(i.length>0){let
`)>=0)return!1;return!0}function $Or(t,e){var r;if(t.indent===" ")r=" ";else if(typeof t.indent=="number"&&t.indent>0)r=G_.call(Array(t.indent+1)," ");else return null;return{base:r,prev:G_.call(Array(e+1),r)}}function SCe(t,e){if(t.length===0)return"";var r=`
2025-07-05 20:48:33 +08:00
`+e.prev+e.base;return r+G_.call(t,","+r)+`
2025-07-12 10:26:56 +08:00
`+e.prev}function Oee(t,e){var r=wCe(t),n=[];if(r){n.length=t.length;for(var o=0;o<t.length;o++)n[o]=PO(t,o)?e(t[o],t):""}var i=typeof gCe=="function"?gCe(t):[],a;if(f$){a={};for(var s=0;s<i.length;s++)a["$"+i[s]]=i[s]}for(var u in t)PO(t,u)&&(r&&String(Number(u))===u&&u<t.length||f$&&a["$"+u]instanceof Symbol||(Fvt.call(/[^\w$]/,u)?n.push(e(u,t)+": "+e(t[u],t)):n.push(u+": "+e(t[u],t))));if(typeof gCe=="function")for(var l=0;l<i.length;l++)kvt.call(t,i[l])&&n.push("["+e(i[l])+"]: "+e(t[i[l]],t));return n}});var Wvt=v((Ivo,Vvt)=>{"use strict";var BOr=eV(),qOr=uj(),Tee=function(t,e,r){for(var n=t,o;(o=n.next)!=null;n=o)if(o.key===e)return n.next=o.next,r||(o.next=t.next,t.next=o),o},UOr=function(t,e){if(t){var r=Tee(t,e);return r&&r.value}},zOr=function(t,e,r){var n=Tee(t,e);n?n.value=r:t.next={key:e,next:t.next,value:r}},HOr=function(t,e){return t?!!Tee(t,e):!1},VOr=function(t,e){if(t)return Tee(t,e,!0)};Vvt.exports=function(){var e,r={assert:function(n){if(!r.has(n))throw new qOr("Side channel does not contain "+BOr(n))},delete:function(n){var o=e&&e.next,i=VOr(e,n);return i&&o&&o===i&&(e=void 0),!!i},get:function(n){return UOr(e,n)},has:function(n){return HOr(e,n)},set:function(n,o){e||(e={next:void 0}),zOr(e,n,o)}};return r}});var PCe=v((Mvo,Kvt)=>{"use strict";Kvt.exports=Object});var Jvt=v((Rvo,Gvt)=>{"use strict";Gvt.exports=Error});var Zvt=v((jvo,Yvt)=>{"use strict";Yvt.exports=EvalError});var Qvt=v((Nvo,Xvt)=>{"use strict";Xvt.exports=RangeError});var twt=v((Dvo,ewt)=>{"use strict";ewt.exports=ReferenceError});var nwt=v((Lvo,rwt)=>{"use strict";rwt.exports=SyntaxError});var iwt=v((Fvo,owt)=>{"use strict";owt.exports=URIError});var swt=v((kvo,awt)=>{"use strict";awt.exports=Math.abs});var lwt=v(($vo,uwt)=>{"use strict";uwt.exports=Math.floor});var dwt=v((Bvo,cwt)=>{"use strict";cwt.exports=Math.max});var pwt=v((qvo,fwt)=>{"use strict";fwt.exports=Math.min});var hwt=v((Uvo,mwt)=>{"use strict";mwt.exports=Math.pow});var ywt=v((zvo,gwt)=>{"use strict";gwt.exports=Math.round});var _wt=v((Hvo,bwt)=>{"use strict";bwt.exports=Number.isNaN||function(e){return e!==e}});var wwt=v((Vvo,vwt)=>{"use strict";var WOr=_wt();vwt.exports=function(e){return WOr(e)||e===0?e:e<0?-1:1}});var xwt=v((Wvo,Swt)=>{"use strict";Swt.exports=Object.getOwnPropertyDescriptor});var ECe=v((Kvo,Cwt)=>{"use strict";var Aee=xwt();if(Aee)try{Aee([],"length")}catch{Aee=null}Cwt.exports=Aee});var Pwt=v((Gvo,Owt)=>{"use strict";var Iee=Object.defineProperty||!1;if(Iee)try{Iee({},"a",{value:1})}catch{Iee=!1}Owt.exports=Iee});var Twt=v((Jvo,Ewt)=>{"use strict";Ewt.exports=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},r=Symbol("test"),n=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var o=42;e[r]=o;for(var i in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var a=Object.getOwnPropertySymbols(e);if(a.length!==1||a[0]!==r||!Object.prototype.propertyIsEnumerable.call(e,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var s=Object.getOwnPropertyDescriptor(e,r);if(s.value!==o||s.enumerable!==!0)return!1}return!0}});var Mwt=v((Yvo,Iwt)=>{"use strict";var Awt=typeof Symbol<"u"&&Symbol,KOr=Twt();Iwt.exports=function(){return typeof Awt!="function"||typeof Symbol!="function"||typeof Awt("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:KOr()}});var TCe=v((Zvo,Rwt)=>{"use strict";Rwt.exports=typeof Reflect<"u"&&Reflect.getPrototypeOf||null});var ACe=v((Xvo,jwt)=>{"use strict";var GOr=PCe();jwt.exports=GOr.getPrototypeOf||null});var Lwt=v((Qvo,Dwt)=>{"use strict";var JOr="Function.prototype.bind called on incompatible ",YOr=Object.prototype.toString,ZOr=Math.max,XOr="[object Function]",Nwt=function(e,r){for(var n=[],o=0;o<e.length;o+=1)n[o]=e[o];for(var i=0;i<r.length;i+=1)n[i+e.length]=r[i];return n},QOr=function(e,r){f
`,this.streamTerminator=n.streamTerminator):this.messageTerminator=n.messageTerminator,o?.addEventListener("abort",()=>this.controller.abort())}iterMessages(){return lSt(this,arguments,function*(){var r,n;this.controller.signal;let o=cSt(this.stream),i="",a=!1;try{for(var s=uSt(o),u;u=yield $y(s.next()),!u.done;){let l=u.value;i+=this.decodeChunk(l);let c;for(;(c=i.indexOf(this.messageTerminator))>=0;){let d=i.slice(0,c+1);if(i=i.slice(c+1),d.length===0)continue;if(!a&&this.prefix!=null){let p=d.indexOf(this.prefix);if(p===-1)continue;a=!0,d=d.slice(p+this.prefix.length)}if(this.streamTerminator!=null&&d.includes(this.streamTerminator))return yield $y(void 0);let f=yield $y(this.parse(JSON.parse(d)));yield yield $y(f),a=!1}}}catch(l){r={error:l}}finally{try{u&&!u.done&&(n=s.return)&&(yield $y(n.call(s)))}finally{if(r)throw r.error}}})}[Symbol.asyncIterator](){return lSt(this,arguments,function*(){var r,n;try{for(var o=uSt(this.iterMessages()),i;i=yield $y(o.next()),!i.done;){let a=i.value;yield yield $y(a)}}catch(a){r={error:a}}finally{try{i&&!i.done&&(n=o.return)&&(yield $y(n.call(o)))}finally{if(r)throw r.error}}})}decodeChunk(e){let r="";if(typeof TextDecoder<"u"){let n=new TextDecoder("utf8");r+=n.decode(e)}else NTr.RUNTIME.type==="node"&&typeof e<"u"&&(r+=Buffer.isBuffer(e)?e:Buffer.from(e));return r}};Np.Stream=eOe;function cSt(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{next(){return sSt(this,void 0,void 0,function*(){try{let r=yield e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}})},return(){return sSt(this,void 0,void 0,function*(){let r=e.cancel();return e.releaseLock(),yield r,{done:!0,value:void 0}})},[Symbol.asyncIterator](){return this}}}Np.readableStreamAsyncIterable=cSt});var dSt=v(Kee=>{"use strict";Object.defineProperty(Kee,"__esModule",{value:!0});Kee.Stream=void 0;var LTr=tOe();Object.defineProperty(Kee,"Stream",{enumerable:!0,get:function(){return LTr.Stream}})});var mSt=v((qwo,pSt)=>{"use strict";var rOe=Object.defineProperty,FTr=Object.getOwnPropertyDescriptor,kTr=Object.getOwnPropertyNames,$Tr=Object.prototype.hasOwnProperty,BTr=(t,e)=>{for(var r in e)rOe(t,r,{get:e[r],enumerable:!0})},qTr=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of kTr(e))!$Tr.call(t,o)&&o!==r&&rOe(t,o,{get:()=>e[o],enumerable:!(n=FTr(e,o))||n.enumerable});return t},UTr=t=>qTr(rOe({},"__esModule",{value:!0}),t),fSt={};BTr(fSt,{Blob:()=>VTr,File:()=>WTr,FormData:()=>HTr});pSt.exports=UTr(fSt);var zTr=function(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:window}(),{FormData:HTr,Blob:VTr,File:WTr}=zTr});var ESt=v((Uwo,PSt)=>{"use strict";var iOe=Object.defineProperty,KTr=Object.getOwnPropertyDescriptor,GTr=Object.getOwnPropertyNames,JTr=Object.prototype.hasOwnProperty,YTr=(t,e)=>{for(var r in e)iOe(t,r,{get:e[r],enumerable:!0})},ZTr=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of GTr(e))!JTr.call(t,o)&&o!==r&&iOe(t,o,{get:()=>e[o],enumerable:!(n=KTr(e,o))||n.enumerable});return t},XTr=t=>ZTr(iOe({},"__esModule",{value:!0}),t),aOe=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},fs=(t,e,r)=>(aOe(t,e,"read from private field"),r?r.call(t):e.get(t)),Y_=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},uV=(t,e,r,n)=>(aOe(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),nOe=(t,e,r)=>(aOe(t,e,"access private method"),r),wSt={};YTr(wSt,{FormDataEncoder:()=>aAr,isFile:()=>pj,isFormData:()=>CSt});PSt.exports=XTr(wSt);var TO=t=>typeof t=="function",QTr=t=>TO(t[Symbol.asyncIterator]),hSt=65536;function*SSt(t){if(t.byteLength<=hSt){yield t;return}let e=0;for(;e<t.byteLength;){let r=Math.min(t.byteLength-e,hSt),n=t.buffer.slice(e,e+r);e+=n.byteLength,yield new Uint8Array(n)}}async function*eAr(t){let e=t.getReader();for(;;){let{done:r,value:n}=await e.read();if(r)break;yield n}}async function*gSt(t){for await(let e of t)yield*SSt(e)}var tAr=t=>{if(QTr(t))return gSt(t);if(TO(t.getReader))return gSt(eAr(t));throw new TypeError("Unsup
2025-07-05 20:48:33 +08:00
`||e===`
`&&n[r-1]!=="\r"?`\r
2025-07-12 10:26:56 +08:00
`:e),nAr=t=>Object.prototype.toString.call(t).slice(8,-1).toLowerCase();function bSt(t){if(nAr(t)!=="object")return!1;let e=Object.getPrototypeOf(t);return e==null?!0:(e.constructor&&e.constructor.toString())===Object.toString()}function _St(t,e){if(typeof e=="string"){for(let[r,n]of Object.entries(t))if(e.toLowerCase()===r.toLowerCase())return n}}var oAr=t=>new Proxy(t,{get:(e,r)=>_St(e,r),has:(e,r)=>_St(e,r)!==void 0}),CSt=t=>!!(t&&TO(t.constructor)&&t[Symbol.toStringTag]==="FormData"&&TO(t.append)&&TO(t.getAll)&&TO(t.entries)&&TO(t[Symbol.iterator])),vSt=t=>String(t).replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/"/g,"%22"),pj=t=>!!(t&&typeof t=="object"&&TO(t.constructor)&&t[Symbol.toStringTag]==="File"&&TO(t.stream)&&t.name!=null),iAr={enableAdditionalHeaders:!1},Gee={writable:!1,configurable:!1},dA,lV,Jee,cV,fj,dV,fV,Yee,Zee,sOe,oOe,OSt,aAr=class{constructor(t,e,r){if(Y_(this,Zee),Y_(this,oOe),Y_(this,dA,`\r
`),Y_(this,lV,void 0),Y_(this,Jee,void 0),Y_(this,cV,"-".repeat(2)),Y_(this,fj,new TextEncoder),Y_(this,dV,void 0),Y_(this,fV,void 0),Y_(this,Yee,void 0),!CSt(t))throw new TypeError("Expected first argument to be a FormData instance.");let n;if(bSt(e)?r=e:n=e,n||(n=rAr()),typeof n!="string")throw new TypeError("Expected boundary argument to be a string.");if(r&&!bSt(r))throw new TypeError("Expected options argument to be an object.");uV(this,fV,Array.from(t.entries())),uV(this,Yee,{...iAr,...r}),uV(this,lV,fs(this,fj).encode(fs(this,dA))),uV(this,Jee,fs(this,lV).byteLength),this.boundary=`form-data-boundary-${n}`,this.contentType=`multipart/form-data; boundary=${this.boundary}`,uV(this,dV,fs(this,fj).encode(`${fs(this,cV)}${this.boundary}${fs(this,cV)}${fs(this,dA).repeat(2)}`));let o={"Content-Type":this.contentType},i=nOe(this,oOe,OSt).call(this);i&&(this.contentLength=i,o["Content-Length"]=i),this.headers=oAr(Object.freeze(o)),Object.defineProperties(this,{boundary:Gee,contentType:Gee,contentLength:Gee,headers:Gee})}*values(){for(let[t,e]of fs(this,fV)){let r=pj(e)?e:fs(this,fj).encode(xSt(e));yield nOe(this,Zee,sOe).call(this,t,r),yield r,yield fs(this,lV)}yield fs(this,dV)}async*encode(){for(let t of this.values())pj(t)?yield*tAr(t.stream()):yield*SSt(t)}[Symbol.iterator](){return this.values()}[Symbol.asyncIterator](){return this.encode()}};dA=new WeakMap;lV=new WeakMap;Jee=new WeakMap;cV=new WeakMap;fj=new WeakMap;dV=new WeakMap;fV=new WeakMap;Yee=new WeakMap;Zee=new WeakSet;sOe=function(t,e){let r="";if(r+=`${fs(this,cV)}${this.boundary}${fs(this,dA)}`,r+=`Content-Disposition: form-data; name="${vSt(t)}"`,pj(e)&&(r+=`; filename="${vSt(e.name)}"${fs(this,dA)}`,r+=`Content-Type: ${e.type||"application/octet-stream"}`),fs(this,Yee).enableAdditionalHeaders===!0){let n=pj(e)?e.size:e.byteLength;n!=null&&!isNaN(n)&&(r+=`${fs(this,dA)}Content-Length: ${n}`)}return fs(this,fj).encode(`${r}${fs(this,dA).repeat(2)}`)};oOe=new WeakSet;OSt=function(){let t=0;for(let[e,r]of fs(this,fV)){let n=pj(r)?r:fs(this,fj).encode(xSt(r)),o=pj(n)?n.size:n.byteLength;if(o==null||isNaN(o))return;t+=nOe(this,Zee,sOe).call(this,e,n).byteLength,t+=o,t+=fs(this,Jee)}return String(t+fs(this,dV).byteLength)}});var ASt=v((Hwo,TSt)=>{TSt.exports=typeof self=="object"?self.FormData:window.FormData});var ISt=v(Ql=>{"use strict";var sAr=Ql&&Ql.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),uAr=Ql&&Ql.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),M$=Ql&&Ql.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&sAr(e,t,r);return uAr(e,t),e},fA=Ql&&Ql.__awaiter||function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(c){try{l(n.next(c))}catch(d){a(d)}}function u(c){try{l(n.throw(c))}catch(d){a(d)}}function l(c){c.done?i(c.value):o(c.value).then(s,u)}l((n=n.apply(t,e||[])).next())})};Object.defineProperty(Ql,"__esModule",{value:!0});Ql.WebFormData=Ql.Node16FormData=Ql.Node18FormData=Ql.newFormData=void 0;var Xee=v$();function uOe(t){return typeof t=="object"&&t!=null&&"name"in t}function lAr(){return fA(this,void 0,void 0,function*(){let t;return Xee.RUNTIME.type==="node"&&Xee.RUNTIME.parsedVersion!=null&&Xee.RUNTIME.parsedVersion>=18?t=new Qee:Xee.RUNTIME.type==="node"?t=new ete:t=new tte,yield t.setup(),t})}Ql.newFormData=lAr;var Qee=class{setup(){return fA(this,void 0,void 0,function*(){this.fd=new(yield Promise.resolve().then(()=>M$(mSt()))).FormData})}append(e,r){var n;(n=this.fd)===null||n===void 0||n.append(e,r)}appendFile(e,r,n){var o,i;return fA(this,void 0,void 0,function*(){n==null&&uOe(r)&&(n=r.name),r instanceof(yield Promise.resolve().then
`)),{ok:!0,value:e}):n}}});var lOe=v(ite=>{"use strict";Object.defineProperty(ite,"__esModule",{value:!0});ite.stringifyValidationError=void 0;function hAr(t){return t.path.length===0?t.message:`${t.path.join(" -> ")}: ${t.message}`}ite.stringifyValidationError=hAr});var dOe=v(ate=>{"use strict";Object.defineProperty(ate,"__esModule",{value:!0});ate.JsonError=void 0;var gAr=lOe(),cOe=class t extends Error{constructor(e){super(e.map(gAr.stringifyValidationError).join("; ")),this.errors=e,Object.setPrototypeOf(this,t.prototype)}};ate.JsonError=cOe});var pOe=v(ste=>{"use strict";Object.defineProperty(ste,"__esModule",{value:!0});ste.ParseError=void 0;var yAr=lOe(),fOe=class t extends Error{constructor(e){super(e.map(yAr.stringifyValidationError).join("; ")),this.errors=e,Object.setPrototypeOf(this,t.prototype)}};ste.ParseError=fOe});var DSt=v(pA=>{"use strict";Object.defineProperty(pA,"__esModule",{value:!0});pA.transform=pA.optional=pA.getSchemaUtils=void 0;var bAr=Uc(),_Ar=dOe(),vAr=pOe();function mOe(t){return{optional:()=>jSt(t),transform:e=>NSt(t,e),parseOrThrow:(e,r)=>{let n=t.parse(e,r);if(n.ok)return n.value;throw new vAr.ParseError(n.errors)},jsonOrThrow:(e,r)=>{let n=t.json(e,r);if(n.ok)return n.value;throw new _Ar.JsonError(n.errors)}}}pA.getSchemaUtils=mOe;function jSt(t){let e={parse:(r,n)=>r==null?{ok:!0,value:void 0}:t.parse(r,n),json:(r,n)=>n?.omitUndefined&&r===void 0?{ok:!0,value:void 0}:r==null?{ok:!0,value:null}:t.json(r,n),getType:()=>bAr.SchemaType.OPTIONAL};return Object.assign(Object.assign({},e),mOe(e))}pA.optional=jSt;function NSt(t,e){let r={parse:(n,o)=>{let i=t.parse(n,o);return i.ok?{ok:!0,value:e.transform(i.value)}:i},json:(n,o)=>{let i=e.untransform(n);return t.json(i,o)},getType:()=>t.getType()};return Object.assign(Object.assign({},r),mOe(r))}pA.transform=NSt});var Lm=v(ag=>{"use strict";Object.defineProperty(ag,"__esModule",{value:!0});ag.ParseError=ag.JsonError=ag.transform=ag.optional=ag.getSchemaUtils=void 0;var hOe=DSt();Object.defineProperty(ag,"getSchemaUtils",{enumerable:!0,get:function(){return hOe.getSchemaUtils}});Object.defineProperty(ag,"optional",{enumerable:!0,get:function(){return hOe.optional}});Object.defineProperty(ag,"transform",{enumerable:!0,get:function(){return hOe.transform}});var wAr=dOe();Object.defineProperty(ag,"JsonError",{enumerable:!0,get:function(){return wAr.JsonError}});var SAr=pOe();Object.defineProperty(ag,"ParseError",{enumerable:!0,get:function(){return SAr.ParseError}})});var LSt=v(ute=>{"use strict";Object.defineProperty(ute,"__esModule",{value:!0});ute.date=void 0;var xAr=Uc(),gOe=Dp(),CAr=AO(),OAr=Lm(),PAr=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;function EAr(){let t={parse:(e,{breadcrumbsPrefix:r=[]}={})=>typeof e!="string"?{ok:!1,errors:[{path:r,message:(0,gOe.getErrorMessageForIncorrectType)(e,"string")}]}:PAr.test(e)?{ok:!0,value:new Date(e)}:{ok:!1,errors:[{path:r,message:(0,gOe.getErrorMessageForIncorrectType)(e,"ISO 8601 date string")}]},json:(e,{breadcrumbsPrefix:r=[]}={})=>e instanceof Date?{ok:!0,value:e.toISOString()}:{ok:!1,errors:[{path:r,message:(0,gOe.getErrorMessageForIncorrectType)(e,"Date object")}]},getType:()=>xAr.SchemaType.DATE};return Object.assign(Object.assign({},(0,CAr.maybeSkipValidation)(t)),(0,OAr.getSchemaUtils)(t))}ute.date=EAr});var FSt=v(lte=>{"use strict";Object.defineProperty(lte,"__esModule",{value:!0});lte.date=void 0;var TAr=LSt();Object.defineProperty(lte,"date",{enumerable:!0,get:function(){return TAr.date}})});var IO=v(cte=>{"use strict";Object.defineProperty(cte,"__esModule",{value:!0});cte.createIdentitySchemaCreator=void 0;var AAr=Lm(),IAr=AO();function MAr(t,e){return()=>{let r={parse:e,json:e,getType:()=>t};return Object.assign(Object.assign({},(0,IAr.maybeSkipValidation)(r)),(0,AAr.getSchemaUtils)(r))}}cte.createIdentitySchemaCreator=MAr});var $St=v(dte=>{"use stri
`);o.enqueue(s)}catch(i){o.error(i)}})},cancel(){var o;return bV(this,void 0,void 0,function*(){yield(o=r.return)===null||o===void 0?void 0:o.call(r)})}})}};Vs.StreamUtils=AOe;function Mxt(t,e){return vV(this,arguments,function*(){var n,o;if(!t.body)throw e?.abort(),new B$.CohereError({message:"Attempted to iterate over a response with no body"});let i=new IOe,a=new hA,s=MOe(t.body);try{for(var u=_V(EMr(s)),l;l=yield Ta(u.next()),!l.done;){let c=l.value;for(let d of a.decode(c)){let f=i.decode(d);f&&(yield yield Ta(f))}}}catch(c){n={error:c}}finally{try{l&&!l.done&&(o=u.return)&&(yield Ta(o.call(u)))}finally{if(n)throw n.error}}for(let c of a.flush()){let d=i.decode(c);d&&(yield yield Ta(d))}})}Vs._iterSSEMessages=Mxt;function EMr(t){return vV(this,arguments,function*(){var r,n;let o=new Uint8Array;try{for(var i=_V(t),a;a=yield Ta(i.next()),!a.done;){let s=a.value;if(s==null)continue;let u=s instanceof ArrayBuffer?new Uint8Array(s):typeof s=="string"?new TextEncoder().encode(s):s,l=new Uint8Array(o.length+u.length);l.set(o),l.set(u,o.length),o=l;let c;for(;(c=TMr(o))!==-1;)yield yield Ta(o.slice(0,c)),o=o.slice(c)}}catch(s){r={error:s}}finally{try{a&&!a.done&&(n=i.return)&&(yield Ta(n.call(i)))}finally{if(r)throw r.error}}o.length>0&&(yield yield Ta(o))})}function TMr(t){for(let n=0;n<t.length-2;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)return n+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)return n+4}return-1}var IOe=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=IMr(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},hA=class t{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){let r=this.decodeText(e);if(this.trailingCR&&(r="\r"+r,this.trailingCR=!1),r.endsWith("\r")&&(this.trailingCR=!0,r=r.slice(0,-1)),!r)return[];let n=t.NEWLINE_CHARS.has(r[r.length-1]||""),o=r.split(t.NEWLINE_REGEXP);return n&&o.pop(),o.length===1&&!n?(this.buffer.push(o[0]),[]):(this.buffer.length>0&&(o=[this.buffer.join("")+o[0],...o.slice(1)],this.buffer=[]),n||(this.buffer=[o.pop()||""]),o)}decodeText(e){var r;if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new B$.CohereError({message:`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`})}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return(r=this.textDecoder)!==null&&r!==void 0||(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new B$.CohereError({message:`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`})}throw new B$.CohereError({message:"Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error."})}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}};Vs.LineDecoder=hA;hA.NEWLINE_CHARS=new Set([`
`,"\r"]);hA.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function AMr(t){let e=new hA,r=[];for(let n of t)r.push(...e.decode(n));return r}Vs._decodeChunks=AMr;function IMr(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}function MOe(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{next(){return bV(this,void 0,void 0,function*(){try{let r=yield e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}})},return(){return bV(this,void 0,void 0,function*(){let r=e.cancel();return e.releaseLock(),yield r,{done:!0,value:void 0}})},[Symbol.asyncIterator](){return this}}}Vs.readableStreamAsyncIterable=MOe});var ROe=v(Z_=>{"use strict";var MMr=Z_&&Z_.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),RMr=Z_&&Z_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),jMr=Z_&&Z_.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&MMr(e,t,r);return RMr(e,t),e};Object.defineProperty(Z_,"__esModule",{value:!0});Z_.V2ChatStreamRequestCitationMode=void 0;var NMr=jMr(G());Z_.V2ChatStreamRequestCitationMode=NMr.serialization.enum_(["FAST","ACCURATE","OFF"])});var jOe=v(X_=>{"use strict";var DMr=X_&&X_.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),LMr=X_&&X_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),FMr=X_&&X_.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&DMr(e,t,r);return LMr(e,t),e};Object.defineProperty(X_,"__esModule",{value:!0});X_.V2ChatRequestCitationMode=void 0;var kMr=FMr(G());X_.V2ChatRequestCitationMode=kMr.serialization.enum_(["FAST","ACCURATE","OFF"])});var q$=v(Q_=>{"use strict";var $Mr=Q_&&Q_.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),BMr=Q_&&Q_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),qMr=Q_&&Q_.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&$Mr(e,t,r);return BMr(e,t),e};Object.defineProperty(Q_,"__esModule",{value:!0});Q_.TextContent=void 0;var jxt=qMr(G());Q_.TextContent=jxt.serialization.object({text:jxt.serialization.string()})});var NOe=v(ev=>{"use strict";var UMr=ev&&ev.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),zMr=ev&&ev.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),HMr=ev&&ev.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&UMr(e,t,r);return zMr(e,t),e};Object.defineProperty(ev,"__esModule",{value:!0});ev.Content=void 0;var VMr=HMr(G()),WMr=q$();ev.Content=VMr.serialization.union("type",{text:WMr.TextContent}).transform({
2025-07-05 20:48:33 +08:00
`)}}}}catch(S){a={error:S}}finally{try{h&&!h.done&&(s=m.return)&&(yield s.call(m))}finally{if(a)throw a.error}}for(let S of g.flush()){let x=(0,ni.parseAWSEvent)(S);if(x){let O=yield(0,ni.mapResponseFromBedrock)(c,u,x);y.push(JSON.stringify(O)+`
2025-07-12 10:26:56 +08:00
`)}}return y.end(),{ok:!0,body:y}}else{let b=yield p.body;return{ok:!0,body:yield(0,ni.mapResponseFromBedrock)(c,u,b)}}}catch(b){throw b}});ni.fetchOverride=V8r});var LO=v(wre=>{"use strict";Object.defineProperty(wre,"__esModule",{value:!0});wre.CohereEnvironment=void 0;wre.CohereEnvironment={Production:"https://api.cohere.com"}});var PA=v((rPt,Sre)=>{(function(t,e,r){typeof Sre<"u"&&Sre.exports?Sre.exports=r():typeof define=="function"&&define.amd?define(r):e[t]=r()})("urljoin",rPt,function(){function t(e){var r=[];if(e.length===0)return"";if(typeof e[0]!="string")throw new TypeError("Url must be a string. Received "+e[0]);if(e[0].match(/^[^/:]+:\/*$/)&&e.length>1){var n=e.shift();e[0]=n+e[0]}e[0].match(/^file:\/\/\//)?e[0]=e[0].replace(/^([^/:]+):\/*/,"$1:///"):e[0]=e[0].replace(/^([^/:]+):\/*/,"$1://");for(var o=0;o<e.length;o++){var i=e[o];if(typeof i!="string")throw new TypeError("Url must be a string. Received "+i);i!==""&&(o>0&&(i=i.replace(/^[\/]+/,"")),o<e.length-1?i=i.replace(/[\/]+$/,""):i=i.replace(/[\/]+$/,"/"),r.push(i))}var a=r.join("/");a=a.replace(/\/(\?|&|#[^!])/g,"$1");var s=a.split("?");return a=s.shift()+(s.length>0?"?":"")+s.join("&"),a}return function(){var e;return typeof arguments[0]=="object"?e=arguments[0]:e=[].slice.call(arguments),t(e)}})});var UTe=v($p=>{"use strict";var W8r=$p&&$p.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),K8r=$p&&$p.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),VV=$p&&$p.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&W8r(e,t,r);return K8r(e,t),e},xre=$p&&$p.__awaiter||function(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(c){try{l(n.next(c))}catch(d){a(d)}}function u(c){try{l(n.throw(c))}catch(d){a(d)}}function l(c){c.done?i(c.value):o(c.value).then(s,u)}l((n=n.apply(t,e||[])).next())})},G8r=$p&&$p.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty($p,"__esModule",{value:!0});$p.V2=void 0;var nPt=VV(LO()),Fp=VV(G()),ms=VV(aO()),kp=VV(DO()),oPt=G8r(PA()),FO=VV(As()),qTe=class{constructor(e={}){this._options=e}chatStream(e,r){var n,o;return xre(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:Fp.fetcher)({url:(0,oPt.default)((o=yield Fp.Supplier.get(this._options.environment))!==null&&o!==void 0?o:nPt.CohereEnvironment.Production,"v2/chat"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield Fp.Supplier.get(this._options.clientName))!=null?yield Fp.Supplier.get(this._options.clientName):void 0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.13.0","User-Agent":"cohere-ai/7.13.0","X-Fern-Runtime":Fp.RUNTIME.type,"X-Fern-Runtime-Version":Fp.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},kp.V2ChatStreamRequest.jsonOrThrow(e,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0})),{stream:!0}),responseType:"sse",timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:3e5,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(i.ok)return new Fp.Stream({stream:i.body,parse:a=>xre(this,void 0,void 0,function*(){return kp.StreamedChatResponse2.parseOrThrow(a,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]})}),signal:r?.abortSignal,eventShape:{type:"sse",streamTerminator:"[DONE]"}});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new ms.BadRequestError(i.error.body);case 401:th
2025-07-05 20:48:33 +08:00
`}});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new Ee.BadRequestError(i.error.body);case 401:throw new Ee.UnauthorizedError(i.error.body);case 403:throw new Ee.ForbiddenError(i.error.body);case 404:throw new Ee.NotFoundError(i.error.body);case 422:throw new Ee.UnprocessableEntityError(st.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new Ee.TooManyRequestsError(st.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new Ee.ClientClosedRequestError(st.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 500:throw new Ee.InternalServerError(i.error.body);case 501:throw new Ee.NotImplementedError(st.NotImplementedErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 503:throw new Ee.ServiceUnavailableError(i.error.body);case 504:throw new Ee.GatewayTimeoutError(st.GatewayTimeoutErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));default:throw new jr.CohereError({statusCode:i.error.statusCode,body:i.error.body})}switch(i.error.reason){case"non-json":throw new jr.CohereError({statusCode:i.error.statusCode,body:i.error.rawBody});case"timeout":throw new jr.CohereTimeoutError;case"unknown":throw new jr.CohereError({message:i.error.errorMessage})}})}chat(e,r){var n,o;return Vp(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:_t.fetcher)({url:(0,Hy.default)((o=yield _t.Supplier.get(this._options.environment))!==null&&o!==void 0?o:zy.CohereEnvironment.Production,"v1/chat"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield _t.Supplier.get(this._options.clientName))!=null?yield _t.Supplier.get(this._options.clientName):void 0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.13.0","User-Agent":"cohere-ai/7.13.0","X-Fern-Runtime":_t.RUNTIME.type,"X-Fern-Runtime-Version":_t.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},st.ChatRequest.jsonOrThrow(e,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0})),{stream:!1}),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:3e5,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(i.ok)return st.NonStreamedChatResponse.parseOrThrow(i.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new Ee.BadRequestError(i.error.body);case 401:throw new Ee.UnauthorizedError(i.error.body);case 403:throw new Ee.ForbiddenError(i.error.body);case 404:throw new Ee.NotFoundError(i.error.body);case 422:throw new Ee.UnprocessableEntityError(st.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new Ee.TooManyRequestsError(st.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new Ee.ClientClosedRequestError(st.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{
2025-07-12 10:26:56 +08:00
`}});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new Ee.BadRequestError(i.error.body);case 401:throw new Ee.UnauthorizedError(i.error.body);case 403:throw new Ee.ForbiddenError(i.error.body);case 404:throw new Ee.NotFoundError(i.error.body);case 422:throw new Ee.UnprocessableEntityError(st.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new Ee.TooManyRequestsError(st.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new Ee.ClientClosedRequestError(st.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 500:throw new Ee.InternalServerError(i.error.body);case 501:throw new Ee.NotImplementedError(st.NotImplementedErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 503:throw new Ee.ServiceUnavailableError(i.error.body);case 504:throw new Ee.GatewayTimeoutError(st.GatewayTimeoutErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));default:throw new jr.CohereError({statusCode:i.error.statusCode,body:i.error.body})}switch(i.error.reason){case"non-json":throw new jr.CohereError({statusCode:i.error.statusCode,body:i.error.rawBody});case"timeout":throw new jr.CohereTimeoutError;case"unknown":throw new jr.CohereError({message:i.error.errorMessage})}})}generate(e,r){var n,o;return Vp(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:_t.fetcher)({url:(0,Hy.default)((o=yield _t.Supplier.get(this._options.environment))!==null&&o!==void 0?o:zy.CohereEnvironment.Production,"v1/generate"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield _t.Supplier.get(this._options.clientName))!=null?yield _t.Supplier.get(this._options.clientName):void 0,"X-Fern-Language":"JavaScript","X-Fern-SDK-Name":"cohere-ai","X-Fern-SDK-Version":"7.13.0","User-Agent":"cohere-ai/7.13.0","X-Fern-Runtime":_t.RUNTIME.type,"X-Fern-Runtime-Version":_t.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},st.GenerateRequest.jsonOrThrow(e,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0})),{stream:!1}),timeoutMs:r?.timeoutInSeconds!=null?r.timeoutInSeconds*1e3:3e5,maxRetries:r?.maxRetries,abortSignal:r?.abortSignal});if(i.ok)return st.Generation.parseOrThrow(i.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new Ee.BadRequestError(i.error.body);case 401:throw new Ee.UnauthorizedError(i.error.body);case 403:throw new Ee.ForbiddenError(i.error.body);case 404:throw new Ee.NotFoundError(i.error.body);case 422:throw new Ee.UnprocessableEntityError(st.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new Ee.TooManyRequestsError(st.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new Ee.ClientClosedRequestError(st.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{u
`).filter(Boolean).reduce((n,o)=>{let[i,a,...s]=o.split(" "),u=Number.parseInt(a,10);return s.forEach((l,c)=>n[l]=u+c),n},{});for(let[n,o]of Object.entries(r)){let i=wPt.default.toByteArray(n);this.rankMap.set(i.join(","),o),this.textMap.set(o,i)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[o,i])=>(n[i]=this.textEncoder.encode(o),n),{})}encode(t,e=[],r="all"){let n=new RegExp(this.patStr,"ug"),o=oAe.specialTokenRegex(Object.keys(this.specialTokens)),i=[],a=new Set(e==="all"?Object.keys(this.specialTokens):e),s=new Set(r==="all"?Object.keys(this.specialTokens).filter(l=>!a.has(l)):r);if(s.size>0){let l=oAe.specialTokenRegex([...s]),c=t.match(l);if(c!=null)throw new Error(`The text contains a special token that is not allowed: ${c[0]}`)}let u=0;for(;;){let l=null,c=u;for(;o.lastIndex=c,l=o.exec(t),!(l==null||a.has(l[0]));)c=l.index+1;let d=l?.index??t.length;for(let p of t.substring(u,d).matchAll(n)){let m=this.textEncoder.encode(p[0]),h=this.rankMap.get(m.join(","));if(h!=null){i.push(h);continue}i.push(...U6r(m,this.rankMap))}if(l==null)break;let f=this.specialTokens[l[0]];i.push(f),u=l.index+l[0].length}return i}decode(t){let e=[],r=0;for(let i=0;i<t.length;++i){let a=t[i],s=this.textMap.get(a)??this.inverseSpecialTokens[a];s!=null&&(e.push(s),r+=s.length)}let n=new Uint8Array(r),o=0;for(let i of e)n.set(i,o),o+=i.length;return this.textDecoder.decode(n)}},jre=oAe;B6r(jre,"specialTokenRegex",t=>new RegExp(t.map(e=>z6r(e)).join("|"),"g"))});var xPt=w(()=>{SPt()});async function CPt(t){return t in Nre||(Nre[t]=H6r.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>new jre(e)).catch(e=>{throw delete Nre[t],e})),await Nre[t]}async function OPt(t){return CPt(iAe(t))}var Nre,H6r,aAe=w(()=>{xPt();QL();Nre={},H6r=new _m({})});function Wc(t){return typeof t!="object"||!t?!1:!!("type"in t&&t.type==="function"&&"function"in t&&typeof t.function=="object"&&t.function&&"name"in t.function&&"parameters"in t.function)}var V6r,W6r,dB,fB,r8=w(()=>{vPt();K2();NE();QL();aAe();Df();V6r=t=>t.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":t.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":t.startsWith("gpt-4-32k")?"gpt-4-32k":t.startsWith("gpt-4-")?"gpt-4":t.startsWith("gpt-4o")?"gpt-4o":t;W6r=()=>!1,dB=class extends Cn{get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.verbose=e.verbose??W6r(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}},fB=class extends dB{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}constructor({callbacks:e,callbackManager:r,...n}){let{cache:o,...i}=n;super({callbacks:e??r,...i}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_encoding",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof o=="object"?this.cache=o:o?this.cache=Rre.global():this.cache=void 0,this.caller=new _m(n??{})}async getNumTokens(e){if(typeof e!="string")return 0;let r=Math.ceil(e.length/4);if(!this._encoding)try{this._encoding=await OPt("modelName"in this?V6r(this.modelName):"gpt2")}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}if(this._encoding)try{r=this._encoding.encode(e).length}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}return r}static _convertInputToPromptValue(e){return typeof e=="string"?new rF(e):Array.isArray(e)?new nF(e.map(fy)):e}_identifyingParams(){return{}}_getSerializedCacheKey
`+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&i.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function iEt(t){var e,r,n,o;let i=[];if(!((r=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||r===void 0)&&r.parts)for(let a of(o=(n=t.candidates)===null||n===void 0?void 0:n[0].content)===null||o===void 0?void 0:o.parts)a.functionCall&&i.push(a.functionCall);if(i.length>0)return i}function qre(t){return!!t.finishReason&&p5r.includes(t.finishReason)}function IA(t){var e,r,n;let o="";if((!t.candidates||t.candidates.length===0)&&t.promptFeedback)o+="Response was blocked",!((e=t.promptFeedback)===null||e===void 0)&&e.blockReason&&(o+=` due to ${t.promptFeedback.blockReason}`),!((r=t.promptFeedback)===null||r===void 0)&&r.blockReasonMessage&&(o+=`: ${t.promptFeedback.blockReasonMessage}`);else if(!((n=t.candidates)===null||n===void 0)&&n[0]){let i=t.candidates[0];qre(i)&&(o+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(o+=`: ${i.finishMessage}`))}return o}function i8(t){return this instanceof i8?(this.v=t,this):new i8(t)}function m5r(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),o,i=[];return o={},a("next"),a("throw"),a("return"),o[Symbol.asyncIterator]=function(){return this},o;function a(f){n[f]&&(o[f]=function(p){return new Promise(function(m,h){i.push([f,p,m,h])>1||s(f,p)})})}function s(f,p){try{u(n[f](p))}catch(m){d(i[0][3],m)}}function u(f){f.value instanceof i8?Promise.resolve(f.value.v).then(l,c):d(i[0][2],f)}function l(f){s("next",f)}function c(f){s("throw",f)}function d(f,p){f(p),i.shift(),i.length&&s(i[0][0],i[0][1])}}function h5r(t){let e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),r=b5r(e),[n,o]=r.tee();return{stream:y5r(n),response:g5r(o)}}async function g5r(t){let e=[],r=t.getReader();for(;;){let{done:n,value:o}=await r.read();if(n)return bAe(_5r(e));e.push(o)}}function y5r(t){return m5r(this,arguments,function*(){let r=t.getReader();for(;;){let{value:n,done:o}=yield i8(r.read());if(o)break;yield yield i8(bAe(n))}})}function b5r(t){let e=t.getReader();return new ReadableStream({start(n){let o="";return i();function i(){return e.read().then(({value:a,done:s})=>{if(s){if(o.trim()){n.error(new ef("Failed to parse stream"));return}n.close();return}o+=a;let u=o.match(aEt),l;for(;u;){try{l=JSON.parse(u[1])}catch{n.error(new ef(`Error parsing JSON response: "${u[1]}"`));return}n.enqueue(l),o=o.substring(u[0].length),u=o.match(aEt)}return i()})}}})}function _5r(t){let e=t[t.length-1],r={promptFeedback:e?.promptFeedback};for(let n of t){if(n.candidates)for(let o of n.candidates){let i=o.index;if(r.candidates||(r.candidates=[]),r.candidates[i]||(r.candidates[i]={index:o.index}),r.candidates[i].citationMetadata=o.citationMetadata,r.candidates[i].groundingMetadata=o.groundingMetadata,r.candidates[i].finishReason=o.finishReason,r.candidates[i].finishMessage=o.finishMessage,r.candidates[i].safetyRatings=o.safetyRatings,o.content&&o.content.parts){r.candidates[i].content||(r.candidates[i].content={role:o.content.role||"user",parts:[]});let a={};for(let s of o.content.parts)s.text&&(a.text=s.text),s.functionCall&&(a.functionCall=s.functionCall),s.executableCode&&(a.executableCode=s.executableCode),s.codeExecutionResult&&(a.codeExecutionResult=s.codeExecutionResult),Object.keys(a).length===0&&(a.text=""),r.candidates[i].content.parts.push(a)}}n.usageMetadata&&(r.usageMetadata=n.usageMetadata)}return r}async function cEt(t,e,r,n){let o=await s8(e,kj.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(r),n);return h5r(o)}async function dEt(t,e,r,n){let i=await(await s8(e,kj.GENERATE_CONTENT,t,!1,JSON.stringify(r),n)).json();return{response:bAe(i)}}function fEt(t){if(t!=null){if(typeof t=="string")return{role:"system",parts:[{text:t}]};if(t.text)return{role:"system",parts:[t]};if(t.parts)return t.role?t:{role:"system",parts:t.parts}}}function a8(t){let e=[];if(typeof t=="string")e=[{text:t}];else for(let r of t)typeof r=="string"?e.push({text:r}):e.push(r);return v5r(e)}
`)===0?n.substr(1,n.length):n}).forEach(function(n){var o=n.split(":"),i=o.shift().trim();if(i){var a=o.join(":").trim();try{e.append(i,a)}catch(s){console.warn("Response "+s.message)}}}),e}function mx(t,e){if(!(this instanceof mx))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(e||(e={}),this.type="default",this.status=e.status===void 0?200:e.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=e.statusText===void 0?"":""+e.statusText,this.headers=new jl(e.headers),this.url=e.url||"",this._initBody(t)}function TEt(t,e){return new Promise(function(r,n){var o=new qj(t,e);if(o.signal&&o.signal.aborted)return n(new Bj("Aborted","AbortError"));var i=new XMLHttpRequest;function a(){i.abort()}i.onload=function(){var l={statusText:i.statusText,headers:U5r(i.getAllResponseHeaders()||"")};o.url.indexOf("file://")===0&&(i.status<200||i.status>599)?l.status=200:l.status=i.status,l.url="responseURL"in i?i.responseURL:l.headers.get("X-Request-URL");var c="response"in i?i.response:i.responseText;setTimeout(function(){r(new mx(c,l))},0)},i.onerror=function(){setTimeout(function(){n(new TypeError("Network request failed"))},0)},i.ontimeout=function(){setTimeout(function(){n(new TypeError("Network request timed out"))},0)},i.onabort=function(){setTimeout(function(){n(new Bj("Aborted","AbortError"))},0)};function s(l){try{return l===""&&Gc.location.href?Gc.location.href:l}catch{return l}}if(i.open(o.method,s(o.url),!0),o.credentials==="include"?i.withCredentials=!0:o.credentials==="omit"&&(i.withCredentials=!1),"responseType"in i&&(Zf.blob?i.responseType="blob":Zf.arrayBuffer&&(i.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof jl||Gc.Headers&&e.headers instanceof Gc.Headers)){var u=[];Object.getOwnPropertyNames(e.headers).forEach(function(l){u.push(gB(l)),i.setRequestHeader(l,CAe(e.headers[l]))}),o.headers.forEach(function(l,c){u.indexOf(c)===-1&&i.setRequestHeader(c,l)})}else o.headers.forEach(function(l,c){i.setRequestHeader(c,l)});o.signal&&(o.signal.addEventListener("abort",a),i.onreadystatechange=function(){i.readyState===4&&o.signal.removeEventListener("abort",a)}),i.send(typeof o._bodyInit>"u"?null:o._bodyInit)})}var Gc,Zf,xEt,OEt,$5r,z5r,Bj,AEt=w(()=>{Gc=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof window<"u"&&window||{},Zf={searchParams:"URLSearchParams"in Gc,iterable:"Symbol"in Gc&&"iterator"in Symbol,blob:"FileReader"in Gc&&"Blob"in Gc&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in Gc,arrayBuffer:"ArrayBuffer"in Gc};Zf.arrayBuffer&&(xEt=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],OEt=ArrayBuffer.isView||function(t){return t&&xEt.indexOf(Object.prototype.toString.call(t))>-1});jl.prototype.append=function(t,e){t=gB(t),e=CAe(e);var r=this.map[t];this.map[t]=r?r+", "+e:e};jl.prototype.delete=function(t){delete this.map[gB(t)]};jl.prototype.get=function(t){return t=gB(t),this.has(t)?this.map[t]:null};jl.prototype.has=function(t){return this.map.hasOwnProperty(gB(t))};jl.prototype.set=function(t,e){this.map[gB(t)]=CAe(e)};jl.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)};jl.prototype.keys=function(){var t=[];return this.forEach(function(e,r){t.push(r)}),OAe(t)};jl.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),OAe(t)};jl.prototype.entries=function(){var t=[];return this.forEach(function(e,r){t.push([r,e])}),OAe(t)};Zf.iterable&&(jl.prototype[Symbol.iterator]=jl.prototype.entries);$5r=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];qj.prototype.clone=function(){return new qj(this,{body:this._bodyInit})};EEt.call(qj.prototype);EEt.call(mx.pro
2025-07-05 20:48:33 +08:00
`);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(`
2025-07-12 10:26:56 +08:00
`).filter(i=>i!==""))try{yield JSON.parse(o)}catch{console.warn("invalid json: ",o)}},Z5r=t=>{if(!t)return REt;let e=t.includes("://");t.startsWith(":")&&(t=`http://127.0.0.1${t}`,e=!0),e||(t=`http://${t}`);let r=new URL(t),n=r.port;n||(e?n=r.protocol==="https:"?"443":"80":n=MEt);let o=`${r.protocol}//${r.hostname}:${n}${r.pathname}`;return o.endsWith("/")&&(o=o.slice(0,-1)),o},X5r=Object.defineProperty,Q5r=(t,e,r)=>e in t?X5r(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,EAe=(t,e,r)=>(Q5r(t,typeof e!="symbol"?e+"":e,r),r),bB=class{constructor(e){EAe(this,"config"),EAe(this,"fetch"),EAe(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e?.headers},e?.proxy||(this.config.host=Z5r(e?.host??REt)),this.fetch=e?.fetch??fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,r){r.stream=r.stream??!1;let n=`${this.config.host}/api/${e}`;if(r.stream){let i=new AbortController,a=await yB(this.fetch,n,r,{signal:i.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");let s=Y5r(a.body),u=new AAe(i,s,()=>{let l=this.ongoingStreamedRequests.indexOf(u);l>-1&&this.ongoingStreamedRequests.splice(l,1)});return this.ongoingStreamedRequests.push(u),u}return await(await yB(this.fetch,n,r,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!="string"){let r=new Uint8Array(e),n="",o=r.byteLength;for(let i=0;i<o;i++)n+=String.fromCharCode(r[i]);return btoa(n)}return e}async generate(e){return e.images&&(e.images=await Promise.all(e.images.map(this.encodeImage.bind(this)))),this.processStreamableRequest("generate",e)}async chat(e){if(e.messages)for(let r of e.messages)r.images&&(r.images=await Promise.all(r.images.map(this.encodeImage.bind(this))));return this.processStreamableRequest("chat",e)}async create(e){return this.processStreamableRequest("create",{...e})}async pull(e){return this.processStreamableRequest("pull",{name:e.model,stream:e.stream,insecure:e.insecure})}async push(e){return this.processStreamableRequest("push",{name:e.model,stream:e.stream,insecure:e.insecure})}async delete(e){return await J5r(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await yB(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await IEt(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await yB(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await yB(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await yB(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await IEt(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}},NAo=new bB});var jEt=w(()=>{Wb()});function NEt(t,e=0){return(Jc[t[e+0]]+Jc[t[e+1]]+Jc[t[e+2]]+Jc[t[e+3]]+"-"+Jc[t[e+4]]+Jc[t[e+5]]+"-"+Jc[t[e+6]]+Jc[t[e+7]]+"-"+Jc[t[e+8]]+Jc[t[e+9]]+"-"+Jc[t[e+10]]+Jc[t[e+11]]+Jc[t[e+12]]+Jc[t[e+13]]+Jc[t[e+14]]+Jc[t[e+15]]).toLowerCase()}var Jc,Jre,DEt=w(()=>{Jc=[];for(Jre=0;Jre<256;++Jre)Jc.push((Jre+256).toString(16).slice(1))});function RAe(){if(!Yre&&(Yre=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Yre))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Yre(eWr)}var Yre,eWr,LEt=w(()=>{eWr=new Uint8Array(16)});var tWr,jAe,FEt=w(()=>{tWr=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),jAe={randomUUID:tWr}});function rWr(t,e,r){if(jAe.randomUUID&&!e&&!t)return jAe.randomUUID();t=t||{};var n=t.random||(t.rng||RAe)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){r=r||0;for(var o=0;o<16;++o)e[r+o]=n[o];return e}return NEt(n)}var NAe,kEt=w(()=>{FEt();LEt();DEt();NAe=rWr});var $Et=w(
`):[]}};Gm=new WeakMap;Vj.NEWLINE_CHARS=new Set([`
`,"\r"]);Vj.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function YAe(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var fTt=w(()=>{});async function*SWr(t,e){if(!t.body)throw e.abort(),new vt("Attempted to iterate over a response with no body");let r=new ZAe,n=new Vj,o=YAe(t.body);for await(let i of xWr(o))for(let a of n.decode(i)){let s=r.decode(a);s&&(yield s)}for(let i of n.flush()){let a=r.decode(i);a&&(yield a)}}async function*xWr(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?new TextEncoder().encode(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let i;for(;(i=cTt(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function CWr(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var yx,ZAe,ane=w(()=>{c8();Kp();dTt();fTt();Vn();Kp();yx=class t{constructor(e,r){this.iterator=e,this.controller=r}static fromSSEResponse(e,r){let n=!1;async function*o(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let i=!1;try{for await(let a of SWr(e,r))if(!i){if(a.data.startsWith("[DONE]")){i=!0;continue}if(a.event===null||a.event.startsWith("response.")||a.event.startsWith("transcript.")){let s;try{s=JSON.parse(a.data)}catch(u){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),u}if(s&&s.error)throw new Ys(void 0,s.error,void 0,XAe(e.headers));yield s}else{let s;try{s=JSON.parse(a.data)}catch(u){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),u}if(a.event=="error")throw new Ys(void 0,s.error,s.message,void 0);yield{event:a.event,data:s}}}i=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{i||r.abort()}}return new t(o,r)}static fromReadableStream(e,r){let n=!1;async function*o(){let a=new Vj,s=YAe(e);for await(let u of s)for(let l of a.decode(u))yield l;for(let u of a.flush())yield u}async function*i(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{for await(let s of o())a||s&&(yield JSON.parse(s));a=!0}catch(s){if(s instanceof Error&&s.name==="AbortError")return;throw s}finally{a||r.abort()}}return new t(i,r)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),o=i=>({next:()=>{if(i.length===0){let a=n.next();e.push(a),r.push(a)}return i.shift()}});return[new t(()=>o(e),this.controller),new t(()=>o(r),this.controller)]}toReadableStream(){let e=this,r,n=new TextEncoder;return new HAe({async start(){r=e[Symbol.asyncIterator]()},async pull(o){try{let{value:i,done:a}=await r.next();if(a)return o.close();let s=n.encode(JSON.stringify(i)+`
`);o.enqueue(s)}catch(i){o.error(i)}},async cancel(){await r.return?.()}})}};ZAe=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=CWr(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function tIe(t,e,r){if(t=await t,mTt(t))return t;if(pTt(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=d8(o)?[await o.arrayBuffer()]:[o];return new tne(i,e,r)}let n=await PWr(t);if(e||(e=TWr(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new tne(n,e,r)}async function PWr(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(d8(t))e.push(await t.arrayBuffer());else if(AWr(t))for await(let r of t)e.push(r);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${EWr(t)}`);return e}function EWr(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function TWr(t){return QAe(t.name)||QAe(t.filename)||QAe(t.path)?.split(/[\\/]/).pop()}var pTt,mTt,d8,OWr,QAe,AWr,rIe,fg,hTt,eIe,sne=w(()=>{c8();c8();pTt=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",mTt=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&d8(t),d8=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",OWr=t=>mTt(t)||pTt(t)||KAe(t);QAe=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},AWr=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",rIe=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody",fg=async t=>{let e=await hTt(t.body);return VAe(e,t)},hTt=async t=>{let e=new zAe;return await Promise.all(Object.entries(t||{}).map(([r,n])=>eIe(e,r,n))),e},eIe=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(OWr(r)){let n=await tIe(r);t.append(e,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>eIe(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>eIe(t,`${e}[${n}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}}});async function wTt(t){let{response:e}=t;if(t.options.stream)return UO("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):yx.fromSSEResponse(e,t.controller);if(e.status===204)return null;if(t.options.__binaryResponse)return e;let n=e.headers.get("content-type")?.split(";")[0]?.trim();if(n?.includes("application/json")||n?.endsWith("+json")){let a=await e.json();return UO("response",e.status,e.url,e.headers,a),STt(a,e)}let i=await e.text();return UO("response",e.status,e.url,e.headers,i),i}function STt(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}function DWr(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let o=n[1]||0,i=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${i}.${a}`}}}return null}function xTt(t){if(!t)return!0;for(let e in t)return!1;return!0}function CTt(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function _Tt(t,e){for(let r
\r `.includes(t[n]);)n++};return a()},EIe=t=>YWr(t,oc.ALL^oc.NUM)});function XWr(t,e){let{id:r,choices:n,created:o,model:i,system_fingerprint:a,...s}=t,u={...s,id:r,choices:n.map(({message:l,finish_reason:c,index:d,logprobs:f,...p})=>{if(!c)throw new vt(`missing finish_reason for choice ${d}`);let{content:m=null,function_call:h,tool_calls:b,...g}=l,y=l.role;if(!y)throw new vt(`missing role for choice ${d}`);if(h){let{arguments:S,name:x}=h;if(S==null)throw new vt(`missing function_call.arguments for choice ${d}`);if(!x)throw new vt(`missing function_call.name for choice ${d}`);return{...p,message:{content:m,function_call:{arguments:S,name:x},role:y,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}return b?{...p,index:d,finish_reason:c,logprobs:f,message:{...g,role:y,content:m,refusal:l.refusal??null,tool_calls:b.map((S,x)=>{let{function:O,type:P,id:E,...A}=S,{arguments:I,name:R,...N}=O||{};if(E==null)throw new vt(`missing choices[${d}].tool_calls[${x}].id
${Sne(t)}`);if(P==null)throw new vt(`missing choices[${d}].tool_calls[${x}].type
${Sne(t)}`);if(R==null)throw new vt(`missing choices[${d}].tool_calls[${x}].function.name
${Sne(t)}`);if(I==null)throw new vt(`missing choices[${d}].tool_calls[${x}].function.arguments
${Sne(t)}`);return{...A,id:E,type:P,function:{...N,name:R,arguments:I}}})}}:{...p,message:{...g,content:m,role:y,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}),created:o,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};return jTt(u,e)}function Sne(t){return JSON.stringify(t)}var kB,Ti,Dl,WO,$B,kA,TIe,vne,AIe,IIe,MIe,wne,RIe,BTt,BB,jIe=w(()=>{Kp();CIe();ane();LB();$Tt();kB=function(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r},Ti=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},BB=class t extends FB{constructor(e){super(),Dl.add(this),WO.set(this,void 0),$B.set(this,void 0),kA.set(this,void 0),kB(this,WO,e,"f"),kB(this,$B,[],"f")}get currentChatCompletionSnapshot(){return Ti(this,kA,"f")}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createChatCompletion(e,r,n){let o=new t(r);return o._run(()=>o._runChatCompletion(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createChatCompletion(e,r,n){super._createChatCompletion;let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),Ti(this,Dl,"m",TIe).call(this);let i=await e.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let a of i)Ti(this,Dl,"m",AIe).call(this,a);if(i.controller.signal?.aborted)throw new Li;return this._addChatCompletion(Ti(this,Dl,"m",wne).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),Ti(this,Dl,"m",TIe).call(this),this._connected();let o=yx.fromReadableStream(e,this.controller),i;for await(let a of o)i&&i!==a.id&&this._addChatCompletion(Ti(this,Dl,"m",wne).call(this)),Ti(this,Dl,"m",AIe).call(this,a),i=a.id;if(o.controller.signal?.aborted)throw new Li;return this._addChatCompletion(Ti(this,Dl,"m",wne).call(this))}[(WO=new WeakMap,$B=new WeakMap,kA=new WeakMap,Dl=new WeakSet,TIe=function(){this.ended||kB(this,kA,void 0,"f")},vne=function(r){let n=Ti(this,$B,"f")[r.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},Ti(this,$B,"f")[r.index]=n,n)},AIe=function(r){if(this.ended)return;let n=Ti(this,Dl,"m",BTt).call(this,r);this._emit("chunk",r,n);for(let o of r.choices){let i=n.choices[o.index];o.delta.content!=null&&i.message?.role==="assistant"&&i.message?.content&&(this._emit("content",o.delta.content,i.message.content),this._emit("content.delta",{delta:o.delta.content,snapshot:i.message.content,parsed:i.message.parsed})),o.delta.refusal!=null&&i.message?.role==="assistant"&&i.message?.refusal&&this._emit("refusal.delta",{delta:o.delta.refusal,snapshot:i.message.refusal}),o.logprobs?.content!=null&&i.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:o.logprobs?.content,snapshot:i.logprobs?.content??[]}),o.logprobs?.refusal!=null&&i.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:o.logprobs?.refusal,snapshot:i.logprobs?.refusal??[]});let a=Ti(this,Dl,"m",vne).call(this,i);i.finish_reason&&(Ti(this,Dl,"m",MIe).call(this,i),a.current_tool_call_index!=null&&Ti(this,Dl,"m",IIe).call(this,i,a.current_tool_call_index));for(let s of o.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(Ti(this,Dl,"m",MIe).call(this,i),a.current_tool_call_index!=null&&Ti(this,Dl,"m",IIe).call(this,i,a.current_tool_call_index)),a.cur
2025-07-05 20:48:33 +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.,
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
2025-07-12 10:26:56 +08:00
`);super({baseURL:a.baseURL,timeout:a.timeout??6e5,httpAgent:a.httpAgent,maxRetries:a.maxRetries,fetch:a.fetch}),this.completions=new Qj(this),this.chat=new HO(this),this.embeddings=new eN(this),this.files=new BA(this),this.images=new aN(this),this.audio=new _x(this),this.moderations=new uN(this),this.models=new UA(this),this.fineTuning=new Yy(this),this.vectorStores=new Zm(this),this.beta=new Jy(this),this.batches=new DA(this),this.uploads=new WA(this),this.responses=new VA(this),this.evals=new xx(this),this._options=a,this.apiKey=r,this.organization=n,this.project=o}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return qAe(e,{arrayFormat:"brackets"})}};sAt=Wt;Wt.OpenAI=sAt;Wt.DEFAULT_TIMEOUT=6e5;Wt.OpenAIError=vt;Wt.APIError=Ys;Wt.APIConnectionError=qO;Wt.APIConnectionTimeoutError=Xf;Wt.APIUserAbortError=Li;Wt.NotFoundError=SB;Wt.ConflictError=xB;Wt.RateLimitError=OB;Wt.BadRequestError=_B;Wt.AuthenticationError=vB;Wt.InternalServerError=PB;Wt.PermissionDeniedError=wB;Wt.UnprocessableEntityError=CB;Wt.toFile=tIe;Wt.fileFromPath=rne;Wt.Completions=Qj;Wt.Chat=HO;Wt.ChatCompletionsPage=NA;Wt.Embeddings=eN;Wt.Files=BA;Wt.FileObjectsPage=nN;Wt.Images=aN;Wt.Audio=_x;Wt.Moderations=uN;Wt.Models=UA;Wt.ModelsPage=sN;Wt.FineTuning=Yy;Wt.VectorStores=Zm;Wt.VectorStoresPage=lN;Wt.VectorStoreSearchResponsesPage=cN;Wt.Beta=Jy;Wt.Batches=DA;Wt.BatchesPage=Wj;Wt.Uploads=WA;Wt.Responses=VA;Wt.Evals=xx;Wt.EvalListResponsesPage=rN;jne=class extends Wt{constructor({baseURL:e=MA("OPENAI_BASE_URL"),apiKey:r=MA("AZURE_OPENAI_API_KEY"),apiVersion:n=MA("OPENAI_API_VERSION"),endpoint:o,deployment:i,azureADTokenProvider:a,dangerouslyAllowBrowser:s,...u}={}){if(!n)throw new vt("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof a=="function"&&(s=!0),!a&&!r)throw new vt("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(a&&r)throw new vt("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(r??(r=aAt),u.defaultQuery={...u.defaultQuery,"api-version":n},e){if(o)throw new vt("baseURL and endpoint are mutually exclusive")}else{if(o||(o=process.env.AZURE_OPENAI_ENDPOINT),!o)throw new vt("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${o}/openai`}super({apiKey:r,baseURL:e,...u,...s!==void 0?{dangerouslyAllowBrowser:s}:{}}),this.apiVersion="",this._azureADTokenProvider=a,this.apiVersion=n,this.deploymentName=i}buildRequest(e,r={}){if(O9r.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!AB(e.body))throw new Error("Expected request body to be an object");let n=this.deploymentName||e.body.model||e.__metadata?.model;n!==void 0&&!this.baseURL.includes("/deployments")&&(e.path=`/deployments/${n}${e.path}`)}return super.buildRequest(e,r)}async _getAzureADToken(){if(typeof this._azureADTokenProvider=="function"){let e=await this._azureADTokenProvider();if(!e||typeof e!="string")throw new vt(`Expected 'azureADTokenProvider' argument to return a string but it returned ${e}`);return e}}authHeaders(e){return{}}async prepareOptions(e){if(e.headers?.["api-key"])return super.prepareOptions(e);let r=await this._getAzureADToken();if(e.headers??(e.headers={}),r)e.headers.Authorization=`Bearer ${r}`;else if(this.apiKey!==aAt)e.headers["api-key"]=this.apiKey;else throw new vt("Unable to handle auth");return super.prepareOptions(e)}},O9r=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations"]),aAt="<Missing Key>"});function Jp(t,e){if(t.function===void 0)return;let r;if(e?.part
`))}let n={name:t.function.name,args:r,type:"tool_call"};return e?.returnId&&(n.id=t.id),n}function Ox(t){if(t.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:t.id,type:"function",function:{name:t.name,arguments:JSON.stringify(t.args)}}}function Xm(t,e){return{name:t.function?.name,args:t.function?.arguments,id:t.id,error:e,type:"invalid_tool_call"}}var fMe,Zc,uAt=w(()=>{tF();bhe();$E();SR();fMe=class extends AR{static lc_name(){return"JsonOutputToolsParser"}constructor(e){super(e),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","openai_tools"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.returnId=e?.returnId??this.returnId}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,r=!0){let n=e[0].message,o;if(Oi(n)&&n.tool_calls?.length?o=n.tool_calls.map(a=>{let{id:s,...u}=a;return this.returnId?{id:s,...u}:u}):n.additional_kwargs.tool_calls!==void 0&&(o=JSON.parse(JSON.stringify(n.additional_kwargs.tool_calls)).map(s=>Jp(s,{returnId:this.returnId,partial:r}))),!o)return[];let i=[];for(let a of o)if(a!==void 0){let s={type:a.name,args:a.args,id:a.id};i.push(s)}return i}},Zc=class extends fMe{static lc_name(){return"JsonOutputKeyToolsParser"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","openai_tools"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"keyName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"returnSingle",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"zodSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){if(this.zodSchema===void 0)return e;let r=await this.zodSchema.safeParseAsync(e);if(r.success)return r.data;throw new vm(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(r.error.errors)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){let n=(await super.parsePartialResult(e)).filter(i=>i.type===this.keyName),o=n;if(n.length)return this.returnId||(o=n.map(i=>i.args)),this.returnSingle?o[0]:o}async parseResult(e){let n=(await super.parsePartialResult(e,!1)).filter(a=>a.type===this.keyName),o=n;return n.length?(this.returnId||(o=n.map(a=>a.args)),this.returnSingle?this._validateResult(o[0]):await Promise.all(o.map(a=>this._validateResult(a)))):void 0}}});var lAt=w(()=>{uAt()});var aq=w(()=>{lAt()});var dAt,cAt,fAt,Nne=w(()=>{dAt=Symbol("Let zodToJsonSchema decide on which parser to use"),cAt={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},fAt=t=>typeof t=="string"?{...cAt,basePath:["#"],definitions:{},name:t}:{...cAt,basePath:["#"],definitions:{},...t}});function pAt(t){if(!t)return!0;for(let e in t)return!1;return!0}var P8,pMe=w(()=>{P8=t=>"_def"in t?t._def:t});var mAt,mMe=w(()=>{Nne();pMe();mAt=t=>{let e=fAt(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[P8(o),{def:P8(o),path:[...e.ba
2025-07-05 20:48:33 +08:00
]))`;continue}else if(o[l]==="$"){i+=`($|(?=[\r
]))`;continue}}if(n.s&&o[l]==="."){i+=s?`${o[l]}\r
`:`[${o[l]}\r
2025-07-12 10:26:56 +08:00
]`;continue}i+=o[l],o[l]==="\\"?a=!0:s&&o[l]==="]"?s=!1:!s&&o[l]==="["&&(s=!0)}try{let l=new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return i}});function Fne(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===de.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:pr(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:pr(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===de.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(Dne(t.keyType._def,e)).reduce((o,[i,a])=>i==="type"?o:{...o,[i]:a},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===de.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}var kne=w(()=>{Td();Zs();Lne()});function EAt(t,e){if(e.mapStrategy==="record")return Fne(t,e);let r=pr(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=pr(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var IMe=w(()=>{Zs();kne()});function TAt(t){let e=t.values,n=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var MMe=w(()=>{});function AAt(){return{not:{}}}var RMe=w(()=>{});function IAt(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var jMe=w(()=>{});function RAt(t,e){if(e.target==="openApi3")return MAt(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in E8&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=E8[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((i,a,s)=>s.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return MAt(t,e)}var E8,MAt,$ne=w(()=>{Zs();E8={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};MAt=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>pr(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function jAt(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:E8[t.innerType._def.typeName],nullable:!0}:{type:[E8[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=pr(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=pr(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var NMe=w(()=>{Zs();$ne()});function NAt(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",hMe(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?Wn(r,"
This will become an error in a future version of the SDK.`),{properties:{...n.properties,[o]:s},required:i.isOptional()&&!e.openaiStrictMode?n.required:[...n.required,o]})},{properties:{},required:[]}),additionalProperties:A9r(t,e)};return r.required.length||delete r.required,r}var LMe=w(()=>{Zs()});var LAt,FMe=w(()=>{Zs();LAt=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return pr(t.innerType._def,e);let r=pr(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}}});var FAt,kMe=w(()=>{Zs();FAt=(t,e)=>{if(e.pipeStrategy==="input")return pr(t.in._def,e);if(e.pipeStrategy==="output")return pr(t.out._def,e);let r=pr(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=pr(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function kAt(t,e){return pr(t.type._def,e)}var $Me=w(()=>{Zs()});function $At(t,e){let n={type:"array",uniqueItems:!0,items:pr(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&Wn(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&Wn(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var BMe=w(()=>{JA();Zs()});function BAt(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>pr(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:pr(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>pr(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var qMe=w(()=>{Zs()});function qAt(){return{not:{}}}var UMe=w(()=>{});function UAt(){return{}}var zMe=w(()=>{});var zAt,HMe=w(()=>{Zs();zAt=(t,e)=>pr(t.innerType._def,e)});function pr(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==dAt)return a}if(n&&!r){let a=I9r(n,e);if(a!==void 0)return"$ref"in a&&e.seenRefs.add(a.$ref),a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let i=R9r(t,t.typeName,e,r);return i&&j9r(t,e,i),o.jsonSchema=i,i}var I9r,M9r,R9r,j9r,Zs=w(()=>{Td();gMe();yMe();bMe();_Me();vMe();wMe();xMe();CMe();OMe();PMe();EMe();TMe();IMe();MMe();RMe();jMe();NMe();DMe();LMe();FMe();kMe();$Me();kne();BMe();Lne();qMe();UMe();$ne();zMe();HMe();Nne();I9r=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":let r=t.path.slice(e.basePath.length+1).join("_");return r!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[r]=t.def),{$ref:[...e.basePath,e.definitionPath,r].join("/")};case"relative":return{$ref:M9r(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,o)=>e.currentPath[o]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},M9r=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},R9r=(t,e,r,n)=>{switch(e){case de.ZodString:return Dne(t,r);case de.ZodNumber:return NAt(t,r);case de.ZodObject:return DAt(t,r);case de.ZodBigInt:return yAt(t,r);case de.ZodBoolean:return bAt();case de.ZodDate:return SMe(t,r);case de.ZodUndefined:return qAt();case de.ZodNull:return IAt(r);case de.ZodArray:return gAt(t,r);case de.ZodUnion:case de.ZodDiscriminatedUnion:return RAt(t,r);case de.ZodIntersection:return CAt(t,r);case de.ZodTuple:return BAt(t,r);case de.ZodRecord:return Fne(t,r);case de.ZodLiteral:return OAt(t,r);case de.ZodEnum:return xAt(t);case de.ZodNativeEnum:return TAt(t);case de.ZodNullable:return jAt(t,r);case de.ZodOptional:return LAt(t,r);case de.ZodMap:return EAt(t,r);case de.ZodSet:return $At(t,r);case de.ZodLazy:return pr(t.getter()._def,r);case de.ZodPromise:return kAt(t,r);case de.ZodNaN:case de.ZodNever:return AAt();case de.ZodEffects:return SAt(t,r,n);case de.ZodAny:return hAt();case de.ZodUnknown:return UAt();case de.ZodDefault:return wAt(t,
2025-07-05 20:48:33 +08:00
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
2025-07-12 10:26:56 +08:00
`,t}var GAt=w(()=>{});function YO(t){let e;return t.constructor.name===Xf.name?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===Li.name?(e=new Error(t.message),e.name="AbortError"):t.status===400&&t.message.includes("tool_calls")?e=T8(t,"INVALID_TOOL_RESULTS"):t.status===401?e=T8(t,"MODEL_AUTHENTICATION"):t.status===429?e=T8(t,"MODEL_RATE_LIMIT"):t.status===404?e=T8(t,"MODEL_NOT_FOUND"):e=t,e}function VMe(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}var fN=w(()=>{pg();Km();Ec();mB();GAt()});function N9r(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function JAt(t){let e=["namespace functions {",""];for(let r of t)r.description&&e.push(`// ${r.description}`),Object.keys(r.parameters.properties??{}).length>0?(e.push(`type ${r.name} = (_: {`),e.push(YAt(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
`)}function YAt(t,e){let r=[];for(let[n,o]of Object.entries(t.properties??{}))o.description&&e<2&&r.push(`// ${o.description}`),t.required?.includes(n)?r.push(`${n}: ${qne(o,e)},`):r.push(`${n}?: ${qne(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
`)}function qne(t,e){if(N9r(t))return t.anyOf.map(r=>qne(r,e)).join(" | ");switch(t.type){case"string":return t.enum?t.enum.map(r=>`"${r}"`).join(" | "):"string";case"number":return t.enum?t.enum.map(r=>`${r}`).join(" | "):"number";case"integer":return t.enum?t.enum.map(r=>`${r}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",YAt(t,e+2),"}"].join(`
`);case"array":return t.items?`${qne(t.items,e)}[]`:"any[]";default:return""}}var ZAt=w(()=>{});function XAt(t,e){let r;return rc(t)?r=dx(t):r=t,e?.strict!==void 0&&(r.function.strict=e.strict),r}var QAt=w(()=>{Km();fN()});function D9r(t){return t.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}function GMe(t){let e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":{if(!Cs.isInstance(t))throw new Error("Invalid generic chat message");return D9r(t)}default:throw new Error(`Unknown message type: ${e}`)}}function KMe(t,e){return t.flatMap(r=>{let n=GMe(r);n==="system"&&JMe(e)&&(n="developer");let o={role:n,content:r.content};if(r.name!=null&&(o.name=r.name),r.additional_kwargs.function_call!=null&&(o.function_call=r.additional_kwargs.function_call,o.content=""),Oi(r)&&r.tool_calls?.length?(o.tool_calls=r.tool_calls.map(Ox),o.content=""):(r.additional_kwargs.tool_calls!=null&&(o.tool_calls=r.additional_kwargs.tool_calls),r.tool_call_id!=null&&(o.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio){let i={role:"assistant",audio:{id:r.additional_kwargs.audio.id}};return[o,i]}return o})}function eIt(t,e){return t.flatMap(r=>{let n=GMe(r);if(n==="system"&&JMe(e)&&(n="developer"),n==="function")throw new Error("Function messages are not supported in Responses API");if(n==="tool"){let i=r;return i.additional_kwargs?.type==="computer_call_output"?{type:"computer_call_output",output:(()=>{if(typeof i.content=="string")return{type:"computer_screenshot",image_url:i.content};if(Array.isArray(i.content)){let s=i.content.find(l=>l.type==="computer_screenshot");if(s)return s;let u=i.content.find(l=>l.type==="image_url");if(u)return{type:"computer_screenshot",image_url:typeof u.image_url=="string"?u.image_url:u.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:i.tool_call_id}:{type:"function_call_output",call_id:i.tool_call_id,id:i.id,output:typeof i.content!="string"?JSON.stringify(i.content):i.content}}if(n==="assistant"){let i=[];r.additional_kwargs.reasoning!=null&&(c=>typeof c=="object"&&c!=null&&"type"in c&&c.type==="reasoning")(r.additional_kwargs.reasoning)&&i.push(r.additional_kwargs.reasoning);let{content:a}=r;r.additional_kwargs.refusal!=null&&(typeof a=="string"&&(a=[{type:"output_text",text:a,annotations:[]}]),a=[...a,{type:"refusal",refusal:r.additional_kwargs.refusal}]),i.push({type:"message",role:"assistant",content:typeof a=="string"?a:a.flatMap(l=>l.type==="text"?{type:"output_text",text:l.text,annotations:l.annotations??[]}:l.type==="output_text"||l.type==="refusal"?l:[])});let s=r.additional_kwargs[lq];Oi(r)&&r.tool_calls?.length?i.push(...r.tool_calls.map(l=>({type:"function_call",name:l.name,arguments:JSON.stringify(l.args),call_id:l.id,id:s?.[l.id]}))):r.additional_kwargs.tool_calls!=null&&i.push(...r.additional_kwargs.tool_calls.map(l=>({type:"function_call",name:l.function.name,call_id:l.id,id:s?.[l.id],arguments:l.function.arguments})));let u=r.response_metadata.output?.length?r.response_metadata.output:r.additional_kwargs.tool_outputs;if(u!=null){let l=u,c=l?.filter(f=>f.type==="reasoning"),d=l?.filter(f=>f.type==="computer_call");c.length>0&&d.length>0&&i.push(...c),d.length>0&&i.push(...d)}return i}let o=typeof r.content=="string"?r.content:r.content.flatMap(i=>{if(i.type==="text")return{type:"input_text",text:i.text};if(i.type==="image_url"){let a=typeof i.image_url=="string"?i.image_url:i.image_url.url,s=typeof i.image_url=="string"?"auto":i.image_url.detail;return{type:"input_image",image_url:a,detail:s}}return i.type==="input_text"||i.type==="input_image"||i.type==="input_file"?i:[]});return n==="user"||n==="system"||n==="developer"?{type:"message",role:n,content:o}:(console.warn(`Unsupported role found when converting to OpenAI Responses API: ${n}`),[])})}fun
2025-07-05 20:48:33 +08:00
Details: ${m.message}`),new wR(h,JSON.stringify(e))}else{let m=oa(o,this.schema);if(!m.valid){let h="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(h=`${h}
Details: ${m.errors.map(b=>`${b.keywordLocation}: ${b.error}`).join(`
`)}`),new wR(h,JSON.stringify(e))}i=o}let a=CR(r),u=await Bs.configure(a.callbacks,this.callbacks,a.tags||n,this.tags,a.metadata,this.metadata,{verbose:this.verbose})?.handleToolStart(this.toJSON(),typeof e=="string"?e:JSON.stringify(e),a.runId,void 0,void 0,void 0,a.runName);delete a.runId;let l;try{l=await this._call(i,u,a)}catch(m){throw await u?.handleToolError(m),m}let c,d;if(this.responseFormat==="content_and_artifact")if(Array.isArray(l)&&l.length===2)[c,d]=l;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
2025-07-12 10:26:56 +08:00
Result: ${JSON.stringify(l)}`);else c=l;let f;RE(e)&&(f=e.id),!f&&U4e(a)&&(f=a.toolCall.id);let p=$9r({content:c,artifact:d,toolCallId:f,name:this.name});return await u?.handleToolEnd(p),p}},ZO=class extends Vne{constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:Wr.object({input:Wr.string().optional()}).transform(r=>r.input)})}call(e,r){let n=typeof e=="string"||e==null?{input:e}:e;return super.call(n,r)}},XMe=class extends ZO{static lc_name(){return"DynamicTool"}constructor(e){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}async call(e,r){let n=CR(r);return n.runName===void 0&&(n.runName=this.name),super.call(e,n)}async _call(e,r,n){return this.func(e,r,n)}},QMe=class extends Vne{static lc_name(){return"DynamicStructuredTool"}constructor(e){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}async call(e,r,n){let o=CR(r);return o.runName===void 0&&(o.runName=this.name),super.call(e,o,n)}_call(e,r,n){return this.func(e,r,n)}}});var ZA=w(()=>{lIt()});var eRe,cIt=w(()=>{Dn();pg();ZA();eRe=class extends ZO{static lc_name(){return"DallEAPIWrapper"}constructor(e){e?.responseFormat!==void 0&&["url","b64_json"].includes(e.responseFormat)&&(e.dallEResponseFormat=e.responseFormat,e.responseFormat="content"),super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"dalle_api_wrapper"}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:"A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description."}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"dall-e-3"}),Object.defineProperty(this,"style",{enumerable:!0,configurable:!0,writable:!0,value:"vivid"}),Object.defineProperty(this,"quality",{enumerable:!0,configurable:!0,writable:!0,value:"standard"}),Object.defineProperty(this,"n",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:"1024x1024"}),Object.defineProperty(this,"dallEResponseFormat",{enumerable:!0,configurable:!0,writable:!0,value:"url"}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let r=e?.apiKey??e?.openAIApiKey??ot("OPENAI_API_KEY"),n=e?.organization??ot("OPENAI_ORGANIZATION"),o={apiKey:r,organization:n,dangerouslyAllowBrowser:!0,baseURL:e?.baseUrl};this.client=new Wt(o),this.model=e?.model??e?.modelName??this.model,this.style=e?.style??this.style,this.quality=e?.quality??this.quality,this.n=e?.n??this.n,this.size=e?.size??this.size,this.dallEResponseFormat=e?.dallEResponseFormat??this.dallEResponseFormat,this.user=e?.user}processMultipleGeneratedUrls(e){return this.dallEResponseFormat==="url"?e.flatMap(r=>r.data.flatMap(o=>o.url?{type:"image_url",image_url:o.url}:[]).filter(o=>o!==void 0&&o.type==="image_url"&&typeof o.image_url=="string"&&o.image_url!==void 0)):e.flatMap(r=>r.data.flatMap(o=>o.b64_json?{type:"image_url",image_url:{url:o.b64_json}}:[]).filter(o=>o!==void 0&&o.type==="image_url"&&typeof o.image_url=="object"&&"url"in
2025-07-05 20:48:33 +08:00
without CORS Error: `+ei(n)+`
2025-07-12 10:26:56 +08:00
with CORS Error: `+ei(o);throw new Error(i)}}}}});function vIt(t){return t!==void 0&&A8.includes(t)?bIt[t]:void 0}var bIt,_It,A8,Zne=w(()=>{bIt={arabic:"ar",armenian:"am",bulgarian:"bg",danish:"dk",dutch:"nl",english:"en",finnish:"fi",french:"fr",german:"de",greek:"gr",hungarian:"hu",indian:"in",indonesian:"id",irish:"ie",italian:"it",lithuanian:"lt",nepali:"np",norwegian:"no",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"rs",slovenian:"ru",spanish:"es",swedish:"se",tamil:"ta",turkish:"tr",ukrainian:"uk",sanskrit:"sk"},_It={dutch:/[^A-Za-zàèéìòóù0-9_'-]+/gim,english:/[^A-Za-zàèéìòóù0-9_'-]+/gim,french:/[^a-z0-9äâàéèëêïîöôùüûœç-]+/gim,italian:/[^A-Za-zàèéìòóù0-9_'-]+/gim,norwegian:/[^a-z0-9_æøåÆØÅäÄöÖüÜ]+/gim,portuguese:/[^a-z0-9à-úÀ-Ú]/gim,russian:/[^a-z0-9а-яА-ЯёЁ]+/gim,spanish:/[^a-z0-9A-Zá-úÁ-ÚñÑüÜ]+/gim,swedish:/[^a-z0-9_åÅäÄöÖüÜ-]+/gim,german:/[^a-z0-9A-ZäöüÄÖÜß]+/gim,finnish:/[^a-z0-9äöÄÖ]+/gim,danish:/[^a-z0-9æøåÆØÅ]+/gim,hungarian:/[^a-z0-9áéíóöőúüűÁÉÍÓÖŐÚÜŰ]+/gim,romanian:/[^a-z0-9ăâîșțĂÂÎȘȚ]+/gim,serbian:/[^a-z0-9čćžšđČĆŽŠĐ]+/gim,turkish:/[^a-z0-9çÇğĞıİöÖşŞüÜ]+/gim,lithuanian:/[^a-z0-9ąčęėįšųūžĄČĘĖĮŠŲŪŽ]+/gim,arabic:/[^a-z0-9أ-ي]+/gim,nepali:/[^a-z0-9अ-ह]+/gim,irish:/[^a-z0-9áéíóúÁÉÍÓÚ]+/gim,indian:/[^a-z0-9अ-ह]+/gim,armenian:/[^a-z0-9ա-ֆ]+/gim,greek:/[^a-z0-9α-ωά-ώ]+/gim,indonesian:/[^a-z0-9]+/gim,ukrainian:/[^a-z0-9а-яА-ЯіїєІЇЄ]+/gim,slovenian:/[^a-z0-9螚ȎŠ]+/gim,bulgarian:/[^a-z0-9а-яА-Я]+/gim,tamil:/[^a-z0-9அ-ஹ]+/gim,sanskrit:/[^a-z0-9A-Zāīūṛḷṃṁḥśṣṭḍṇṅñḻḹṝ]+/gim},A8=Object.keys(bIt)});function ki(t,e){if(e.length<tRe)Array.prototype.push.apply(t,e);else{let r=e.length;for(let n=0;n<r;n+=tRe)Array.prototype.push.apply(t,e.slice(n,n+tRe))}}function OIt(t,...e){return t.replace(/%(?:(?<position>\d+)\$)?(?<width>-?\d*\.?\d*)(?<type>[dfs])/g,function(...r){let n=r[r.length-1],{width:o,type:i,position:a}=n,s=a?e[Number.parseInt(a)-1]:e.shift(),u=o===""?0:Number.parseInt(o);switch(i){case"d":return s.toString().padStart(u,"0");case"f":{let l=s,[c,d]=o.split(".").map(f=>Number.parseFloat(f));return typeof d=="number"&&d>=0&&(l=l.toFixed(d)),typeof c=="number"&&c>=0?l.toString().padStart(u,"0"):l.toString()}case"s":return u<0?s.toString().padEnd(-u," "):s.toString().padStart(u," ");default:return s}})}function H9r(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function V9r(){return typeof process<"u"&&process.release&&process.release.name==="node"}function CIt(){return BigInt(Math.floor(performance.now()*1e6))}function mN(t){return typeof t=="number"&&(t=BigInt(t)),t<wIt?`${t}ns`:t<SIt?`${t/wIt}\u03BCs`:t<xIt?`${t/SIt}ms`:`${t/xIt}s`}function Qy(){return H9r()?CIt():V9r()||typeof process<"u"&&typeof process?.hrtime?.bigint=="function"?process.hrtime.bigint():typeof performance<"u"?CIt():BigInt(0)}function I8(){return`${U9r}-${z9r++}`}function cq(t,e){return Object.hasOwn===void 0?Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0:Object.hasOwn(t,e)?t[e]:void 0}function PIt(t,e){return e[1]===t[1]?t[0]-e[0]:e[1]-t[1]}function dq(t){if(t.length===0)return[];if(t.length===1)return t[0];for(let r=1;r<t.length;r++)if(t[r].length<t[0].length){let n=t[0];t[0]=t[r],t[r]=n}let e=new Map;for(let r of t[0])e.set(r,1);for(let r=1;r<t.length;r++){let n=0;for(let o of t[r]){let i=e.get(o);i===r&&(e.set(o,i+1),n++)}if(n===0)return[]}return t[0].filter(r=>{let n=e.get(r);return n!==void 0&&e.set(r,0),n===t.length})}function Xne(t,e){let r={},n=e.length;for(let o=0;o<n;o++){let i=e[o],a=i.split("."),s=t,u=a.length;for(let l=0;l<u;l++)if(s=s[a[l]],typeof s=="object"){if(s!==null&&"lat"in s&&"lon"in s&&typeof s.lat=="number"&&typeof s.lon=="number"){s=r[i]=s;break}else if(!Array.isArray(s)&&s!==null&&l===u-1){s=void 0;break}}else if((s===null||typeof s!="object")&&l<u-1){s=void 0;break}typeof s<"u"&&(r[i]=s)}return r}function fq(t,e){return Xne(t,[e])[e]}functi
- `),G9r={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported.
2025-07-05 20:48:33 +08:00
Supported languages are:
2025-07-12 10:26:56 +08:00
- ${K9r}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmer property must be a function.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.oramasearch.com/open-source/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Custom stop words array must only contain strings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boost value must be a number greater than, or less than 0.",INVALID_FILTER_OPERATION:"You can only use one operation per filter, you requested %d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sort is disabled. Please read the documentation at https://docs.oramasearch for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead.
2025-07-05 20:48:33 +08:00
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
2025-07-12 10:26:56 +08:00
`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages."}});function EIt(t){return{raw:Number(t),formatted:mN(t)}}function TIt(t){if(t.id){if(typeof t.id!="string")throw qt("DOCUMENT_ID_MUST_BE_STRING",typeof t.id);return t.id}return I8()}function nRe(t,e){for(let[r,n]of Object.entries(e)){let o=t[r];if(!(typeof o>"u")&&!(n==="geopoint"&&typeof o=="object"&&typeof o.lon=="number"&&typeof o.lat=="number")&&!(n==="enum"&&(typeof o=="string"||typeof o=="number"))){if(n==="enum[]"&&Array.isArray(o)){let i=o.length;for(let a=0;a<i;a++)if(typeof o[a]!="string"&&typeof o[a]!="number")return r+"."+a;continue}if(XO(n)){let i=iRe(n);if(!Array.isArray(o)||o.length!==i)throw qt("INVALID_INPUT_VECTOR",r,i,o.length);continue}if(pq(n)){if(!Array.isArray(o))return r;let i=oRe(n),a=o.length;for(let s=0;s<a;s++)if(typeof o[s]!==i)return r+"."+s;continue}if(typeof n=="object"){if(!o||typeof o!="object")return r;let i=nRe(o,n);if(i)return r+"."+i;continue}if(typeof o!==n)return r}}}function AIt(t){return t==="geopoint"}function XO(t){return typeof t=="string"&&/^vector\[\d+\]$/.test(t)}function pq(t){return typeof t=="string"&&J9r[t]}function oRe(t){return Y9r[t]}function iRe(t){let e=Number(t.slice(7,-1));switch(!0){case isNaN(e):throw qt("INVALID_VECTOR_VALUE",t);case e<=0:throw qt("INVALID_VECTOR_SIZE",t);default:return e}}var J9r,Y9r,M8=w(()=>{ic();Ds();Ds();J9r={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},Y9r={"string[]":"string","number[]":"number","boolean[]":"boolean","enum[]":"enum"}});function IIt(){return{idToInternalId:new Map,internalIdToId:[],save:Z9r,load:X9r}}function Z9r(t){return{internalIdToId:t.internalIdToId}}function X9r(t,e){let{internalIdToId:r}=e;t.internalDocumentIDStore.idToInternalId.clear(),t.internalDocumentIDStore.internalIdToId=[];let n=r.length;for(let o=0;o<n;o++){let i=r[o];t.internalDocumentIDStore.idToInternalId.set(i,o+1),t.internalDocumentIDStore.internalIdToId.push(i)}}function wi(t,e){if(typeof e=="string"){let r=t.idToInternalId.get(e);if(r)return r;let n=t.idToInternalId.size+1;return t.idToInternalId.set(e,n),t.internalIdToId.push(e),n}return e>t.internalIdToId.length?wi(t,e.toString()):e}function hg(t,e){if(t.internalIdToId.length<e)throw new Error(`Invalid internalId ${e}`);return t.internalIdToId[e-1]}var gg=w(()=>{});function eKr(t,e){return{sharedInternalDocumentStore:e,docs:{},count:0}}function tKr(t,e){let r=wi(t.sharedInternalDocumentStore,e);return t.docs[r]}function rKr(t,e){let r=e.length,n=Array.from({length:r});for(let o=0;o<r;o++){let i=wi(t.sharedInternalDocumentStore,e[o]);n[o]=t.docs[i]}return n}function nKr(t){return t.docs}function oKr(t,e,r){let n=wi(t.sharedInternalDocumentStore,e);return typeof t.docs[n]<"u"?!1:(t.docs[n]=r,t.count++,!0)}function iKr(t,e){let r=wi(t.sharedInternalDocumentStore,e);return typeof t.docs[r]>"u"?!1:(delete t.docs[r],t.count--,!0)}function aKr(t){return t.count}function sKr(t,e){let r=e;return{docs:r.docs,count:r.count,sharedInternalDocumentStore:t}}function uKr(t){return{docs:t.docs,count:t.count}}function MIt(){return{create:eKr,get:tKr,getMultiple:rKr,getAll:nKr,store:oKr,remove:iKr,count:aKr,load:sKr,save:uKr}}var aRe=w(()=>{gg()});function jIt(t,e){let r=[],n=t.plugins?.length;if(!n)return r;for(let o=0;o<n;o++)try{let i=t.plugins[o];typeof i[e]=="function"&&r.push(i[e])}catch(i){throw console.error("Caught error in getAllPluginsByHook:",i),qt("PLUGIN_CRASHED")}return r}var RIt,NIt=w(()=>{ic();RIt=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeLoad","afterLoad","afterCreate"]});function eb(t,e,r,n){if(t.some(Qs))return(async()=>{for(let i of t)await i(e,r,n)})();for(let i of t)i(e,r,n)}function hN(t,e,r){if(t.some(Qs))return(async()=>{for(let o of t)await o(e,r)})();for(let o of
which is longer than the specified ${this.chunkSize}`),o.length>0)){let l=this.joinDocs(o,r);for(l!==null&&n.push(l);i>this.chunkOverlap||i+u+o.length*r.length>this.chunkSize&&i>0;)i-=await this.lengthFunction(o[0]),o.shift()}o.push(s),i+=u}let a=this.joinDocs(o,r);return a!==null&&n.push(a),n}},aie=class t extends HRe{static lc_name(){return"RecursiveCharacterTextSplitter"}constructor(e){super(e),Object.defineProperty(this,"separators",{enumerable:!0,configurable:!0,writable:!0,value:[`
2025-07-05 20:48:33 +08:00
`,`
`," ",""]}),this.separators=e?.separators??this.separators,this.keepSeparator=e?.keepSeparator??!0}async _splitText(e,r){let n=[],o=r[r.length-1],i;for(let l=0;l<r.length;l+=1){let c=r[l];if(c===""){o=c;break}if(e.includes(c)){o=c,i=r.slice(l+1);break}}let a=this.splitOnSeparator(e,o),s=[],u=this.keepSeparator?"":o;for(let l of a)if(await this.lengthFunction(l)<this.chunkSize)s.push(l);else{if(s.length){let c=await this.mergeSplits(s,u);n.push(...c),s=[]}if(!i)n.push(l);else{let c=await this._splitText(l,i);n.push(...c)}}if(s.length){let l=await this.mergeSplits(s,u);n.push(...l)}return n}async splitText(e){return this._splitText(e,this.separators)}static fromLanguage(e,r){return new t({...r,separators:t.getSeparatorsForLanguage(e)})}static getSeparatorsForLanguage(e){if(e==="cpp")return[`
class `,`
void `,`
int `,`
float `,`
double `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
`,`
`," ",""];if(e==="go")return[`
func `,`
var `,`
const `,`
type `,`
if `,`
for `,`
switch `,`
case `,`
`,`
`," ",""];if(e==="java")return[`
class `,`
public `,`
protected `,`
private `,`
static `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
`,`
`," ",""];if(e==="js")return[`
function `,`
const `,`
let `,`
var `,`
class `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
default `,`
`,`
`," ",""];if(e==="php")return[`
function `,`
class `,`
if `,`
foreach `,`
while `,`
do `,`
switch `,`
case `,`
`,`
`," ",""];if(e==="proto")return[`
message `,`
service `,`
enum `,`
option `,`
import `,`
syntax `,`
`,`
`," ",""];if(e==="python")return[`
class `,`
def `,`
def `,`
`,`
`," ",""];if(e==="rst")return[`
===
`,`
---
`,`
***
`,`
.. `,`
`,`
`," ",""];if(e==="ruby")return[`
def `,`
class `,`
if `,`
unless `,`
while `,`
for `,`
do `,`
begin `,`
rescue `,`
`,`
`," ",""];if(e==="rust")return[`
fn `,`
const `,`
let `,`
if `,`
while `,`
for `,`
loop `,`
match `,`
const `,`
`,`
`," ",""];if(e==="scala")return[`
class `,`
object `,`
def `,`
val `,`
var `,`
if `,`
for `,`
while `,`
match `,`
case `,`
`,`
`," ",""];if(e==="swift")return[`
func `,`
class `,`
struct `,`
enum `,`
if `,`
for `,`
while `,`
do `,`
switch `,`
case `,`
`,`
`," ",""];if(e==="markdown")return[`
## `,`
### `,`
#### `,`
##### `,`
###### `,"```\n\n",`
***
`,`
---
`,`
___
`,`
`,`
`," ",""];if(e==="latex")return[`
\\chapter{`,`
\\section{`,`
\\subsection{`,`
\\subsubsection{`,`
\\begin{enumerate}`,`
\\begin{itemize}`,`
\\begin{description}`,`
\\begin{list}`,`
\\begin{quote}`,`
\\begin{quotation}`,`
\\begin{verse}`,`
\\begin{verbatim}`,`
\\begin{align}`,"$$","$",`
`,`
`," ",""];if(e==="html")return["<body>","<div>","<p>","<br>","<li>","<h1>","<h2>","<h3>","<h4>","<h5>","<h6>","<span>","<table>","<tr>","<td>","<th>","<ul>","<ol>","<header>","<footer>","<nav>","<head>","<style>","<script>","<meta>","<title>"," ",""];if(e==="sol")return[`
pragma `,`
using `,`
contract `,`
interface `,`
library `,`
constructor `,`
type `,`
function `,`
event `,`
modifier `,`
error `,`
struct `,`
enum `,`
if `,`
for `,`
while `,`
do while `,`
assembly `,`
`,`
2025-07-12 10:26:56 +08:00
`," ",""];throw new Error(`Language ${e} is not supported.`)}}});var c1t=w(()=>{l1t()});var d1t=w(()=>{c1t()});var f1t=w(()=>{d1t()});var p1t=w(()=>{f1t()});var m1t,Ix,sie,h1t=w(()=>{$r();pN();yo();o1t();nr();yn();m1t=F(wq());p1t();Ix=require("obsidian");_g();sie=class{constructor(e,r,n){this.app=e;this.dbOps=r;this.embeddingsManager=n;this.state={isIndexingPaused:!1,isIndexingCancelled:!1,indexedCount:0,totalFilesToIndex:0,processedFiles:new Set,currentIndexingNotice:null,indexNoticeMessage:null};let o=ue();this.rateLimiter=new U8(o.embeddingRequestsPerMin),this.embeddingBatchSize=o.embeddingBatchSize,this.checkpointInterval=8*this.embeddingBatchSize,xa(async()=>{let i=ue();this.rateLimiter=new U8(i.embeddingRequestsPerMin),this.embeddingBatchSize=i.embeddingBatchSize,this.checkpointInterval=8*this.embeddingBatchSize})}async indexVaultToVectorStore(e){let r=[];try{let n=await this.embeddingsManager.getEmbeddingsAPI();if(!n)return console.error("Embedding instance not found."),0;await this.dbOps.checkAndHandleEmbeddingModelChange(n)&&(e=!0),e?(await this.dbOps.clearIndex(n),this.dbOps.clearFilesMissingEmbeddings()):await this.dbOps.garbageCollect();let i=await this.getFilesToIndex(e);if(i.length===0)return new Ix.Notice("Copilot vault index is up-to-date."),0;this.initializeIndexingState(i.length),this.createIndexingNotice(),this.dbOps.clearFilesMissingEmbeddings();let a=await this.prepareAllChunks(i);if(a.length===0)return new Ix.Notice("No valid content to index."),0;for(let s=0;s<a.length&&!this.state.isIndexingCancelled;s+=this.embeddingBatchSize){await this.handlePause();let u=a.slice(s,s+this.embeddingBatchSize);try{await this.rateLimiter.wait();let l=await n.embedDocuments(u.map(f=>f.content));if(!l||l.length!==u.length)throw new Error(`Embedding model returned ${l?.length??0} embeddings for ${u.length} documents`);for(let f=0;f<u.length;f++){let p=u[f],m=l[f];if(!m||!Array.isArray(m)||m.length===0){fe(`Invalid embedding for document ${p.fileInfo.path}: ${m}`),this.dbOps.markFileMissingEmbeddings(p.fileInfo.path);continue}try{await this.dbOps.upsert({...p.fileInfo,id:this.getDocHash(p.content),content:p.content,embedding:m,created_at:Date.now(),nchars:p.content.length}),this.state.processedFiles.add(p.fileInfo.path)}catch(h){this.handleError(h,{filePath:p.fileInfo.path,errors:r}),this.dbOps.markFileMissingEmbeddings(p.fileInfo.path);continue}}this.state.indexedCount=this.state.processedFiles.size,this.updateIndexingNoticeMessage();let c=Math.floor((this.state.indexedCount-u.length)/this.checkpointInterval);Math.floor(this.state.indexedCount/this.checkpointInterval)>c&&(await this.dbOps.saveDB(),console.log("Copilot index checkpoint save completed."))}catch(l){if(this.handleError(l,{filePath:u?.[0]?.fileInfo?.path,errors:r,batch:u}),this.isRateLimitError(l))break}}return this.finalizeIndexing(r),setTimeout(()=>{this.dbOps.saveDB().then(()=>{ie("Copilot index final save completed."),this.dbOps.checkIndexIntegrity().catch(s=>{fe("Background integrity check failed:",s)})}).catch(s=>{fe("Background save failed:",s)})},100),this.state.indexedCount}catch(n){return this.handleError(n),0}}async prepareAllChunks(e){let r=await this.embeddingsManager.getEmbeddingsAPI();if(!r)return console.error("Embedding instance not found."),[];let n=Xs.getModelName(r),o=aie.fromLanguage("markdown",{chunkSize:OVe}),i=[];for(let a of e){let s=await this.app.vault.cachedRead(a);if(!s?.trim())continue;let u=this.app.metadataCache.getFileCache(a),l={title:a.basename,path:a.path,embeddingModel:n,ctime:a.stat.ctime,mtime:a.stat.mtime,tags:u?.tags?.map(d=>d.tag)??[],extension:a.extension,metadata:{...u?.frontmatter??{},created:Vl(new Date(a.stat.ctime)).display,modified:Vl(new Date(a.stat.mtime)).display}};(await o.createDocuments([s],[],{chunkHeader:`
2025-07-05 20:48:33 +08:00
NOTE TITLE: [[${l.title}]]
METADATA:${JSON.stringify(l.metadata)}
NOTE BLOCK CONTENT:
2025-07-12 10:26:56 +08:00
`,appendChunkOverlapHeader:!0})).forEach(d=>{d.pageContent.trim()&&i.push({content:d.pageContent,fileInfo:l})})}return i}getDocHash(e){return(0,m1t.MD5)(e).toString()}async getFilesToIndex(e){let{inclusions:r,exclusions:n}=rf(),o=this.app.vault.getMarkdownFiles();if(e)return o.filter(c=>eu(c,r,n));let i=new Set(await this.dbOps.getIndexedFiles()),a=await this.dbOps.getLatestFileMtime(),s=new Set(this.dbOps.getFilesMissingEmbeddings()),u=new Set,l=new Set;for(let c of o){if(!eu(c,r,n))continue;let d=await this.app.vault.cachedRead(c);if(!d||d.trim().length===0){l.add(c.path);continue}let f=i.has(c.path),p=s.has(c.path);(!f||p||c.stat.mtime>a)&&u.add(c)}return ie([`Files to index: ${u.size}`,`Previously indexed: ${i.size}`,`Empty files skipped: ${l.size}`,`Files missing embeddings: ${s.size}`].join(`
`)),Array.from(u)}initializeIndexingState(e){this.state={isIndexingPaused:!1,isIndexingCancelled:!1,indexedCount:0,totalFilesToIndex:e,processedFiles:new Set,currentIndexingNotice:null,indexNoticeMessage:null}}createIndexingNotice(){let e=document.createDocumentFragment(),r=e.createEl("div",{cls:"copilot-notice-container"});this.state.indexNoticeMessage=r.createEl("div",{cls:"copilot-notice-message"}),this.updateIndexingNoticeMessage();let n=r.createEl("div",{cls:"copilot-notice-buttons"}),o=n.createEl("button");o.textContent="Pause",o.addEventListener("click",a=>{a.stopPropagation(),a.preventDefault(),this.state.isIndexingPaused?(this.resumeIndexing(),o.textContent="Pause"):(this.pauseIndexing(),o.textContent="Resume")});let i=n.createEl("button");return i.textContent="Stop",i.style.marginLeft="8px",i.addEventListener("click",a=>{a.stopPropagation(),a.preventDefault(),this.cancelIndexing()}),e.appendChild(this.state.indexNoticeMessage),e.appendChild(n),this.state.currentIndexingNotice=new Ix.Notice(e,0),this.state.currentIndexingNotice}async handlePause(){if(this.state.isIndexingPaused){for(;this.state.isIndexingPaused&&!this.state.isIndexingCancelled;)await new Promise(e=>setTimeout(e,100));if(!this.state.isIndexingCancelled){let e=await this.getFilesToIndex();if(e.length===0){console.log("No files to index after filter change, stopping indexing"),this.cancelIndexing(),new Ix.Notice("No files to index with current filters");return}this.state.totalFilesToIndex=e.length,console.log("Total files to index:",this.state.totalFilesToIndex),console.log("Files to index:",e),this.updateIndexingNoticeMessage()}}}pauseIndexing(){this.state.isIndexingPaused=!0}resumeIndexing(){this.state.isIndexingPaused=!1}updateIndexingNoticeMessage(){if(this.state.indexNoticeMessage){let e=this.state.isIndexingPaused?" (Paused)":"",r=["Copilot is indexing your vault...",`${this.state.indexedCount}/${this.state.totalFilesToIndex} files processed${e}`],n=ue(),o=bg(n.qaInclusions);o.length>0&&r.push(`Inclusions: ${o.join(", ")}`);let a=[...eie(this.app),...bg(n.qaExclusions)];a.length>0&&r.push(`Exclusions: ${a.join(", ")}`),this.state.indexNoticeMessage.textContent=r.join(`
`)}}isStringLengthError(e){if(!e)return!1;if(e instanceof RangeError&&e.message.toLowerCase().includes("string length"))return!0;let n=(e.message||e.toString()).toLowerCase();return n.includes("string length")||n.includes("rangeerror")}handleError(e,r){let n=r?.filePath;if(n?(r.batch?console.error("Batch processing error:",{error:e,batchSize:r.batch.length||0,firstChunk:r.batch[0]?{path:r.batch[0].fileInfo?.path,contentLength:r.batch[0].content?.length,hasFileInfo:!!r.batch[0].fileInfo}:"No chunks in batch",errorType:e?.constructor?.name,errorMessage:e?.message}):console.error(`Error indexing file ${n}:`,e),r.errors?.push(n)):console.error("Fatal error during indexing:",e),this.state.currentIndexingNotice&&this.state.currentIndexingNotice.hide(),this.isStringLengthError(e)){new Ix.Notice("Vault is too large for 1 partition, please increase the number of partitions in your Copilot QA settings!",1e4);return}if(this.isRateLimitError(e))return;let o=n?`Error indexing file ${n}. Check console for details.`:"Fatal error during indexing. Check console for details.";new Ix.Notice(o)}isRateLimitError(e){return e?.message?.includes?.("rate limit")||!1}finalizeIndexing(e){if(this.state.currentIndexingNotice&&this.state.currentIndexingNotice.hide(),this.state.isIndexingCancelled){new Ix.Notice("Indexing cancelled");return}e.length>0?new Ix.Notice(`Indexing completed with ${e.length} errors. Check console for details.`):new Ix.Notice("Indexing completed successfully!")}async reindexFile(e){try{let r=await this.embeddingsManager.getEmbeddingsAPI();if(!r)return;if(await this.dbOps.removeDocs(e.path),await this.dbOps.checkAndHandleEmbeddingModelChange(r)){await this.indexVaultToVectorStore(!0);return}let o=await this.prepareAllChunks([e]);if(o.length===0)return;let i=await r.embedDocuments(o.map(a=>a.content));for(let a=0;a<o.length;a++){let s=o[a];await this.dbOps.upsert({...s.fileInfo,id:this.getDocHash(s.content),content:s.content,embedding:i[a],created_at:Date.now(),nchars:s.content.length})}this.dbOps.markUnsavedChanges(),ue().debug&&console.log(`Reindexed file: ${e.path}`)}catch(r){this.handleError(r,{filePath:e.path})}}async cancelIndexing(){console.log("Indexing cancelled by user"),this.state.isIndexingCancelled=!0,await new Promise(e=>setTimeout(e,100)),this.state.currentIndexingNotice&&this.state.currentIndexingNotice.hide()}}});var g1t={};Cf(g1t,{default:()=>ma});var z8,ma,Mx=w(()=>{wT();pN();nr();z8=require("obsidian");rie();n1t();h1t();ma=class t{constructor(){this.embeddingsManager=Xs.getInstance(),this.dbOps=new eP(app),this.indexOps=new sie(app,this.dbOps,this.embeddingsManager),this.eventHandler=new nie(app,this.indexOps,this.dbOps),this.initializationPromise=this.initialize(),this.setupSettingsSubscription()}static getInstance(){return t.instance||(t.instance=new t),t.instance}setupSettingsSubscription(){this.lastKnownSettings={...ue()};let e=async()=>{let r=ue(),n=this.lastKnownSettings;if(this.lastKnownSettings={...r},r.enableIndexSync!==n?.enableIndexSync){let o=await this.dbOps.getDbPath();this.dbOps.getCurrentDbPath()!==o&&await this.dbOps.initializeDB(await this.embeddingsManager.getEmbeddingsAPI())}};xa(()=>{this.initializationPromise=e()})}async initialize(){try{let e=3;for(;e>0;)try{let r=await this.embeddingsManager.getEmbeddingsAPI();await this.dbOps.initializeDB(r);break}catch(r){if(r instanceof Rr&&r.message.includes("Vault adapter not available")&&(e--,e>0)){await new Promise(n=>setTimeout(n,100));continue}new z8.Notice("Failed to initialize vector store. Please make sure you have a valid API key for your embedding model and restart the plugin."),console.error("Failed to initialize vector store:",r);break}}catch(e){console.error("Failed to initialize vector store:",e)}}async waitForInitialization(){await this.initializationPromise}async indexVaultToVectorStore(e){return await this.waitForInitialization(),z8.Platform.isMobile&&ue().disableIndexOnMobile?(new z8.Notice("Indexing is disabled on mobile devices"),0):this.indexOps.indexVaultToVectorStore(e)}async clearIndex(){await this.waitForInitialization(),
${n}`:"";super(`${e}: Status ${o} Content-Type ${i} Body ${a}`),this.rawResponse=r,this.body=n,this.statusCode=o,this.contentType=i,this.name="SDKError"}};tse.SDKError=RNe});var z5=v(U5=>{"use strict";Object.defineProperty(U5,"__esModule",{value:!0});U5.EventStream=void 0;U5.discardSentinel=etn;var B5=10,q5=13,BLt=new Set([B5,q5]),Xen=[new Uint8Array([q5,B5,q5,B5]),new Uint8Array([q5,q5]),new Uint8Array([B5,B5])],NNe=class{constructor(e){this.stream=e.stream,this.decoder=e.decoder}async*[Symbol.asyncIterator](){let e=this.stream.getReader(),r=new Uint8Array([]),n=0;try{for(;;){let{done:o,value:i}=await e.read();if(o)break;let a=new Uint8Array(r.length+i.length);a.set(r),a.set(i,r.length),r=a;for(let s=n;s<r.length;s++){let u=qLt(r,s);if(u==null)continue;let l=r.slice(n,s);n=s+u.length;let c=DNe(l,this.decoder);c!=null&&(yield c)}n>0&&(r=r.slice(n),n=0)}if(r.length>0){let o=DNe(r,this.decoder);o!=null&&(yield o)}}catch(o){if(o instanceof Error&&o.name==="AbortError")return;throw o}finally{e.releaseLock()}}};U5.EventStream=NNe;function qLt(t,e){let r=t[e],n=t[e+1];if(r==null||n==null||!BLt.has(r)||!BLt.has(n))return null;for(let o of Xen){let i=Qen(e,t,o);if(i!=null)return i}return null}function Qen(t,e,r){if(r.length>e.length-t)return null;for(let n=0;n<r.length;n++)if(e[t+n]!==r[n])return null;return r}function DNe(t,e){if(!t.length)return null;let o=new TextDecoder().decode(t).split(/\r?\n|\r/g),i=!1,a={};for(let s of o){if(!s)continue;let u=s.indexOf(":");if(u===0)continue;let l=u>0?s.substring(0,u):"",c=u>0?s.substring(u+1):"";switch(c.charAt(0)===" "&&(c=c.substring(1)),l){case"event":{i=!0,a.event=c;break}case"data":{i=!0,a.data??(a.data=""),a.data+=c+`
`;break}case"id":{i=!0,a.id=c;break}case"retry":{let d=parseInt(c,10);Number.isNaN(d)||(i=!0,a.retry=d);break}}}return i?(a.data!=null&&(a.data=a.data.slice(0,-1)),e(a)):null}function etn(t,e){return new ReadableStream({async start(r){let n=new Uint8Array([]),o=0,i=!1,a=!1,s=t.getReader();try{for(;!i;){let u=await s.read(),l=u.value;if(i=i||u.done,a||typeof l>"u")continue;let c=new Uint8Array(n.length+l.length);c.set(n),c.set(l,n.length),n=c;for(let d=o;d<n.length;d++){let f=qLt(n,d);if(f==null)continue;let p=o,m=n.slice(p,d);o=d+f.length,DNe(m,ttn)?.data===e?(r.enqueue(n.slice(0,p)),a=!0):(r.enqueue(n.slice(0,o)),n=n.slice(o),o=0)}}}catch(u){r.error(u)}finally{r.close(),s.releaseLock()}}})}function ttn(t){return t}});var kNe=v(db=>{"use strict";var rtn=db&&db.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),ntn=db&&db.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),otn=db&&db.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&rtn(e,t,r);return ntn(e,t),e};Object.defineProperty(db,"__esModule",{value:!0});db.SDKValidationError=void 0;db.formatZodError=FNe;var itn=otn(Te()),LNe=class extends Error{constructor(e,r,n){super(`${e}: ${r}`),this.name="SDKValidationError",this.cause=r,this.rawValue=n,this.rawMessage=e}pretty(){return this.cause instanceof itn.ZodError?`${this.rawMessage}
${FNe(this.cause)}`:this.toString()}};db.SDKValidationError=LNe;function FNe(t,e=0){let r=" ".repeat(e);r=e>0?`\u2502${r}`:r,r+=" ".repeat(e);let n="",o=s=>n+=`
${r}${s}`,i=t.issues.length,a=i===1?`${i} issue found`:`${i} issues found`;i&&o(`\u250C ${a}:`);for(let s of t.issues){let u=s.path.join(".");switch(u=u?`<root>.${u}`:"<root>",o(`\u2502 \u2022 [${u}]: ${s.message} (${s.code})`),s.code){case"invalid_literal":case"invalid_type":{o(`\u2502 Want: ${s.expected}`),o(`\u2502 Got: ${s.received}`);break}case"unrecognized_keys":{o(`\u2502 Keys: ${s.keys.join(", ")}`);break}case"invalid_enum_value":{o(`\u2502 Allowed: ${s.options.join(", ")}`),o(`\u2502 Got: ${s.received}`);break}case"invalid_union_discriminator":{o(`\u2502 Allowed: ${s.options.join(", ")}`);break}case"invalid_union":{let l=s.unionErrors.length;o(`\u2502 \u2716\uFE0E Attemped to deserialize into one of ${l} union members:`),s.unionErrors.forEach((c,d)=>{o(`\u2502 \u2716\uFE0E Member ${d+1} of ${l}`),o(`${FNe(c,e+1)}`)})}}}return t.issues.length&&o("\u2514\u2500*"),n.slice(1)}});var ve=v(H5=>{"use strict";Object.defineProperty(H5,"__esModule",{value:!0});H5.parse=stn;H5.safeParse=utn;H5.collectExtraKeys=ltn;var atn=Te(),zLt=kNe(),ULt=Ig();function stn(t,e,r){try{return e(t)}catch(n){throw n instanceof atn.ZodError?new zLt.SDKValidationError(r,n,t):n}}function utn(t,e,r){try{return(0,ULt.OK)(e(t))}catch(n){return(0,ULt.ERR)(new zLt.SDKValidationError(r,n,t))}}function ltn(t,e,r){return t.transform(n=>{let o={},{shape:i}=t;for(let[a]of Object.entries(n)){if(a in i)continue;let s=n[a];typeof s>"u"||(o[a]=s,delete n[a])}return r&&Object.keys(o).length===0?n:{...n,[e]:o}})}});var ai=v(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});hc.jsonErr=ftn;hc.json=ptn;hc.textErr=mtn;hc.text=htn;hc.bytesErr=gtn;hc.bytes=ytn;hc.streamErr=btn;hc.stream=_tn;hc.sseErr=vtn;hc.sse=wtn;hc.nilErr=Stn;hc.nil=xtn;hc.fail=Ctn;hc.match=Otn;hc.unpackHeaders=rse;hc.discardResponseBody=GLt;var HLt=jNe(),ctn=z5(),VLt=F5(),WLt=CNe(),KLt=ve(),dtn={json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function ftn(t,e,r){return{...r,err:!0,enc:"json",codes:t,schema:e}}function ptn(t,e,r){return{...r,enc:"json",codes:t,schema:e}}function mtn(t,e,r){return{...r,err:!0,enc:"text",codes:t,schema:e}}function htn(t,e,r){return{...r,enc:"text",codes:t,schema:e}}function gtn(t,e,r){return{...r,err:!0,enc:"bytes",codes:t,schema:e}}function ytn(t,e,r){return{...r,enc:"bytes",codes:t,schema:e}}function btn(t,e,r){return{...r,err:!0,enc:"stream",codes:t,schema:e}}function _tn(t,e,r){return{...r,enc:"stream",codes:t,schema:e}}function vtn(t,e,r){return{...r,err:!0,enc:"sse",codes:t,schema:e}}function wtn(t,e,r){return{...r,enc:"sse",codes:t,schema:e}}function Stn(t,e,r){return{...r,err:!0,enc:"nil",codes:t,schema:e}}function xtn(t,e,r){return{...r,enc:"nil",codes:t,schema:e}}function Ctn(t){return{enc:"fail",codes:t}}function Otn(...t){return async function(r,n){let o,i;for(let l of t){let{codes:c}=l,d="ctype"in l?l.ctype:dtn[l.enc];if(d&&(0,VLt.matchResponse)(r,c,d)){i=l;break}else if(!d&&(0,VLt.matchStatusCode)(r,c)){i=l;break}}if(!i){let l=await r.text();return[{ok:!1,error:new HLt.SDKError("Unexpected API response status or content-type",r,l)},l]}let a=i.enc;switch(a){case"json":o=await r.json();break;case"bytes":o=new Uint8Array(await r.arrayBuffer());break;case"stream":o=r.body;break;case"text":o=await r.text();break;case"sse":o=r.body&&i.sseSentinel?(0,ctn.discardSentinel)(r.body,i.sseSentinel):r.body;break;case"nil":o=await GLt(r);break;case"fail":o=await r.text();break;default:throw new Error(`Unsupported response type: ${a}`)}if(i.enc==="fail")return[{ok:!1,error:new HLt.SDKError("API error occurred",r,typeof o=="string"?o:"")},o];let s=i.key||n?.resultKey,u;if("err"in i?u={...n?.extraFields,...i.hdrs?{Headers:rse(r.headers)}:null,...(0,WLt.isPlainObject)(o)?o:null}:s?u={...n?.extraFields,...i.hdrs?{Headers:rse(r.headers)}:null,[s]:o}:i.hdrs?u={...n?.extraFields,...i.hdrs?{Headers:rse(r.headers)}:null,...(0,WLt.isPlainObject)(o)?o:null}:u=o,"err"in i){let l=(0,KLt.safeParse)(u,c=>i.schema.parse(c),"Respon
2025-07-05 20:48:33 +08:00
]))`;continue}else if(n[u]==="$"){o+=`($|(?=[\r
]))`;continue}}if(r.s&&n[u]==="."){o+=a?`${n[u]}\r
`:`[${n[u]}\r
2025-07-12 10:26:56 +08:00
]`;continue}o+=n[u],n[u]==="\\"?i=!0:a&&n[u]==="]"?a=!1:!a&&n[u]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}});var Yue=v(Jue=>{"use strict";Object.defineProperty(Jue,"__esModule",{value:!0});Jue.parseRecordDef=void 0;var nW=Te(),T2t=ml(),Yhn=Gue(),Zhn=Bue();function Xhn(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===nW.ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:(0,T2t.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:(0,T2t.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===nW.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=(0,Yhn.parseStringDef)(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===nW.ZodFirstPartyTypeKind.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===nW.ZodFirstPartyTypeKind.ZodBranded&&t.keyType._def.type._def.typeName===nW.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=(0,Zhn.parseBrandedDef)(t.keyType._def,e);return{...r,propertyNames:o}}}return r}Jue.parseRecordDef=Xhn});var UDe=v(Zue=>{"use strict";Object.defineProperty(Zue,"__esModule",{value:!0});Zue.parseMapDef=void 0;var A2t=ml(),Qhn=Yue();function egn(t,e){if(e.mapStrategy==="record")return(0,Qhn.parseRecordDef)(t,e);let r=(0,A2t.parseDef)(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=(0,A2t.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}Zue.parseMapDef=egn});var zDe=v(Xue=>{"use strict";Object.defineProperty(Xue,"__esModule",{value:!0});Xue.parseNativeEnumDef=void 0;function tgn(t){let e=t.values,n=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}Xue.parseNativeEnumDef=tgn});var HDe=v(Que=>{"use strict";Object.defineProperty(Que,"__esModule",{value:!0});Que.parseNeverDef=void 0;function rgn(){return{not:{}}}Que.parseNeverDef=rgn});var VDe=v(ele=>{"use strict";Object.defineProperty(ele,"__esModule",{value:!0});ele.parseNullDef=void 0;function ngn(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}ele.parseNullDef=ngn});var tle=v(GI=>{"use strict";Object.defineProperty(GI,"__esModule",{value:!0});GI.parseUnionDef=GI.primitiveMappings=void 0;var ogn=ml();GI.primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ign(t,e){if(e.target==="openApi3")return I2t(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in GI.primitiveMappings&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=GI.primitiveMappings[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((i,a,s)=>s.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(n=>n._
`),r=[],n="",o="",i="";for(let a of e)a.startsWith("**user**:")||a.startsWith("**ai**:")?(n&&o&&r.push({sender:n===Pi?Pi:e_,message:o.trim(),isVisible:!0,timestamp:i?Qhe(i):null}),n=a.startsWith("**user**:")?Pi:e_,o=a.substring(a.indexOf(":")+1).trim(),i=""):a.startsWith("[Timestamp:")?i=a.substring(11,a.length-1).trim():o+=`
`+a;return n&&o&&r.push({sender:n===Pi?Pi:e_,message:o.trim(),isVisible:!0,timestamp:i?Qhe(i):null}),r}async function vN(t,e){await e.clearChatMemory();for(let r=0;r<t.length-1;r++){let n=t[r];if(n.sender===Pi){let o=t[r+1];o?.sender===e_&&await e.getMemory().saveContext({input:n.message},{output:o.message})}}}$r();yo();yo();yn();var wN=require("obsidian"),Rx=class{static async isImageUrl(e,r){try{let n,o=!1;try{let i=new URL(e),a=i.pathname,s=a.lastIndexOf("."),u=a.lastIndexOf("/");if(s>u&&s>-1&&(n=a.substring(s+1).toLowerCase()),n&&!this.IMAGE_EXTENSIONS.some(c=>c.toLowerCase()===`.${n}`))return fe(`Unsupported image format from URL path: .${n}. Supported formats: ${this.IMAGE_EXTENSIONS.join(", ")}`,e),!1;try{let c=(await Us(e,{method:"HEAD",headers:{}})).headers.get("content-type");return c?.startsWith("image/")?!0:(console.warn(`HEAD request succeeded for ${e} but Content-Type (${c}) is not image/*.`),!1)}catch(l){console.warn(`HEAD request failed for URL: ${e}. Proceeding to heuristic check.`,l);let c=i.searchParams,f=[c.has("w")||c.has("width"),c.has("h")||c.has("height"),c.has("format"),c.has("fit"),c.has("quality"),i.pathname.includes("/image/"),i.pathname.includes("/images/"),i.pathname.includes("/img/"),c.has("auto"),c.has("crop")].filter(Boolean).length;return f>=2?(fe(`Identified as image based on URL heuristics (indicator count: ${f}): ${e}`),!0):!1}}catch{o=!0;let i=e.lastIndexOf(".");if(i>-1)n=e.substring(i+1).toLowerCase();else return!1}if(o)if(n&&this.IMAGE_EXTENSIONS.some(i=>i.toLowerCase()===`.${n}`)){let i=r.getAbstractFileByPath(e);return i instanceof wN.TFile?i.stat.size>this.MAX_IMAGE_SIZE?(fe(`Vault file too large: ${i.stat.size} bytes for path: ${e}`),!1):!0:(fe(`File with image extension not found in vault: ${e}.`),!1)}else return n&&fe(`Unsupported image format for potential vault path: .${n}. Supported formats: ${this.IMAGE_EXTENSIONS.join(", ")}`,e),!1;return fe(`Could not determine image status for URL/path: ${e}`),!1}catch(n){return fe(`Unexpected error in isImageUrl for "${e}":`,n),!1}}static async handleVaultImage(e,r){try{if(e.stat.size>this.MAX_IMAGE_SIZE)return fe(`Image too large: ${e.stat.size} bytes, skipping: ${e.path}`),null;let n=await r.readBinary(e),o=await this.getMimeType(n,e.extension);if(!o.startsWith("image/"))return fe(`Invalid MIME type: ${o}, skipping: ${e.path}`),null;let a=Buffer.from(n).toString("base64");return`data:${o};base64,${a}`}catch(n){return fe("Error processing vault image:",n),null}}static async handleWebImage(e){try{let r=await Us(e,{method:"GET",headers:{}});if(!r.ok)return fe(`Failed to fetch image: ${r.statusText}, URL: ${e}`),null;let n=r.headers.get("content-type");if(!n?.startsWith("image/"))return fe(`Invalid content type: ${n}, URL: ${e}`),null;let o=await r.arrayBuffer();if(o.byteLength>this.MAX_IMAGE_SIZE)return fe(`Image too large: ${o.byteLength} bytes, URL: ${e}`),null;let a=Buffer.from(o).toString("base64");return`data:${n};base64,${a}`}catch(r){return fe("Error converting web image to base64:",r),null}}static async handleLocalImage(e,r){try{let n=decodeURIComponent(e.replace("app://","")),o=r.getAbstractFileByPath(n);if(!o||!(o instanceof wN.TFile))return fe(`Local image not found: ${n}`),null;if(o.stat.size>this.MAX_IMAGE_SIZE)return fe(`Image too large: ${o.stat.size} bytes, path: ${n}`),null;let i=await r.readBinary(o),a=await this.getMimeType(i,o.extension);if(!a.startsWith("image/"))return fe(`Invalid MIME type: ${a}, path: ${n}`),null;let u=Buffer.from(i).toString("base64");return`data:${a};base64,${u}`}catch(n){return fe("Error processing local image:",n),null}}static async imageToBase64(e,r){if(e.startsWith("data:"))return e;if(e.startsWith("attachment:")){let o=e.substring(11),i=r.getAbstractFileByPath(o);return i instanceof wN.TFile?await this.handleVaultImage(i,r):(console.warn(`Could not find attachment file in vault: ${o}`),null)}if(e.startsWith("app://"))return await this.handleLocalImage(e,r);let n=r.getAbstractFileByPath(e);return n instanceof wN.TFile?await this.handleVaultImage(n,r):await this.handleWebImage(e)}static as
2025-07-05 20:48:33 +08:00
${e.join(`
2025-07-12 10:26:56 +08:00
`)}`)}};mg();yn();var Oq=class t{constructor(){this.mentions=new Map,this.brevilabsClient=Fi.getInstance()}static getInstance(){return t.instance||(t.instance=new t),t.instance}extractAllUrls(e){let r=/https?:\/\/[^\s"'<>]+/g;return(e.match(r)||[]).map(n=>n.replace(/,+$/,"")).filter((n,o,i)=>i.indexOf(n)===o)}extractUrls(e){let r=/https?:\/\/[^\s"'<>]+/g;return(e.match(r)||[]).map(n=>n.replace(/,+$/,"")).filter((n,o,i)=>i.indexOf(n)===o).filter(n=>!bVe(n))}async processUrl(e){try{return await this.brevilabsClient.url4llm(e)}catch(r){return console.error(`Error processing URL ${e}:`,r),{response:e,elapsed_time_ms:0}}}async processUrls(e){let r=this.extractUrls(e),n="",o=[];if(r.length===0)return{urlContext:"",imageUrls:[]};let i=r.map(async s=>{if(await Rx.isImageUrl(s,app.vault))return o.push(s),null;if(!this.mentions.has(s)){let u=await this.processUrl(s);this.mentions.set(s,{type:"url",original:s,processed:u.response})}return this.mentions.get(s)});return(await Promise.all(i)).forEach(s=>{s?.processed&&(n+=`
2025-07-05 20:48:33 +08:00
Content from ${s.original}:
2025-07-12 10:26:56 +08:00
${s.processed}`)}),{urlContext:n,imageUrls:o}}getMentions(){return this.mentions}clearMentions(){this.mentions.clear()}};_g();nr();yo();var A1t=F(wq()),cie=class t{constructor(){this.cacheDir=".copilot/pdf-cache"}static getInstance(){return t.instance||(t.instance=new t),t.instance}async ensureCacheDir(){await app.vault.adapter.exists(this.cacheDir)||(ie("Creating PDF cache directory:",this.cacheDir),await app.vault.adapter.mkdir(this.cacheDir))}getCacheKey(e){let r=`${e.path}:${e.stat.size}:${e.stat.mtime}`,n=(0,A1t.MD5)(r).toString();return ie("Generated cache key for PDF:",{path:e.path,key:n}),n}getCachePath(e){return`${this.cacheDir}/${e}.json`}async get(e){try{let r=this.getCacheKey(e),n=this.getCachePath(r);if(await app.vault.adapter.exists(n)){ie("Cache hit for PDF:",e.path);let o=await app.vault.adapter.read(n);return JSON.parse(o)}return ie("Cache miss for PDF:",e.path),null}catch(r){return fe("Error reading from PDF cache:",r),null}}async set(e,r){try{await this.ensureCacheDir();let n=this.getCacheKey(e),o=this.getCachePath(n);ie("Caching PDF response for:",e.path),await app.vault.adapter.write(o,JSON.stringify(r))}catch(n){fe("Error writing to PDF cache:",n)}}async clear(){try{if(await app.vault.adapter.exists(this.cacheDir)){let e=await app.vault.adapter.list(this.cacheDir);ie("Clearing PDF cache, removing files:",e.files.length);for(let r of e.files)await app.vault.adapter.remove(r)}}catch(e){fe("Error clearing PDF cache:",e)}}};yo();function xN(t){if(!t||typeof t!="object")return!1;let e=t.message||t.toString();return e.includes("Request rate limit exceeded")||e.includes("RATE_LIMIT_EXCEEDED")||e.includes("429")||t.status===429}function I1t(t){let r=(t?.message||t?.toString()||"").match(/Try again in ([\d\w\s]+)/);return r?r[1]:"some time"}var j1t=require("obsidian");var M1t=require("obsidian");var fie,R1t,die=class{constructor(e){this.vault=e;hUe(this,fie)}async load(e){let r=await this.vault.read(e),{nodes:n=[],edges:o=[]}=JSON.parse(r),i=await Promise.all(n.map(async u=>{if(u.type==="file"&&u.file){let l=this.vault.getAbstractFileByPath(u.file),c=l instanceof M1t.TFile?await this.vault.cachedRead(l):"";return{...u,content:c}}return u.type==="text"?{...u,content:u.text??""}:{...u,content:""}})),a=[...o];gUe(this,fie,R1t).call(this,i,a);let s=Object.fromEntries(i.map(u=>[u.id,u]));return{nodes:i,edges:a,byId:s}}buildPrompt(e){let r=new Map,n=e.nodes.filter(s=>s.type==="group");for(let s of n){let u=e.nodes.filter(l=>{if(l.id===s.id)return!1;let c=l.x+l.width/2,d=l.y+l.height/2;return c>=s.x&&d>=s.y&&c<=s.x+s.width&&d<=s.y+s.height});r.set(s.label||s.id,u)}let o=`This canvas contains the following elements:
2025-07-05 20:48:33 +08:00
`,i=s=>{switch(s.type){case"file":return`- File: ${s.file}
Content:
${s.content}
`;case"text":return`- Text: "${s.text}"
`;case"link":return`- Link: ${s.url}
`;default:return""}};n.forEach(s=>{let u=s.label||s.id,l=r.get(u)||[];o+=`Group "${u}" contains:
`,l.forEach(c=>{o+=i(c)}),o+=`
`});let a=e.nodes.filter(s=>s.type==="group"?!1:!Array.from(r.values()).flat().some(u=>u.id===s.id));return a.length>0&&(o+=`Elements outside of groups:
`,a.forEach(s=>{o+=i(s)})),o+=`
When describing this canvas, please:
`,o+=`- Use the actual titles/names of elements instead of their IDs
`,o+=`- Pay attention to the content and relationships between elements
`,o+=`- Describe files by their names, links by their URLs, and text nodes by their content
2025-07-12 10:26:56 +08:00
`,o}};fie=new WeakSet,R1t=function(e,r){let n=e.filter(o=>o.type==="group");for(let o of n)for(let i of e){if(i.id===o.id)continue;let a=i.x+i.width/2,s=i.y+i.height/2;a>=o.x&&s>=o.y&&a<=o.x+o.width&&s<=o.y+o.height&&r.push({id:crypto.randomUUID(),fromNode:o.id,toNode:i.id,label:"contains"})}};var QRe=class{constructor(){this.supportedExtensions=["md"]}async parseFile(e,r){return await r.read(e)}},pie=class{constructor(e){this.supportedExtensions=["pdf"];this.brevilabsClient=e,this.pdfCache=cie.getInstance()}async parseFile(e,r){try{ie("Parsing PDF file:",e.path);let n=await this.pdfCache.get(e);if(n)return ie("Using cached PDF content for:",e.path),n.response;let o=await r.readBinary(e);ie("Calling pdf4llm API for:",e.path);let i=await this.brevilabsClient.pdf4llm(o);return await this.pdfCache.set(e,i),i.response}catch(n){return fe(`Error extracting content from PDF ${e.path}:`,n),`[Error: Could not extract content from PDF ${e.basename}]`}}async clearCache(){ie("Clearing PDF cache"),await this.pdfCache.clear()}},e1e=class{constructor(){this.supportedExtensions=["canvas"]}async parseFile(e,r){try{ie("Parsing Canvas file:",e.path);let n=new die(r),o=await n.load(e);return n.buildPrompt(o)}catch(n){return fe(`Error parsing Canvas file ${e.path}:`,n),`[Error: Could not parse Canvas file ${e.basename}]`}}},Pq=class Pq{constructor(e,r=null){this.supportedExtensions=["pdf","602","abw","cgm","cwk","doc","docx","docm","dot","dotm","hwp","key","lwp","mw","mcw","pages","pbd","ppt","pptm","pptx","pot","potm","potx","rtf","sda","sdd","sdp","sdw","sgl","sti","sxi","sxw","stw","sxg","txt","uof","uop","uot","vor","wpd","wps","xml","zabw","epub","jpg","jpeg","png","gif","bmp","svg","tiff","webp","web","htm","html","xlsx","xls","xlsm","xlsb","xlw","csv","dif","sylk","slk","prn","numbers","et","ods","fods","uos1","uos2","dbf","wk1","wk2","wk3","wk4","wks","123","wq1","wq2","wb1","wb2","wb3","qpw","xlr","eth","tsv","mp3","mp4","mpeg","mpga","m4a","wav","webm"];this.brevilabsClient=e,this.projectContextCache=tb.getInstance(),this.currentProject=r}static resetRateLimitNoticeTimer(){Pq.lastRateLimitNoticeTime=0}async parseFile(e,r){try{if(ie(`[Docs4LLMParser] Project ${this.currentProject?.name}: Parsing ${e.extension} file: ${e.path}`),!this.currentProject)throw fe("[Docs4LLMParser] No project context for parsing file: ",e.path),new Error("No project context provided for file parsing");let n=await this.projectContextCache.getFileContext(this.currentProject,e.path);if(n)return ie(`[Docs4LLMParser] Project ${this.currentProject.name}: Using cached content for: ${e.path}`),n;ie(`[Docs4LLMParser] Project ${this.currentProject.name}: Cache miss for: ${e.path}. Proceeding to API call.`);let o=await r.readBinary(e);ie(`[Docs4LLMParser] Project ${this.currentProject.name}: Calling docs4llm API for: ${e.path}`);let i=await this.brevilabsClient.docs4llm(o,e.extension);if(!i||!i.response)throw new Error("Empty response from docs4llm API");let a="";if(typeof i.response=="string")a=i.response;else if(Array.isArray(i.response)){let s=[];for(let u of i.response)u.content&&(u.content.md?s.push(u.content.md):u.content.text&&s.push(u.content.text));a=s.join(`
2025-07-05 20:48:33 +08:00
2025-07-12 10:26:56 +08:00
`)}else typeof i.response=="object"?i.response.md?a=i.response.md:i.response.text?a=i.response.text:i.response.content?a=i.response.content:a=JSON.stringify(i.response,null,2):a=String(i.response);return await this.projectContextCache.setFileContext(this.currentProject,e.path,a),ie(`[Docs4LLMParser] Project ${this.currentProject.name}: Successfully processed and cached: ${e.path}`),a}catch(n){throw fe(`[Docs4LLMParser] Project ${this.currentProject?.name}: Error processing file ${e.path}:`,n),xN(n)&&this.showRateLimitNotice(n),n}}showRateLimitNotice(e){let r=Date.now();if(r-Pq.lastRateLimitNoticeTime<6e4)return;Pq.lastRateLimitNoticeTime=r;let n=I1t(e);new j1t.Notice(`\u26A0\uFE0F Rate limit exceeded for document processing. Please try again in ${n}. Having fewer non-markdown files in the project will help.`,1e4)}async clearCache(){ie("Cache clearing is now handled at the project level")}};Pq.lastRateLimitNoticeTime=0;var H8=Pq,oI=class{constructor(e,r,n=!1,o=null){this.parsers=new Map;this.isProjectMode=n,this.currentProject=o,this.registerParser(new QRe),this.registerParser(new H8(e,o)),n||this.registerParser(new pie(e)),this.registerParser(new e1e)}registerParser(e){for(let r of e.supportedExtensions)this.parsers.set(r,e)}async parseFile(e,r){let n=this.parsers.get(e.extension);if(!n)throw new Error(`No parser found for file type: ${e.extension}`);return await n.parseFile(e,r)}supportsExtension(e){return this.parsers.has(e)}async clearPDFCache(){let e=this.parsers.get("pdf");e instanceof pie&&await e.clearCache()}};yn();var wW=require("obsidian");mg();Cl();Fd();$r();Cl();yn();async function mie(t,e){let r=`Given the following conversation and a follow up question,
2025-07-05 20:48:33 +08:00
summarize the conversation as context and keep the follow up question unchanged, in its original language.
If the follow up question is unrelated to its preceding messages, return this follow up question directly.
If it is related, then combine the summary and the follow up question to construct a standalone question.
Make sure to keep any [[]] wrapped note titles in the question unchanged.
If there's nothing in the chat history, just return the follow up question.
Chat History:
{chat_history}
Follow Up Input: {question}
Standalone question:`,n=e.map(({role:o,content:i})=>`${o}: ${i}`).join(`
2025-07-12 10:26:56 +08:00
`);return await yy(async()=>{let i=await ac.instance.getCurrentChainManager().chatModelManager.getChatModel().bind({temperature:0}).invoke([{role:"user",content:r.replace("{chat_history}",n).replace("{question}",t)}]);return kR(i.content)})}$r();mg();yo();mg();pN();yo();Mx();nr();yn();iie();qE();LE();Df();Hb();var hie=class extends Cn{constructor(e){super(e),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,r){throw new Error("Not implemented!")}async invoke(e,r){return this.getRelevantDocuments(e,un(r))}async getRelevantDocuments(e,r){let n=un(CR(r)),i=await(await Bs.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,n.runId,void 0,void 0,void 0,n.runName);try{let a=await this._getRelevantDocuments(e,i);return await i?.handleRetrieverEnd(a),a}catch(a){throw await i?.handleRetrieverError(a),a}}};F8();rie();var jx=class extends hie{constructor(r){super();this.options=r;this.lc_namespace=["hybrid_retriever"];this.queryRewritePrompt=xp.fromTemplate(`Please write a passage to answer the question. If you don't know the answer, just make up a passage.
2025-07-05 20:48:33 +08:00
Question: {question}
2025-07-12 10:26:56 +08:00
Passage:`)}async getRelevantDocuments(r,n){return yy(async()=>{let o=DC(r,app.vault),i=o.map(h=>h.basename),a=[...new Set([...this.options.salientTerms,...i])],s=await this.getExplicitChunks(o),u=r;n?.runName!=="no_hyde"&&(u=await this.rewriteQuery(r));let l=await this.getOramaChunks(u,a,this.options.textWeight),c=this.filterAndFormatChunks(l,s),d=c;if(c.length===0)return ue().debug&&console.log("No chunks found for query:",r),d;let f=c.reduce((h,b)=>{let g=b.metadata.score;return typeof g=="number"&&!isNaN(g)?Math.max(h,g):h},0),p=c.every(h=>typeof h.metadata.score!="number"||isNaN(h.metadata.score)),m=this.options.useRerankerThreshold&&(f<this.options.useRerankerThreshold||p);return m&&(d=(await Fi.getInstance().rerank(r,c.map(b=>b.pageContent.slice(0,3e3)))).response.data.map(b=>({...c[b.index],metadata:{...c[b.index].metadata,rerank_score:b.relevance_score}}))),ue().debug&&(console.log("*** HYBRID RETRIEVER DEBUG INFO: ***"),n?.runName!=="no_hyde"&&(console.log(`
2025-07-05 20:48:33 +08:00
Original Query: `,r),console.log("Rewritten Query: ",u)),console.log(`
2025-07-12 10:26:56 +08:00
Explicit Chunks: `,s),console.log("Orama Chunks: ",l),console.log("Combined Chunks: ",c),console.log("Max Orama Score: ",f),m?console.log("Reranked Chunks: ",d):console.log("No reranking applied.")),d})}async rewriteQuery(r){try{let n=await this.queryRewritePrompt.format({question:r}),o=await yy(()=>ac.instance.getCurrentChainManager().chatModelManager.getChatModel().bind({temperature:0}).invoke(n));return o&&"content"in o?kR(o.content):(console.warn("Unexpected rewrittenQuery format. Falling back to original query."),r)}catch(n){return console.error("Error in rewriteQuery:",n),r}}async getExplicitChunks(r){let n=[];for(let o of r){let i=await ma.getInstance().getDb(),a=await eP.getDocsByPath(i,o.path);if(a){let s=a.map(u=>new tP({pageContent:u.document.content,metadata:{...u.document.metadata,score:u.score,path:u.document.path,mtime:u.document.mtime,ctime:u.document.ctime,title:u.document.title,id:u.document.id,embeddingModel:u.document.embeddingModel,tags:u.document.tags,extension:u.document.extension,created_at:u.document.created_at,nchars:u.document.nchars}}));n.push(...s)}}return n}async getOramaChunks(r,n,o){let i;try{i=await this.convertQueryToVector(r)}catch(l){throw console.error("Error in convertQueryToVector, please ensure your embedding model is working and has an adequate context length:",l,`
Query:`,r),l}let a=await ma.getInstance().getDb(),s={similarity:this.options.minSimilarityScore,limit:this.options.maxK,includeVectors:!0};if(n.length>0){let l;o||(o=.5),l=1-o;let c=!0;for(let d of n)if(!d.startsWith("#")){c=!1;break}c&&(ue().debug&&console.log("Tag only query detected, setting textWeight to 1 and vectorWeight to 0."),o=1,l=0),s.mode="hybrid",s.term=n.join(" "),s.vector={value:i,property:"embedding"},s.hybridWeights={text:o,vector:l}}else s.mode="vector",s.vector={value:i,property:"embedding"};if(this.options.timeRange){let{startTime:l,endTime:c}=this.options.timeRange,d=this.generateDailyNoteDateRange(l,c);ie("==== Daily note date range: ====",d[0],d[d.length-1]);let f=DC(d.join(", "),app.vault),m=(await this.getExplicitChunks(f)).map(S=>({...S,metadata:{...S.metadata,includeInContext:!0}}));ie("==== Modified time range: ====",l,c),s.where={mtime:{between:[l,c]}};let b=(await Xc(a,s)).hits.map(S=>new tP({pageContent:S.document.content,metadata:{...S.document.metadata,score:S.score,path:S.document.path,mtime:S.document.mtime,ctime:S.document.ctime,title:S.document.title,id:S.document.id,embeddingModel:S.document.embeddingModel,tags:S.document.tags,extension:S.document.extension,created_at:S.document.created_at,nchars:S.document.nchars}})),g=[...m,...b];return Array.from(new Set(g.map(S=>S.metadata.id))).map(S=>g.find(x=>x.metadata.id===S)).filter(S=>S!==void 0)}ue().debug&&console.log(`==== Orama Search Params: ====
`,s);let u=await Xc(a,s);return!u||!u.hits?(console.warn("Search results or hits are undefined"),[]):u.hits.map(l=>!l||!l.document?(console.warn("Invalid hit or document in search results"),null):((typeof l.score!="number"||isNaN(l.score))&&console.warn("NaN/invalid score detected:",{score:l.score,path:l.document.path,title:l.document.title}),new tP({pageContent:l.document.content||"",metadata:{...l.document.metadata||{},score:l.score,path:l.document.path||"",mtime:l.document.mtime,ctime:l.document.ctime,title:l.document.title||"",id:l.document.id,embeddingModel:l.document.embeddingModel,tags:l.document.tags||[],extension:l.document.extension,created_at:l.document.created_at,nchars:l.document.nchars}}))).filter(l=>l!==null)}async convertQueryToVector(r){let o=await(await Xs.getInstance().getEmbeddingsAPI()).embedQuery(r);if(o.length===0)throw new Error("Query embedding returned an empty vector");return o}generateDailyNoteDateRange(r,n){let o=[],i=new Date(r),a=new Date(n),s=new Date(i);for(;s<=a;)o.push(`[[${s.toLocaleDateString("en-CA")}]]`),s.setDate(s.getDate()+1);return o}filterAndFormatChunks(r,n){let o=this.options.minSimilarityScore,i=r.filter(u=>{let l=u.metadata.score;return typeof l!="number"||isNaN(l)?!0:l>=o}),a=new Set(n.map(u=>u.pageContent)),s=[...n];for(let u of i){let l=u.pageContent;a.has(l)||(a.add(l),s.push(u))}return s.map(u=>({...u,metadata:{...u.metadata,includeInContext:!0}}))}};nr();var t1e=require("obsidian"),N1t=t=>{switch(t){case"@vault":return"Search through your vault for relevant information";case"@websearch":return"Search the web for information";case"@youtube":return"Get the transcript of a YouTube video. Example: @youtube <video_url>";case"@pomodoro":return"Start a pomodoro timer. Example: @pomodoro 25m";case"@composer":return"Edit existing notes or create new notes.";default:return""}},Eq=class{static async callTool(e,r){try{if(!e)throw new Error("Tool is undefined");let n=await e.call(r);return n??(console.warn(`Tool ${e.name} returned null/undefined result`),null)}catch(n){return console.error("Error calling tool:",n),n instanceof Error?new t1e.Notice(n.message):new t1e.Notice("An error occurred while executing the tool. Check console for details."),null}}};yn();var KNt=require("obsidian");Cl();ZA();Td();_g();function tJr(t){return"children"in t&&"path"in t}function rJr(t){return"path"in t&&!("children"in t)}function nJr(t){let e=t.split(".");return e.length>1&&e.pop()?.toLowerCase()||""}function r1e(t,e=!0){let r=[],n={},o={},{inclusions:i,exclusions:a}=rf();for(let u of t.children)if(rJr(u)){if(eu(u,i,a)){e&&r.push(u.name);let l=nJr(u.name)||"unknown";l&&(n[l]=(n[l]||0)+1)}}else if(tJr(u)){let l=r1e(u,e);if(Object.keys(l).length>0&&(o[u.name]=l[u.name],l[u.name].extensionCounts))for(let[c,d]of Object.entries(l[u.name].extensionCounts))n[c]=(n[c]||0)+d}let s={};return Object.keys(n).length>0&&(s.extensionCounts=n),e&&r.length>0&&(s.files=r),Object.keys(o).length>0&&(s.subFolders=o),Object.keys(s).length===0?{}:t.name?{[t.name]:s}:{vault:s}}var D1t=t=>Qm(async()=>{let e=r1e(t,!0),r=`A JSON represents the file tree as a nested structure:
2025-07-05 20:48:33 +08:00
* 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-07-12 10:26:56 +08:00
`,n=JSON.stringify(e);if(n.length>5e5){let o=r1e(t,!1);return r+JSON.stringify(o)}return r+n},{name:"getFileTree",description:"Get the file tree as a nested structure of folders and files",schema:Wr.void()});$r();wT();mg();Mx();nr();ZA();Td();var n1e=Qm(async({timeRange:t,query:e,salientTerms:r})=>{if(await ma.getInstance().isIndexEmpty())throw new Rr(iJ);let o=t!==void 0,i=ue().maxSourceChunks<age?age:ue().maxSourceChunks;ue().debug&&console.log("returnAll:",o);let u=(await new jx({minSimilarityScore:o?0:.1,maxK:o?1e3:i,salientTerms:r,timeRange:t?{startTime:t.startTime.epoch,endTime:t.endTime.epoch}:void 0,textWeight:PVe,returnAll:o,useRerankerThreshold:.5}).getRelevantDocuments(e)).map(l=>({title:l.metadata.title,content:l.pageContent,path:l.metadata.path,score:l.metadata.score,rerank_score:l.metadata.rerank_score,includeInContext:l.metadata.includeInContext}));return JSON.stringify(u)},{name:"localSearch",description:"Search for notes based on the time range and query",schema:Wr.object({timeRange:Wr.object({startTime:Wr.any(),endTime:Wr.any()}).optional(),query:Wr.string().describe("The search query"),salientTerms:Wr.array(Wr.string()).describe("List of salient terms extracted from the query")})}),L1t=Qm(async()=>{try{let t=await ma.getInstance().indexVaultToVectorStore();return`Please report whether the indexing was successful.
If success is true, just say it is successful. If 0 files is indexed, say there are no new files to index.`+JSON.stringify({success:!0,message:t===0?"No new files to index.":`Indexed ${t} files in the vault.`})}catch(t){return console.error("Error indexing vault:",t),JSON.stringify({success:!1,message:"An error occurred while indexing the vault."})}},{name:"indexVault",description:"Index the vault to the Copilot index"}),o1e=Qm(async({query:t,chatHistory:e})=>{try{let r=await mie(t,e),n=await Fi.getInstance().webSearch(r),o=n.response.citations||[],i=o.length>0?`
2025-07-05 20:48:33 +08:00
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)':
2025-07-12 10:26:56 +08:00
`+n.response.choices[0].message.content+i}catch(r){return console.error(`Error processing web search query ${t}:`,r),""}},{name:"webSearch",description:"Search the web for information",schema:Wr.object({query:Wr.string().describe("The search query"),chatHistory:Wr.array(Wr.object({role:Wr.enum(["user","assistant"]),content:Wr.string()})).describe("Previous conversation turns")})});ZA();var B1t=F(F1t(),1),V8=F(iI(),1);var oo;(function(t){t[t.AM=0]="AM",t[t.PM=1]="PM"})(oo||(oo={}));var tu;(function(t){t[t.SUNDAY=0]="SUNDAY",t[t.MONDAY=1]="MONDAY",t[t.TUESDAY=2]="TUESDAY",t[t.WEDNESDAY=3]="WEDNESDAY",t[t.THURSDAY=4]="THURSDAY",t[t.FRIDAY=5]="FRIDAY",t[t.SATURDAY=6]="SATURDAY"})(tu||(tu={}));var eh;(function(t){t[t.JANUARY=1]="JANUARY",t[t.FEBRUARY=2]="FEBRUARY",t[t.MARCH=3]="MARCH",t[t.APRIL=4]="APRIL",t[t.MAY=5]="MAY",t[t.JUNE=6]="JUNE",t[t.JULY=7]="JULY",t[t.AUGUST=8]="AUGUST",t[t.SEPTEMBER=9]="SEPTEMBER",t[t.OCTOBER=10]="OCTOBER",t[t.NOVEMBER=11]="NOVEMBER",t[t.DECEMBER=12]="DECEMBER"})(eh||(eh={}));function k1t(t,e){e=e.add(1,"day"),CN(t,e),Tq(t,e)}function rb(t,e){t.assign("day",e.date()),t.assign("month",e.month()+1),t.assign("year",e.year())}function gie(t,e){t.assign("hour",e.hour()),t.assign("minute",e.minute()),t.assign("second",e.second()),t.assign("millisecond",e.millisecond()),t.get("hour")<12?t.assign("meridiem",oo.AM):t.assign("meridiem",oo.PM)}function CN(t,e){t.imply("day",e.date()),t.imply("month",e.month()+1),t.imply("year",e.year())}function Tq(t,e){t.imply("hour",e.hour()),t.imply("minute",e.minute()),t.imply("second",e.second()),t.imply("millisecond",e.millisecond())}var l1e=F(iI(),1);var oJr={ACDT:630,ACST:570,ADT:-180,AEDT:660,AEST:600,AFT:270,AKDT:-480,AKST:-540,ALMT:360,AMST:-180,AMT:-240,ANAST:720,ANAT:720,AQTT:300,ART:-180,AST:-240,AWDT:540,AWST:480,AZOST:0,AZOT:-60,AZST:300,AZT:240,BNT:480,BOT:-240,BRST:-120,BRT:-180,BST:60,BTT:360,CAST:480,CAT:120,CCT:390,CDT:-300,CEST:120,CET:{timezoneOffsetDuringDst:2*60,timezoneOffsetNonDst:60,dstStart:t=>$1t(t,eh.MARCH,tu.SUNDAY,2),dstEnd:t=>$1t(t,eh.OCTOBER,tu.SUNDAY,3)},CHADT:825,CHAST:765,CKT:-600,CLST:-180,CLT:-240,COT:-300,CST:-360,CT:{timezoneOffsetDuringDst:-5*60,timezoneOffsetNonDst:-6*60,dstStart:t=>aI(t,eh.MARCH,tu.SUNDAY,2,2),dstEnd:t=>aI(t,eh.NOVEMBER,tu.SUNDAY,1,2)},CVT:-60,CXT:420,ChST:600,DAVT:420,EASST:-300,EAST:-360,EAT:180,ECT:-300,EDT:-240,EEST:180,EET:120,EGST:0,EGT:-60,EST:-300,ET:{timezoneOffsetDuringDst:-4*60,timezoneOffsetNonDst:-5*60,dstStart:t=>aI(t,eh.MARCH,tu.SUNDAY,2,2),dstEnd:t=>aI(t,eh.NOVEMBER,tu.SUNDAY,1,2)},FJST:780,FJT:720,FKST:-180,FKT:-240,FNT:-120,GALT:-360,GAMT:-540,GET:240,GFT:-180,GILT:720,GMT:0,GST:240,GYT:-240,HAA:-180,HAC:-300,HADT:-540,HAE:-240,HAP:-420,HAR:-360,HAST:-600,HAT:-90,HAY:-480,HKT:480,HLV:-210,HNA:-240,HNC:-360,HNE:-300,HNP:-480,HNR:-420,HNT:-150,HNY:-540,HOVT:420,ICT:420,IDT:180,IOT:360,IRDT:270,IRKST:540,IRKT:540,IRST:210,IST:330,JST:540,KGT:360,KRAST:480,KRAT:480,KST:540,KUYT:240,LHDT:660,LHST:630,LINT:840,MAGST:720,MAGT:720,MART:-510,MAWT:300,MDT:-360,MESZ:120,MEZ:60,MHT:720,MMT:390,MSD:240,MSK:180,MST:-420,MT:{timezoneOffsetDuringDst:-6*60,timezoneOffsetNonDst:-7*60,dstStart:t=>aI(t,eh.MARCH,tu.SUNDAY,2,2),dstEnd:t=>aI(t,eh.NOVEMBER,tu.SUNDAY,1,2)},MUT:240,MVT:300,MYT:480,NCT:660,NDT:-90,NFT:690,NOVST:420,NOVT:360,NPT:345,NST:-150,NUT:-660,NZDT:780,NZST:720,OMSST:420,OMST:420,PDT:-420,PET:-300,PETST:720,PETT:720,PGT:600,PHOT:780,PHT:480,PKT:300,PMDT:-120,PMST:-180,PONT:660,PST:-480,PT:{timezoneOffsetDuringDst:-7*60,timezoneOffsetNonDst:-8*60,dstStart:t=>aI(t,eh.MARCH,tu.SUNDAY,2,2),dstEnd:t=>aI(t,eh.NOVEMBER,tu.SUNDAY,1,2)},PWT:540,PYST:-180,PYT:-240,RET:240,SAMT:240,SAST:120,SBT:660,SCT:240,SGT:480,SRT:-180,SST:-660,TAHT:-600,TFT:300,TJT:300,TKT:780,TLT:540,TMT:300,TVT:720,ULAT:480,UTC:0,UYST:-120,UYT:-180,UZT:300,VET:-210,VLAST:660,VLAT:660,VUT:660,WAST:120,WAT:60,WEST:60,WESZ:60,WET:0,WEZ:0,WFT:720,WGST:-120,WGT:-180,WIB:420,WIT:540,WITA:480,WST:780,WT:0,YAKST:600,YAKT:600,YAPT:600,YEKST:360,YEKT:360};function aI(t,e,r,n,o=0){let i=0,a=0;for(;a<n;)i++,new Date(t,e-1,i).getDay()===r&&a++;retu
2025-07-05 20:48:33 +08:00
tags: ${JSON.stringify(Array.from(this._tags).sort())},
knownValues: ${JSON.stringify(this.knownValues)},
impliedValues: ${JSON.stringify(this.impliedValues)}},
2025-07-12 10:26:56 +08:00
reference: ${JSON.stringify(this.reference)}]`}dayjs(){return(0,V8.default)(this.date())}date(){let e=this.dateWithoutTimezoneAdjustment(),r=this.reference.getSystemTimezoneAdjustmentMinute(e,this.get("timezoneOffset"));return new Date(e.getTime()+r*6e4)}addTag(e){return this._tags.add(e),this}addTags(e){for(let r of e)this._tags.add(r);return this}tags(){return new Set(this._tags)}dateWithoutTimezoneAdjustment(){let e=new Date(this.get("year"),this.get("month")-1,this.get("day"),this.get("hour"),this.get("minute"),this.get("second"),this.get("millisecond"));return e.setFullYear(this.get("year")),e}static createRelativeFromReference(e,r){let n=(0,V8.default)(e.instant);for(let i in r)n=n.add(r[i],i);let o=new t(e);return r.hour||r.minute||r.second?(gie(o,n),rb(o,n),e.timezoneOffset!==null&&o.assign("timezoneOffset",-e.instant.getTimezoneOffset())):(Tq(o,n),e.timezoneOffset!==null&&o.imply("timezoneOffset",-e.instant.getTimezoneOffset()),r.d?(o.assign("day",n.date()),o.assign("month",n.month()+1),o.assign("year",n.year())):r.week?(o.assign("day",n.date()),o.assign("month",n.month()+1),o.assign("year",n.year()),o.imply("weekday",n.day())):(o.imply("day",n.date()),r.month?(o.assign("month",n.month()+1),o.assign("year",n.year())):(o.imply("month",n.month()+1),r.year?o.assign("year",n.year()):o.imply("year",n.year())))),o}},rP=class t{constructor(e,r,n,o,i){this.reference=e,this.refDate=e.instant,this.index=r,this.text=n,this.start=o||new io(e),this.end=i}clone(){let e=new t(this.reference,this.index,this.text);return e.start=this.start?this.start.clone():null,e.end=this.end?this.end.clone():null,e}date(){return this.start.date()}tags(){let e=new Set(this.start.tags());if(this.end)for(let r of this.end.tags())e.add(r);return e}toString(){let e=Array.from(this.tags()).sort();return`[ParsingResult {index: ${this.index}, text: '${this.text}', tags: ${JSON.stringify(e)} ...}]`}};function c1e(t,e,r="\\s{0,5},?\\s{0,5}"){let n=e.replace(/\((?!\?)/g,"(?:");return`${t}${n}(?:${r}${n}){0,10}`}function iJr(t){let e;return t instanceof Array?e=[...t]:t instanceof Map?e=Array.from(t.keys()):e=Object.keys(t),e}function Qc(t){return`(?:${iJr(t).sort((r,n)=>n.length-r.length).join("|").replace(/\./g,"\\.")})`}var q1t=F(iI(),1);function bie(t){return t<100&&(t>50?t=t+1900:t=t+2e3),t}function uI(t,e,r){let n=(0,q1t.default)(t),o=n;o=o.month(r-1),o=o.date(e),o=o.year(n.year());let i=o.add(1,"y"),a=o.add(-1,"y");return Math.abs(i.diff(n))<Math.abs(o.diff(n))?o=i:Math.abs(a.diff(n))<Math.abs(o.diff(n))&&(o=a),o.year()}var p1e={sunday:0,sun:0,"sun.":0,monday:1,mon:1,"mon.":1,tuesday:2,tue:2,"tue.":2,wednesday:3,wed:3,"wed.":3,thursday:4,thurs:4,"thurs.":4,thur:4,"thur.":4,thu:4,"thu.":4,friday:5,fri:5,"fri.":5,saturday:6,sat:6,"sat.":6},m1e={january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12},vg={...m1e,jan:1,"jan.":1,feb:2,"feb.":2,mar:3,"mar.":3,apr:4,"apr.":4,jun:6,"jun.":6,jul:7,"jul.":7,aug:8,"aug.":8,sep:9,"sep.":9,sept:9,"sept.":9,oct:10,"oct.":10,nov:11,"nov.":11,dec:12,"dec.":12},d1e={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12},f1e={first:1,second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,tenth:10,eleventh:11,twelfth:12,thirteenth:13,fourteenth:14,fifteenth:15,sixteenth:16,seventeenth:17,eighteenth:18,nineteenth:19,twentieth:20,"twenty first":21,"twenty-first":21,"twenty second":22,"twenty-second":22,"twenty third":23,"twenty-third":23,"twenty fourth":24,"twenty-fourth":24,"twenty fifth":25,"twenty-fifth":25,"twenty sixth":26,"twenty-sixth":26,"twenty seventh":27,"twenty-seventh":27,"twenty eighth":28,"twenty-eighth":28,"twenty ninth":29,"twenty-ninth":29,thirtieth:30,"thirty first":31,"thirty-first":31},z1t={second:"second",seconds:"second",minute:"minute",minutes:"minute",hour:"hour",hours:"hour",day:"d",days:"d",week:"week",weeks:"week",month:"month",months:"month",quarter:"quarter",quarters:"quarter",year:"year",years:"year"},W8={s:"second",sec:"second",second:"second",seconds:"second",m:"minut
2025-07-05 20:48:33 +08:00
<think>`,this.hasOpenThinkBlock=!0),this.fullResponse+=n.thinking,this.updateCurrentAiMessage(this.fullResponse),!0}return r&&(this.fullResponse+=r),!1}handleDeepseekChunk(e){return typeof e.content=="string"&&(this.fullResponse+=e.content),e.additional_kwargs?.reasoning_content?(this.hasOpenThinkBlock||(this.fullResponse+=`
2025-07-12 10:26:56 +08:00
<think>`,this.hasOpenThinkBlock=!0),this.fullResponse+=e.additional_kwargs.reasoning_content,!0):!1}processChunk(e){let r=!1;Array.isArray(e.content)?r=this.handleClaude37Chunk(e.content):r=this.handleDeepseekChunk(e),this.hasOpenThinkBlock&&!r&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),this.updateCurrentAiMessage(this.fullResponse)}close(){return this.hasOpenThinkBlock&&(this.fullResponse+="</think>",this.updateCurrentAiMessage(this.fullResponse)),this.fullResponse}},e5=class{constructor(e){this.chainManager=e}async handleResponse(e,r,n,o,i,a){return e&&!(n.signal.aborted&&n.signal.reason==="new-chat")?(await this.chainManager.memoryManager.getMemory().saveContext({input:r.message},{output:e}),o({message:e,sender:e_,isVisible:!0,timestamp:Vl(new Date),sources:a}),i("")):n.signal.reason==="new-chat"&&i(""),ie(`==== Chat Memory ====
2025-07-05 20:48:33 +08:00
`,this.chainManager.memoryManager.getMemory().chatHistory.messages.map(s=>s.content)),ie(`==== Final AI Response ====
`,e),e}async handleError(e,r,n){let o=ei(e);fe("Error during LLM invocation:",o);let i=e?.response?.data?.error||o,a=i?.code||o,s="";if(e?.message?.includes("Invalid license key")?s="Invalid Copilot Plus license key. Please check your license key in settings.":a==="model_not_found"?s="You do not have access to this model or the model does not exist, please check with your API provider.":s=`${a}`,fe(i),r&&n){n("");let u=s.search("Troubleshooting URL");s=u!==-1?s.slice(0,u):s,o.search(/401|invalid|not valid/gi)!==-1&&(s=`Something went wrong. Please check if you have set your API key.
Path: Settings > copilot plugin > Basic Tab > Set Keys.
Or check model config
2025-07-12 10:26:56 +08:00
Error Details: `+s),r({message:s,isErrorMessage:!0,sender:e_,isVisible:!0,timestamp:Vl(new Date)})}else new KNt.Notice(s),fe(i)}},Hie=class extends e5{async run(e,r,n,o,i){let a=new Q6(n);try{let l=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),c=LR(l),d=[],f=Yb(),p=this.chainManager.chatModelManager.getChatModel();f&&d.push({role:oJ(p),content:f});for(let h of c)d.push({role:h.role,content:h.content});d.push({role:"user",content:e.message}),ie(`==== Final Request to AI ====
`,d);let m=await yy(()=>this.chainManager.chatModelManager.getChatModel().stream(d,{signal:r.signal}));for await(let h of m){if(r.signal.aborted){ie("Stream iteration aborted",{reason:r.signal.reason});break}a.processChunk(h)}}catch(u){u.name==="AbortError"||r.signal.aborted?ie("Stream aborted by user",{reason:r.signal.reason}):await this.handleError(u,o,n)}let s=a.close();return r.signal.aborted&&r.signal.reason==="new-chat"?(n(""),""):this.handleResponse(s,e,r,o,n)}},Vie=class extends e5{async run(e,r,n,o,i){let a=new Q6(n);try{if(await this.chainManager.vectorStoreManager.isIndexEmpty())return this.handleResponse(iJ,e,r,o,n);let c=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),d=LR(c),f=e.message;d.length>0&&(f=e.message);let m=await new jx({minSimilarityScore:.01,maxK:ue().maxSourceChunks,salientTerms:[]}).getRelevantDocuments(f);this.chainManager.storeRetrieverDocuments(m);let h=m.map(P=>P.pageContent).join(`
2025-07-05 20:48:33 +08:00
`),b=[],g=Yb(),y=`
Answer the question with as detailed as possible based only on the following context:
2025-07-12 10:26:56 +08:00
`+h,S=g+y,x=this.chainManager.chatModelManager.getChatModel();S&&b.push({role:oJ(x),content:S});for(let P of d)b.push({role:P.role,content:P.content});b.push({role:"user",content:e.message}),ie(`==== Final Request to AI ====
`,b);let O=await yy(()=>this.chainManager.chatModelManager.getChatModel().stream(b,{signal:r.signal}));for await(let P of O){if(r.signal.aborted){ie("VaultQA stream iteration aborted",{reason:r.signal.reason});break}a.processChunk(P)}}catch(u){u.name==="AbortError"||r.signal.aborted?ie("VaultQA stream aborted by user",{reason:r.signal.reason}):await this.handleError(u,o,n)}let s=a.close();return r.signal.aborted&&r.signal.reason==="new-chat"?(n(""),""):(s=this.addSourcestoResponse(s),this.handleResponse(s,e,r,o,n))}addSourcestoResponse(e){let r=yVe(this.chainManager.getRetrievedDocuments());if(r.length>0){let n=r.map(o=>`- [[${o}]]`).join(`
2025-07-05 20:48:33 +08:00
`);e+=`
#### Sources:
2025-07-12 10:26:56 +08:00
`+n}return e}},t5=class extends e5{isYoutubeOnlyMessage(e){let r=e.trim(),n=r.includes("@youtube"),o=rge(r),i=r.split(/\s+/).filter(a=>a!=="@youtube"&&a.length>0);return n&&o!==null&&i.length===1}async processImageUrls(e){let r=[],n=await SN.processUrlBatch(e,r,this.chainManager.app.vault);return SN.showFailedImagesNotice(r),n}async processChatInputImages(e){let r=[],n=await SN.processChatImageBatch(e,r,this.chainManager.app.vault);return SN.showFailedImagesNotice(r),n}async extractEmbeddedImages(e){let r=/!\[\[(.*?\.(png|jpg|jpeg|gif|webp|bmp|svg))\]\]/g;return[...e.matchAll(r)].map(i=>i[1])}async buildMessageContent(e,r){let n=[],o=[],i=ue(),a=[],s=r.context?.urls;if(s&&s.length>0&&a.push({urls:s,type:"context"}),i.passMarkdownImages){let d=await this.extractEmbeddedImages(e);d.length>0&&a.push({urls:d,type:"embedded"})}for(let d of a){let f=await this.processImageUrls(d.urls);o.push(...f.successfulImages),n.push(...f.failureDescriptions)}let u=r.content;if(u&&u.length>0){let d=await this.processChatInputImages(u);o.push(...d.successfulImages),n.push(...d.failureDescriptions)}let l=e;n.length>0&&(l=`${e}
2025-07-05 20:48:33 +08:00
Note:
${n.join(`
`)}
2025-07-12 10:26:56 +08:00
`);let c=[{type:"text",text:l}];return o.length>0&&c.push(...o),c}hasCapability(e,r){let n=e.modelName||e.model||"";return this.chainManager.chatModelManager.findModelByName(n)?.capabilities?.includes(r)??!1}isMultimodalModel(e){return this.hasCapability(e,"vision")}async streamMultimodalResponse(e,r,n,o){let a=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),s=LR(a),u=[],l=await this.getSystemPrompt();s.length>0&&(l+=`
2025-07-05 20:48:33 +08:00
2025-07-12 10:26:56 +08:00
The following is the relevant conversation history. Use this context to maintain consistency in your responses:`);let c=this.chainManager.chatModelManager.getChatModel();l&&u.push({role:oJ(c),content:`${l}
2025-07-05 20:48:33 +08:00
IMPORTANT: Maintain consistency with previous responses in the conversation. If you've provided information about a person or topic before, use that same information in follow-up questions.`});for(let g of s)u.push({role:g.role,content:g.content});let d=this.chainManager.chatModelManager.getChatModel(),p=this.isMultimodalModel(d)?await this.buildMessageContent(e,r):e;u.push({role:"user",content:p});let m=p instanceof Array?p[0].text:p;ie("Enhanced user message: ",m),ie(`==== Final Request to AI ====
2025-07-12 10:26:56 +08:00
`,u);let h=new Q6(o),b=await yy(()=>this.chainManager.chatModelManager.getChatModel().stream(u,{signal:n.signal}));for await(let g of b){if(n.signal.aborted){ie("CopilotPlus multimodal stream iteration aborted",{reason:n.signal.reason});break}h.processChunk(g)}return h.close()}async run(e,r,n,o,i){let{updateLoadingMessage:a}=i,s="",u=[],l="",c=d=>{l=d,n(d)};try{if(this.isYoutubeOnlyMessage(e.message)){let S=rge(e.message),x="Transcript not available. Only videos with the auto transcript option turned on are supported at the moment.";if(S)try{let O=await Fi.getInstance().youtube4llm(S);return O.response.transcript?this.handleResponse(O.response.transcript,e,r,o,n):this.handleResponse(x,e,r,o,n)}catch(O){return fe("Error processing YouTube video:",O),this.handleResponse(x,e,r,o,n)}}ie("==== Step 1: Analyzing intent ====");let d,f=e.originalMessage||e.message;try{d=await MN.analyzeIntent(f)}catch(S){return this.handleResponse(fVe(S),e,r,o,n)}let p=e.message.split(" ").filter(S=>!X6.includes(S.toLowerCase())).join(" ").trim(),m=await this.executeToolCalls(d,a),h=m.find(S=>S.tool==="localSearch"&&S.output&&S.output.length>0),g=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),y=LR(g);if(h){ie("==== Step 2: Processing local search results ====");let S=JSON.parse(h.output);ie("==== Step 3: Condensing Question ====");let x=await mie(p,y);ie("Condensed standalone question: ",x),ie("==== Step 4: Preparing context ====");let O=this.getTimeExpression(d),P=this.prepareLocalSearchResult(S,O),E=m.filter(R=>R.tool==="getCurrentTime"),A=this.prepareEnhancedUserMessage(x,E);ie(P),ie("==== Step 5: Invoking QA Chain ====");let I=await this.chainManager.promptManager.getQAPrompt({question:A,context:P,systemMessage:""});s=await this.streamMultimodalResponse(I,e,r,c),u=this.getSources(S)}else{let S=this.prepareEnhancedUserMessage(p,m);ie("No local search results. Using standard LLM Chain."),s=await this.streamMultimodalResponse(S,e,r,c)}}catch(d){a?.(t_.DEFAULT),d.name==="AbortError"||r.signal.aborted?ie("CopilotPlus stream aborted by user",{reason:r.signal.reason}):await this.handleError(d,o,n)}return r.signal.aborted&&r.signal.reason==="new-chat"?(n(""),""):(r.signal.aborted&&l&&(s=l),this.handleResponse(s,e,r,o,n,u))}getSources(e){return!e||!Array.isArray(e)?(Mh("No valid documents provided to getSources"),[]):this.sortUniqueDocsByScore(e)}sortUniqueDocsByScore(e){let r=new Map;for(let n of e){if(!n.title||!n?.score&&!n?.rerank_score){Mh("Invalid document structure:",n);continue}let o=r.get(n.title),i=n&&"rerank_score"in n,a=i?n.rerank_score:n.score;(!o||a>(o.score??0))&&r.set(n.title,{title:n.title,score:a,isReranked:i})}return Array.from(r.values()).sort((n,o)=>(o.score??0)-(n.score??0))}async executeToolCalls(e,r){let n=[];for(let o of e){ie(`==== Step 2: Calling tool: ${o.tool.name} ====`),o.tool.name==="localSearch"?r?.(t_.READING_FILES):o.tool.name==="webSearch"?r?.(t_.SEARCHING_WEB):o.tool.name==="getFileTree"&&r?.(t_.READING_FILE_TREE);let i=await Eq.callTool(o.tool,o.args);n.push({tool:o.tool.name,output:i})}return n}prepareEnhancedUserMessage(e,r){let n="";if(r.length>0){let o=r.filter(i=>i.output!=null);o.length>0&&(n=`
2025-07-05 20:48:33 +08:00
# Additional context:
`+o.map(i=>`<${i.tool}>
${typeof i.output!="string"?JSON.stringify(i.output):i.output}
</${i.tool}>`).join(`
2025-07-12 10:26:56 +08:00
`))}return`${e}${n}`}getTimeExpression(e){let r=e.find(n=>n.tool.name==="getTimeRangeMs");return r?r.args.timeExpression:""}prepareLocalSearchResult(e,r){let n=e.filter(s=>s.includeInContext),o=n.reduce((s,u)=>s+u.content.length,0),i=n;if(o>sge){let s=sge/o;ie("Truncating documents to fit context length. Truncation ratio:",s),i=n.map(u=>({...u,content:u.content.slice(0,Math.floor(u.content.length*s))}))}let a=i.map(s=>`Note in Vault: ${s.content}`).join(`
2025-07-05 20:48:33 +08:00
`);return r?`Local Search Result for ${r}:
${a}`:`Local Search Result:
2025-07-12 10:26:56 +08:00
${a}`}async getSystemPrompt(){return Yb()}},Wie=class extends t5{async getSystemPrompt(){let e=Yb(),r=Mc();if(!r)return e;let n=await ac.instance.getProjectContext(r.id);return e=`${e}
2025-07-05 20:48:33 +08:00
<project_system_prompt>
${r.systemPrompt}
</project_system_prompt>`,n&&(e=`${e}
<project_context>
${n}
2025-07-12 10:26:56 +08:00
</project_context>`),e}};yo();nr();yn();qE();var Jle=require("obsidian");Cl();$r();qR();yo();nr();yn();u8();var RN="0.39.0";var GNt=!1,jN,sje,XYr,QYr,eZr,JNt,tZr,Kie,uje,YNt,lje,Gie,ZNt;function XNt(t,e={auto:!1}){if(GNt)throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${t.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(jN)throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${t.kind}'\` after \`import '@anthropic-ai/sdk/shims/${jN}'\``);GNt=e.auto,jN=t.kind,sje=t.fetch,XYr=t.Request,QYr=t.Response,eZr=t.Headers,JNt=t.FormData,tZr=t.Blob,Kie=t.File,uje=t.ReadableStream,YNt=t.getMultipartRequestOptions,lje=t.getDefaultAgent,Gie=t.fileFromPath,ZNt=t.isFsReadStream}var Jie=class{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}};function QNt({manuallyImported:t}={}){let e=t?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from '@anthropic-ai/sdk'`:\n- `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)\n- `import '@anthropic-ai/sdk/shims/web'` (otherwise)\n",r,n,o,i;try{r=fetch,n=Request,o=Response,i=Headers}catch(a){throw new Error(`this environment is missing the following Web Fetch API type: ${a.message}. ${e}`)}return{kind:"web",fetch:r,Request:n,Response:o,Headers:i,FormData:typeof FormData<"u"?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${e}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${e}`)}},File:typeof File<"u"?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${e}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${e}`)}},getMultipartRequestOptions:async(a,s)=>({...s,body:new Jie(a)}),getDefaultAgent:a=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/anthropics/anthropic-sdk-typescript#file-uploads")},isFsReadStream:a=>!1}}jN||XNt(QNt(),{auto:!0});var Or=class extends Error{},cc=class t extends Or{constructor(e,r,n,o){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=o,this.request_id=o?.["request-id"],this.error=r}static makeMessage(e,r,n){let o=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,r,n,o){if(!e||!o)return new wI({message:n,cause:Yie(r)});let i=r;return e===400?new r5(e,i,n,o):e===401?new n5(e,i,n,o):e===403?new o5(e,i,n,o):e===404?new i5(e,i,n,o):e===409?new a5(e,i,n,o):e===422?new s5(e,i,n,o):e===429?new u5(e,i,n,o):e>=500?new l5(e,i,n,o):new t(e,i,n,o)}},ed=class extends cc{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},wI=class extends cc{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Zq=class extends wI{constructor({message:e}={}){super({message:e??"Request timed out."})}},r5=class extends cc{},n5=class extends cc{},o5=class extends cc{},i5=class extends cc{},a5=class extends cc{},s5=class extends cc{},u5=class extends cc{},l5=class extends cc{};var Zie=function(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r},NN=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");retur
2025-07-05 20:48:33 +08:00
`):[]}};nh=new WeakMap;uP.NEWLINE_CHARS=new Set([`
2025-07-12 10:26:56 +08:00
`,"\r"]);uP.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function oZr(t,e){for(let o=e??0;o<t.length;o++){if(t[o]===10)return{preceding:o,index:o+1,carriage:!1};if(t[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function eDt(t){for(let n=0;n<t.length-1;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)return n+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)return n+4}return-1}function c5(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var Nx=class t{constructor(e,r){this.iterator=e,this.controller=r}static fromSSEResponse(e,r){let n=!1;async function*o(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let i=!1;try{for await(let a of iZr(e,r)){if(a.event==="completion")try{yield JSON.parse(a.data)}catch(s){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),s}if(a.event==="message_start"||a.event==="message_delta"||a.event==="message_stop"||a.event==="content_block_start"||a.event==="content_block_delta"||a.event==="content_block_stop")try{yield JSON.parse(a.data)}catch(s){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),s}if(a.event!=="ping"&&a.event==="error")throw cc.generate(void 0,`SSE Error: ${a.data}`,a.data,dje(e.headers))}i=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{i||r.abort()}}return new t(o,r)}static fromReadableStream(e,r){let n=!1;async function*o(){let a=new uP,s=c5(e);for await(let u of s)for(let l of a.decode(u))yield l;for(let u of a.flush())yield u}async function*i(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{for await(let s of o())a||s&&(yield JSON.parse(s));a=!0}catch(s){if(s instanceof Error&&s.name==="AbortError")return;throw s}finally{a||r.abort()}}return new t(i,r)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),o=i=>({next:()=>{if(i.length===0){let a=n.next();e.push(a),r.push(a)}return i.shift()}});return[new t(()=>o(e),this.controller),new t(()=>o(r),this.controller)]}toReadableStream(){let e=this,r,n=new TextEncoder;return new uje({async start(){r=e[Symbol.asyncIterator]()},async pull(o){try{let{value:i,done:a}=await r.next();if(a)return o.close();let s=n.encode(JSON.stringify(i)+`
`);o.enqueue(s)}catch(i){o.error(i)}},async cancel(){await r.return?.()}})}};async function*iZr(t,e){if(!t.body)throw e.abort(),new Or("Attempted to iterate over a response with no body");let r=new cje,n=new uP,o=c5(t.body);for await(let i of aZr(o))for(let a of n.decode(i)){let s=r.decode(a);s&&(yield s)}for(let i of n.flush()){let a=r.decode(i);a&&(yield a)}}async function*aZr(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?new TextEncoder().encode(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let i;for(;(i=eDt(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}var cje=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=sZr(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}};function sZr(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var uZr=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",lZr=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&d5(t),d5=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function";async function tDt(t,e,r){if(t=await t,lZr(t))return t;if(uZr(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=d5(o)?[await o.arrayBuffer()]:[o];return new Kie(i,e,r)}let n=await cZr(t);if(e||(e=fZr(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new Kie(n,e,r)}async function cZr(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(d5(t))e.push(await t.arrayBuffer());else if(pZr(t))for await(let r of t)e.push(r);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${dZr(t)}`);return e}function dZr(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function fZr(t){return fje(t.name)||fje(t.filename)||fje(t.path)?.split(/[\\/]/).pop()}var fje=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},pZr=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",pje=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody";var hZr=function(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r},gZr=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Xie;async function aDt(t){let{response:e}=t;if(t.options.stream)return Xq("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):Nx.fromSSEResponse(e,t.controller);if(e.status===204)return null;if(t.options.__binaryResponse)return e;let r=e.headers.get("content-type");if(r?.includes("application/json")||r?.includes("application/vnd.api+json")){let i=await e.json();return Xq("response",e.status,e.url,e.headers,i),sDt(i,e)}let o=await e.text();return Xq("response",e.status,e.url,e.headers,o),o}function sDt(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var eae=class t extends Promise{constructor(e,r=aDt){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=r}_thenUnwrap(e){return new t(this.responsePromise,async r=>sDt(e(await this.parseResponse(r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}},tae=class{constructor({baseURL:e,maxRetries:r=2,timeout:n=6e5,httpAgent:o,fetch:i}){this.baseURL=e,this.maxRetries=mje("maxRetries",r),this.timeout=mje("timeout",n),this.httpAgent=o,this.f
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages?beta=true",{body:o,timeout:this._client._options.timeout??(o.stream?6e5:this._client._calculateNonstreamingTimeout(o.max_tokens)),...r,headers:{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...r?.headers},stream:e.stream??!1})}stream(e,r){return dae.createMessage(this,e,r)}countTokens(e,r){let{betas:n,...o}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:o,...r,headers:{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString(),...r?.headers}})}};xI.Batches=LN;xI.BetaMessageBatchesPage=tU;var Lx=class extends dc{constructor(){super(...arguments),this.models=new DN(this._client),this.messages=new xI(this._client)}};Lx.Models=DN;Lx.BetaModelInfosPage=Qq;Lx.Messages=xI;var FN=class extends dc{create(e,r){return this._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...r,stream:e.stream??!1})}};var kN=class extends dc{create(e,r){return this._client.post("/v1/messages/batches",{body:e,...r})}retrieve(e,r){return this._client.get(`/v1/messages/batches/${e}`,r)}list(e={},r){return Pg(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",oU,{query:e,...r})}delete(e,r){return this._client.delete(`/v1/messages/batches/${e}`,r)}cancel(e,r){return this._client.post(`/v1/messages/batches/${e}/cancel`,r)}async results(e,r){let n=await this.retrieve(e);if(!n.results_url)throw new Or(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...r,headers:{Accept:"application/binary",...r?.headers},__binaryResponse:!0})._thenUnwrap((o,i)=>eU.fromResponse(i.response,i.controller))}},oU=class extends Dx{};kN.MessageBatchesPage=oU;var af=function(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r},vn=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Tg,CI,b5,fae,_5,v5,pae,w5,cP,S5,mae,hae,iU,gae,yae,wje,mDt,Sje,xje,Cje,Oje,hDt,gDt="__json_buf",bae=class t{constructor(){Tg.add(this),this.messages=[],this.receivedMessages=[],CI.set(this,void 0),this.controller=new AbortController,b5.set(this,void 0),fae.set(this,()=>{}),_5.set(this,()=>{}),v5.set(this,void 0),pae.set(this,()=>{}),w5.set(this,()=>{}),cP.set(this,{}),S5.set(this,!1),mae.set(this,!1),hae.set(this,!1),iU.set(this,!1),gae.set(this,void 0),yae.set(this,void 0),Sje.set(this,e=>{if(af(this,mae,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new ed),e instanceof ed)return af(this,hae,!0,"f"),this._emit("abort",e);if(e instanceof Or)return this._emit("error",e);if(e instanceof Error){let r=new Or(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new Or(String(e)))}),af(this,b5,new Promise((e,r)=>{af(this,fae,e,"f"),af(this,_5,r,"f")}),"f"),af(this,v5,new Promise((e,r)=>{af(this,pae,e,"f"),af(this,w5,r,"f")}),"f"),vn(this,b5,"f").catch(()=>{}),vn(this,v5,"f").catch(()=>{})}get response(){return vn(this,gae,"f")}get request_id(){return vn(this,yae,"f")}async withResponse(){let e=await vn(this,b5,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let r=new t;return r._run(()=>r._fromReadableStream(e)),r}static createMessage(e,r,n){let o=new t;for(let i of r.messages)o._addMessageParam(i);return o._run(()=>o._createMessage(e,{...r,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages",{body:e,timeout:this._client._options.timeout??(e.stream?6e5:this._client._calculateNonstreamingTimeout(e.max_tokens)),...r,stream:e.stream??!1})}stream(e,r){return bae.createMessage(this,e,r)}countTokens(e,r){return this._client.post("/v1/messages/count_tokens",{body:e,...r})}},yDt={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};dP.Batches=kN;dP.MessageBatchesPage=oU;var OI=class extends dc{retrieve(e,r){return this._client.get(`/v1/models/${e}`,r)}list(e={},r){return Pg(e)?this.list({},e):this._client.getAPIList("/v1/models",$N,{query:e,...r})}},$N=class extends Dx{};OI.ModelInfosPage=$N;var bDt,mi=class extends tae{constructor({baseURL:e=nae("ANTHROPIC_BASE_URL"),apiKey:r=nae("ANTHROPIC_API_KEY")??null,authToken:n=nae("ANTHROPIC_AUTH_TOKEN")??null,...o}={}){let i={apiKey:r,authToken:n,...o,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&lDt())throw new Or(`It looks like you're running in a browser-like environment.
2025-07-05 20:48:33 +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.,
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
2025-07-12 10:26:56 +08:00
`);super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new FN(this),this.messages=new dP(this),this.models=new OI(this),this.beta=new Lx(this),this._options=i,this.apiKey=r,this.authToken=n}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01",...this._options.defaultHeaders}}validateHeaders(e,r){if(!(this.apiKey&&e["x-api-key"])&&r["x-api-key"]!==null&&!(this.authToken&&e.authorization)&&r.authorization!==null)throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}authHeaders(e){let r=this.apiKeyAuth(e),n=this.bearerAuth(e);return r!=null&&!f5(r)?r:n!=null&&!f5(n)?n:{}}apiKeyAuth(e){return this.apiKey==null?{}:{"X-Api-Key":this.apiKey}}bearerAuth(e){return this.authToken==null?{}:{Authorization:`Bearer ${this.authToken}`}}};bDt=mi;mi.Anthropic=bDt;mi.HUMAN_PROMPT=`
2025-07-05 20:48:33 +08:00
Human:`;mi.AI_PROMPT=`
2025-07-12 10:26:56 +08:00
Assistant:`;mi.DEFAULT_TIMEOUT=6e5;mi.AnthropicError=Or;mi.APIError=cc;mi.APIConnectionError=wI;mi.APIConnectionTimeoutError=Zq;mi.APIUserAbortError=ed;mi.NotFoundError=i5;mi.ConflictError=a5;mi.RateLimitError=u5;mi.BadRequestError=r5;mi.AuthenticationError=n5;mi.InternalServerError=l5;mi.PermissionDeniedError=o5;mi.UnprocessableEntityError=s5;mi.toFile=tDt;mi.fileFromPath=Gie;mi.Completions=FN;mi.Messages=dP;mi.Models=OI;mi.ModelInfosPage=$N;mi.Beta=Lx;var{HUMAN_PROMPT:yWo,AI_PROMPT:bWo}=mi;gs();Qd();Dn();fx();Wm();Ec();Sm();mB();Km();gy();var x5=class extends PR{static lc_name(){return"AnthropicToolsOutputParser"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","anthropic","output_parsers"]}),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"keyName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"returnSingle",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"zodSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){let r=e;if(typeof e=="string")try{r=JSON.parse(e)}catch(o){throw new vm(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(o.message)}`,e)}else r=e;if(this.zodSchema===void 0)return r;let n=await this.zodSchema.safeParseAsync(r);if(n.success)return n.data;throw new vm(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.errors)}`,JSON.stringify(r,null,2))}async parseResult(e){let r=e.flatMap(i=>{let{message:a}=i;return Array.isArray(a.content)?Pje(a.content)[0]:[]});if(r[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");let[n]=r;return await this._validateResult(n.args)}};function Pje(t){let e=[];for(let r of t)r.type==="tool_use"&&e.push({name:r.name,args:r.input,id:r.id,type:"tool_call"});return e}function _Dt(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:typeof t=="string"?{type:"tool",name:t}:t}gs();function vDt(t){return t==null||typeof t!="object"||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}function wDt(t){let e=lme({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let r;try{r=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
2025-07-05 20:48:33 +08:00
`))}if(r.protocol==="http:"||r.protocol==="https:")return{type:"url",url:t};throw new Error([`Invalid image URL protocol: ${JSON.stringify(r.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
2025-07-12 10:26:56 +08:00
`))}function LZr(t){let e=[];for(let r of t)if(r._getType()==="tool")if(typeof r.content=="string"){let n=e[e.length-1];n?._getType()==="human"&&Array.isArray(n.content)&&"type"in n.content[0]&&n.content[0].type==="tool_result"?n.content.push({type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}):e.push(new Os({content:[{type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}]}))}else e.push(new Os({content:[{type:"tool_result",content:Eje(r.content),tool_use_id:r.tool_call_id}]}));else e.push(r);return e}function SDt(t){if(t.id===void 0)throw new Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:t.id,name:t.name,input:t.args}}var FZr={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){let e=lme({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){let e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}};function Eje(t){let e=["tool_use","tool_result","input_json_delta"],r=["text","text_delta"];return typeof t=="string"?t:t.map(o=>{if(jE(o))return W4e(o,FZr);let i="cache_control"in o?o.cache_control:void 0;if(o.type==="image_url"){let a;return typeof o.image_url=="string"?a=wDt(o.image_url):a=wDt(o.image_url.url),{type:"image",source:a,...i?{cache_control:i}:{}}}else{if(vDt(o))return o;if
2025-07-05 20:48:33 +08:00
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
2025-07-12 10:26:56 +08:00
`,t}function Tje(t){let e;return t.status===400&&t.message.includes("tool")?e=vae(t,"INVALID_TOOL_RESULTS"):t.status===401?e=vae(t,"MODEL_AUTHENTICATION"):t.status===404?e=vae(t,"MODEL_NOT_FOUND"):t.status===429?e=vae(t,"MODEL_RATE_LIMIT"):e=t,e}function $Zr(t){return!!(t.tools&&t.tools.length>0)}function BZr(t){for(let e of t.messages??[])if(typeof e.content!="string"){for(let r of e.content??[])if(typeof r=="object"&&r!=null&&r.type==="document"&&typeof r.citations=="object"&&r.citations.enabled)return!0}return!1}function qZr(t){return!!(t.thinking&&t.thinking.type==="enabled")}function UZr(t){return"input_schema"in t}function zZr(t){if(typeof t.content=="string")return t.content;if(Array.isArray(t.content)&&t.content.length>=1&&"input"in t.content[0])return typeof t.content[0].input=="string"?t.content[0].input:JSON.stringify(t.content[0].input);if(Array.isArray(t.content)&&t.content.length>=1&&"text"in t.content[0])return t.content[0].text}var Aje=class extends Js{static lc_name(){return"ChatAnthropic"}get lc_secrets(){return{anthropicApiKey:"ANTHROPIC_API_KEY",apiKey:"ANTHROPIC_API_KEY"}}get lc_aliases(){return{modelName:"model"}}constructor(e){if(super(e??{}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"anthropicApiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"topK",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:2048}),Object.defineProperty(this,"modelName",{enumerable:!0,configurable:!0,writable:!0,value:"claude-2.1"}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"claude-2.1"}),Object.defineProperty(this,"invocationKwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stopSequences",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"clientOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"thinking",{enumerable:!0,configurable:!0,writable:!0,value:{type:"disabled"}}),Object.defineProperty(this,"batchClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streamingClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streamUsage",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"createClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.anthropicApiKey=e?.apiKey??e?.anthropicApiKey??ot("ANTHROPIC_API_KEY"),!this.anthropicApiKey&&!e?.createClient)throw new Error("Anthropic API key not found");this.clientOptions=e?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=e?.anthropicApiUrl,this.modelName=e?.model??e?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=e?.invocationKwargs??{},this.temperature=e?.temperature??this.temperature,this.topK=e?.topK??this.topK,this.topP=e?.topP??this.topP,this.maxTokens=e?.maxTokensToSample??e?.maxTokens??this.maxTokens,this.stopSequences=e?.stopSequences??this.stopSequences,this.streaming=e?.streaming??!1,this.streamUsage=e?.streamUsage??this.streamUsage,this.thinking=e?.thinking??this.thinking,this.createClient=e?.createClient??(r=>new mi(r))}getLsParams(e){let r=this.invocationParams(e);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:r.temperature??void 0,ls_max_tokens:r.max_tokens??void 0,ls_stop:e.stop}}formatStructuredToolToAnthropic(e){if(!(!e||!e.l
2025-07-05 20:48:33 +08:00
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
2025-07-12 10:26:56 +08:00
`,t}function qN(t){let e;return t.constructor.name===Xf.name?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===Li.name?(e=new Error(t.message),e.name="AbortError"):t.status===400&&t.message.includes("tool_calls")?e=C5(t,"INVALID_TOOL_RESULTS"):t.status===401?e=C5(t,"MODEL_AUTHENTICATION"):t.status===429?e=C5(t,"MODEL_RATE_LIMIT"):t.status===404?e=C5(t,"MODEL_NOT_FOUND"):e=t,e}function Ije(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}function HZr(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function ODt(t){let e=["namespace functions {",""];for(let r of t)r.description&&e.push(`// ${r.description}`),Object.keys(r.parameters.properties??{}).length>0?(e.push(`type ${r.name} = (_: {`),e.push(PDt(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
`)}function PDt(t,e){let r=[];for(let[n,o]of Object.entries(t.properties??{}))o.description&&e<2&&r.push(`// ${o.description}`),t.required?.includes(n)?r.push(`${n}: ${Sae(o,e)},`):r.push(`${n}?: ${Sae(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
`)}function Sae(t,e){if(HZr(t))return t.anyOf.map(r=>Sae(r,e)).join(" | ");switch(t.type){case"string":return t.enum?t.enum.map(r=>`"${r}"`).join(" | "):"string";case"number":return t.enum?t.enum.map(r=>`${r}`).join(" | "):"number";case"integer":return t.enum?t.enum.map(r=>`${r}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",PDt(t,e+2),"}"].join(`
`);case"array":return t.items?`${Sae(t.items,e)}[]`:"any[]";default:return""}}Km();uq();function EDt(t,e){let r;if(rc(t)){let n=Bne({name:t.name,parameters:t.schema,description:t.description});n.function.parameters?r={type:n.type,function:{name:n.function.name,description:n.function.description,parameters:n.function.parameters,...e?.strict!==void 0?{strict:e.strict}:{}}}:r={type:"function",function:TA(t,e)}}else r=t;return e?.strict!==void 0&&(r.function.strict=e.strict),r}function VZr(t){return t.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}function jje(t){let e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":{if(!Cs.isInstance(t))throw new Error("Invalid generic chat message");return VZr(t)}default:throw new Error(`Unknown message type: ${e}`)}}function Rje(t,e){return t.flatMap(r=>{let n=jje(r);n==="system"&&Nje(e)&&(n="developer");let o={role:n,content:r.content};if(r.name!=null&&(o.name=r.name),r.additional_kwargs.function_call!=null&&(o.function_call=r.additional_kwargs.function_call,o.content=""),Oi(r)&&r.tool_calls?.length?(o.tool_calls=r.tool_calls.map(Ox),o.content=""):(r.additional_kwargs.tool_calls!=null&&(o.tool_calls=r.additional_kwargs.tool_calls),r.tool_call_id!=null&&(o.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio){let i={role:"assistant",audio:{id:r.additional_kwargs.audio.id}};return[o,i]}return o})}var aU="__openai_function_call_ids__";function TDt(t,e){return t.flatMap(r=>{let n=jje(r);if(n==="system"&&Nje(e)&&(n="developer"),n==="function")throw new Error("Function messages are not supported in Responses API");if(n==="tool"){let o=r;return o.additional_kwargs?.type==="computer_call_output"?{type:"computer_call_output",output:(()=>{if(typeof o.content=="string")return{type:"computer_screenshot",image_url:o.content};if(Array.isArray(o.content)){let a=o.content.find(u=>u.type==="computer_screenshot");if(a)return a;let s=o.content.find(u=>u.type==="image_url");if(s)return{type:"computer_screenshot",image_url:typeof s.image_url=="string"?s.image_url:s.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:o.tool_call_id}:{type:"function_call_output",call_id:o.tool_call_id,id:o.id,output:typeof o.content!="string"?JSON.stringify(o.content):o.content}}if(n==="assistant"){let o=[];r.additional_kwargs.reasoning!=null&&(u=>typeof u=="object"&&u!=null&&"type"in u&&u.type==="reasoning")(r.additional_kwargs.reasoning)&&o.push(r.additional_kwargs.reasoning);let{content:i}=r;r.additional_kwargs.refusal!=null&&(typeof i=="string"&&(i=[{type:"output_text",text:i,annotations:[]}]),i=[...i,{type:"refusal",refusal:r.additional_kwargs.refusal}]),o.push({type:"message",role:"assistant",content:typeof i=="string"?i:i.flatMap(s=>s.type==="text"?{type:"output_text",text:s.text,annotations:s.annotations??[]}:s.type==="output_text"||s.type==="refusal"?s:[])});let a=r.additional_kwargs[aU];if(Oi(r)&&r.tool_calls?.length?o.push(...r.tool_calls.map(s=>({type:"function_call",name:s.name,arguments:JSON.stringify(s.args),call_id:s.id,id:a?.[s.id]}))):r.additional_kwargs.tool_calls!=null&&o.push(...r.additional_kwargs.tool_calls.map(s=>({type:"function_call",name:s.function.name,call_id:s.id,id:a?.[s.id],arguments:s.function.arguments}))),r.additional_kwargs.tool_outputs!=null){let u=r.additional_kwargs.tool_outputs?.filter(l=>l.type==="computer_call");u.length>0&&o.push(...u)}return o}return n==="user"?{type:"message",role:"user",content:typeof r.content=="string"?r.content:r.content.flatMap(o=>{if(o.type==="text")return{type:"input_text",text:o.text};if(o.type==="image_url"){let i=typeof o.image_url=="string"?o.image_url:o.image_url.url,a=typeof o.image_url=="string"?"auto":o.image_url.detail;return{type:"input_image",image_url:i,detail:a}}return o.type==="input_text"||o.type=
`);o.enqueue(s)}catch(i){o.error(i)}},async cancel(){await r.return?.()}})}},zje=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,o]=eXr(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},hU=class t{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){let r=this.decodeText(e);if(this.trailingCR&&(r="\r"+r,this.trailingCR=!1),r.endsWith("\r")&&(this.trailingCR=!0,r=r.slice(0,-1)),!r)return[];let n=t.NEWLINE_CHARS.has(r[r.length-1]||""),o=r.split(t.NEWLINE_REGEXP);return o.length===1&&!n?(this.buffer.push(o[0]),[]):(this.buffer.length>0&&(o=[this.buffer.join("")+o[0],...o.slice(1)],this.buffer=[]),n||(this.buffer=[o.pop()||""]),o)}decodeText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new fc(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new fc(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new fc("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}};hU.NEWLINE_CHARS=new Set([`
`,"\r","\v","\f","","","","\x85","\u2028","\u2029"]);hU.NEWLINE_REGEXP=/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g;function eXr(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}function NDt(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var DDt=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",LDt=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Iae(t),Iae=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",tXr=t=>LDt(t)||DDt(t)||qje(t);async function Wje(t,e,r){if(t=await t,r??(r=LDt(t)?{lastModified:t.lastModified,type:t.type}:{}),DDt(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file"),new Oae([o],e,r)}let n=await rXr(t);if(e||(e=oXr(t)??"unknown_file"),!r.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new Oae(n,e,r)}async function rXr(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Iae(t))e.push(await t.arrayBuffer());else if(iXr(t))for await(let r of t)e.push(r);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${nXr(t)}`);return e}function nXr(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function oXr(t){return Hje(t.name)||Hje(t.filename)||Hje(t.path)?.split(/[\\/]/).pop()}var Hje=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},iXr=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Kje=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody";var P5=async t=>{let e=await FDt(t.body);return $je(e,t)},FDt=async t=>{let e=new Fje;return await Promise.all(Object.entries(t||{}).map(([r,n])=>Vje(e,r,n))),e};var Vje=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(tXr(r)){let n=await Wje(r);t.append(e,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>Vje(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>Vje(t,`${e}[${n}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var sXr=function(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r},uXr=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},Mae;async function zDt(t){let{response:e}=t;if(t.options.stream)return gU("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):Aae.fromSSEResponse(e,t.controller);if(e.status===204)return null;if(t.options.__binaryResponse)return e;let r=e.headers.get("content-type");if(r?.includes("application/json")||r?.includes("application/vnd.api+json")){let i=await e.json();return gU("response",e.status,e.url,e.headers,i),i}let o=await e.text();return gU("response",e.status,e.url,e.headers,o),o}var Rae=class t extends Promise{constructor(e
2025-07-05 20:48:33 +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-07-12 10:26:56 +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 AI(this),this.chat=new TI(this),this.embeddings=new II(this),this.audio=new EI(this),this.models=new MI(this),this._options=o,this.apiKey=r}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}};VDt=bs;bs.Groq=VDt;bs.GroqError=fc;bs.APIError=Fl;bs.APIConnectionError=fP;bs.APIConnectionTimeoutError=HN;bs.APIUserAbortError=PI;bs.NotFoundError=cU;bs.ConflictError=dU;bs.RateLimitError=pU;bs.BadRequestError=sU;bs.AuthenticationError=uU;bs.InternalServerError=mU;bs.PermissionDeniedError=lU;bs.UnprocessableEntityError=fU;bs.toFile=Wje;bs.fileFromPath=Pae;var{GroqError:PGo,APIError:EGo,APIConnectionError:TGo,APIConnectionTimeoutError:AGo,APIUserAbortError:IGo,NotFoundError:MGo,ConflictError:RGo,RateLimitError:jGo,BadRequestError:NGo,AuthenticationError:DGo,InternalServerError:LGo,PermissionDeniedError:FGo,UnprocessableEntityError:kGo}=Uje;(function(t){t.Completions=AI,t.Chat=TI,t.Embeddings=II,t.Audio=EI,t.Models=MI})(bs||(bs={}));var WDt=bs;Sm();gy();aq();Km();function OXr(t){let e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";default:throw new Error(`Unknown message type: ${e}`)}}function KDt(t){return t.map(e=>{if(typeof e.content!="string")throw new Error("Non string message content not supported");let r={role:OXr(e),content:e.content,name:e.name,function_call:e.additional_kwargs.function_call,tool_calls:e.additional_kwargs.tool_calls,tool_call_id:e.tool_call_id};return Oi(e)&&e.tool_calls?.length?r.tool_calls=e.tool_calls.map(Ox):(e.additional_kwargs.tool_calls!=null&&(r.tool_calls=e.additional_kwargs.tool_calls),e.tool_call_id!=null&&(r.tool_call_id=e.tool_call_id)),r})}function PXr(t,e){let r=t.tool_calls;switch(t.role){case"assistant":{let n=[],o=[];for(let i of r??[])try{n.push(Jp(i,{returnId:!0}))}catch(a){o.push(Xm(i,a.message))}return new gn({content:t.content||"",additional_kwargs:{tool_calls:r},tool_calls:n,invalid_tool_calls:o,usage_metadata:e})}default:return new Cs(t.content||"",t.role??"unknown")}}function EXr(t,e){if(t?.length)return t.map(r=>({id:r.id,name:r.function?.name,args:r.function?.arguments,type:"tool_call_chunk",index:e}))}function TXr(t,e,r){let{role:n}=t,o=t.content??"",i;t.function_call?i={function_call:t.function_call}:t.tool_calls?i={tool_calls:t.tool_calls}:i={};let a,s;if(r?.usage&&(a={input_tokens:r.usage.prompt_tokens,output_tokens:r.usage.completion_tokens,total_tokens:r.usage.total_tokens},s=r.id),n==="user")return{message:new Mf({content:o})};if(n==="assistant"){let u=EXr(t.tool_calls,e);return{message:new dr({content:o,additional_kwargs:i,tool_call_chunks:u?u.map(l=>({type:l.type,args:l.args,index:l.index})):void 0,usage_metadata:a,id:s}),toolCallData:u?u.map(l=>({id:l.id??"",name:l.name??"",index:l.index??e,type:"tool_call_chunk"})):void 0}}else return n==="system"?{message:new Rd({content:o})}:{message:new If({content:o,role:n})}}var Nae=class extends Js{static lc_name(){return"ChatGroq"}_llmType(){return"groq"}get lc_secrets(){return{apiKey:"GROQ_API_KEY"}}constructor(e){super(e??{}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","chat_models","groq"]}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"modelName",{enumerable:!0,configurable:!0,writable:!0,value:"mixtral-8x7b-32768"}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"mixtral-8x7b-32768"}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:.7}),Object.defineProperty(this,"stop",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stopSequences",{enumerabl
2025-07-05 20:48:33 +08:00
Received: ${JSON.stringify(o,null,2)}`)};if(typeof o=="string")return o;if(Array.isArray(o)){let s=e(i),u=[];return o.forEach(l=>{if(l.type==="text"||l.type==="image_url")u.push(a(l,s));else throw new Error('Mistral only supports types "text" or "image_url" for complex message types.')}),u}throw new Error(`Message content must be a string or an array.
2025-07-12 10:26:56 +08:00
Received: ${JSON.stringify(o,null,2)}`)},n=o=>{if(Oi(o)&&o.tool_calls?.length)return o.tool_calls.map(i=>({...i,id:FLe(i.id??"")})).map(Ox)};return t.map(o=>{let i=n(o),a=r(o.content,o.getType());return"tool_call_id"in o&&typeof o.tool_call_id=="string"?{role:e(o.getType()),content:a,name:o.name,toolCallId:FLe(o.tool_call_id)}:Oi(o)?i===void 0?{role:e(o.getType()),content:a}:{role:e(o.getType()),toolCalls:i}:{role:e(o.getType()),content:a}})}function Lwn(t,e){let{message:r}=t;if(r===void 0)throw new Error("No message found in response");let n=[];"toolCalls"in r&&Array.isArray(r.toolCalls)&&(n=r.toolCalls);let o=kLe(r.content);switch(r.role){case"assistant":{let i=[],a=[];for(let s of n)try{let u=Jp(s,{returnId:!0});i.push({...u,id:u.id??Fae().replace(/-/g,"")})}catch(u){a.push(Xm(s,u.message))}return new gn({content:o,tool_calls:i,invalid_tool_calls:a,additional_kwargs:{},usage_metadata:e?{input_tokens:e.promptTokens,output_tokens:e.completionTokens,total_tokens:e.totalTokens}:void 0})}default:return new Os({content:o})}}function Fwn(t,e){if(!t.content&&!t.toolCalls)return e?new dr({content:"",usage_metadata:e?{input_tokens:e.promptTokens,output_tokens:e.completionTokens,total_tokens:e.totalTokens}:void 0}):null;let r=t.toolCalls?.length?t.toolCalls?.map((s,u)=>({...s,index:u,id:s.id??Fae().replace(/-/g,""),type:"function"})):void 0,n="assistant";t.role&&(n=t.role);let o=kLe(t.content),i,a=[];if(r!==void 0)for(let s of r){let u=s.function?.arguments,l=u===void 0||typeof u=="string"?u:JSON.stringify(u);a.push({name:s.function?.name,args:l,id:s.id,index:s.index,type:"tool_call_chunk"})}else i={};return n==="user"?new Mf({content:o}):n==="assistant"?new dr({content:o,tool_call_chunks:a,additional_kwargs:i,usage_metadata:e?{input_tokens:e.promptTokens,output_tokens:e.completionTokens,total_tokens:e.totalTokens}:void 0}):n==="tool"?new Th({content:o,additional_kwargs:i,tool_call_id:r?.[0].id??""}):n==="function"?new ym({content:o,additional_kwargs:i}):new If({content:o,role:n})}function r3t(t){return t.map(e=>{if("function"in e)return e;let r=e.description??`Tool: ${e.name}`;return{type:"function",function:{name:e.name,description:r,parameters:So(e.schema)}}})}var zle=class extends Js{static lc_name(){return"ChatMistralAI"}constructor(e){super(e??{}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","chat_models","mistralai"]}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"mistral-small-latest"}),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"endpoint",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serverURL",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:.7}),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"safeMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"safePrompt",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"randomSeed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"seed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"streamUsage",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"beforeRequestHooks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"requestErrorHooks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"r
2025-07-05 20:48:33 +08:00
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
2025-07-12 10:26:56 +08:00
`,t}function PD(t){let e;return t.constructor.name===Xf.name?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===Li.name?(e=new Error(t.message),e.name="AbortError"):t.status===400&&t.message.includes("tool_calls")?e=mW(t,"INVALID_TOOL_RESULTS"):t.status===401?e=mW(t,"MODEL_AUTHENTICATION"):t.status===429?e=mW(t,"MODEL_RATE_LIMIT"):t.status===404?e=mW(t,"MODEL_NOT_FOUND"):e=t,e}function $Le(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}function kwn(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function a3t(t){let e=["namespace functions {",""];for(let r of t)r.description&&e.push(`// ${r.description}`),Object.keys(r.parameters.properties??{}).length>0?(e.push(`type ${r.name} = (_: {`),e.push(s3t(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
`)}function s3t(t,e){let r=[];for(let[n,o]of Object.entries(t.properties??{}))o.description&&e<2&&r.push(`// ${o.description}`),t.required?.includes(n)?r.push(`${n}: ${Hle(o,e)},`):r.push(`${n}?: ${Hle(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
`)}function Hle(t,e){if(kwn(t))return t.anyOf.map(r=>Hle(r,e)).join(" | ");switch(t.type){case"string":return t.enum?t.enum.map(r=>`"${r}"`).join(" | "):"string";case"number":return t.enum?t.enum.map(r=>`${r}`).join(" | "):"number";case"integer":return t.enum?t.enum.map(r=>`${r}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",s3t(t,e+2),"}"].join(`
`);case"array":return t.items?`${Hle(t.items,e)}[]`:"any[]";default:return""}}Km();uq();function u3t(t,e){let r;if(rc(t)){let n=Bne({name:t.name,parameters:t.schema,description:t.description});n.function.parameters?r={type:n.type,function:{name:n.function.name,description:n.function.description,parameters:n.function.parameters,...e?.strict!==void 0?{strict:e.strict}:{}}}:r={type:"function",function:TA(t,e)}}else r=t;return e?.strict!==void 0&&(r.function.strict=e.strict),r}function $wn(t){return t.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}function ULe(t){let e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":{if(!Cs.isInstance(t))throw new Error("Invalid generic chat message");return $wn(t)}default:throw new Error(`Unknown message type: ${e}`)}}function qLe(t,e){return t.flatMap(r=>{let n=ULe(r);n==="system"&&zLe(e)&&(n="developer");let o={role:n,content:r.content};if(r.name!=null&&(o.name=r.name),r.additional_kwargs.function_call!=null&&(o.function_call=r.additional_kwargs.function_call,o.content=""),Oi(r)&&r.tool_calls?.length?(o.tool_calls=r.tool_calls.map(Ox),o.content=""):(r.additional_kwargs.tool_calls!=null&&(o.tool_calls=r.additional_kwargs.tool_calls),r.tool_call_id!=null&&(o.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio){let i={role:"assistant",audio:{id:r.additional_kwargs.audio.id}};return[o,i]}return o})}var HU="__openai_function_call_ids__";function l3t(t,e){return t.flatMap(r=>{let n=ULe(r);if(n==="system"&&zLe(e)&&(n="developer"),n==="function")throw new Error("Function messages are not supported in Responses API");if(n==="tool"){let o=r;return o.additional_kwargs?.type==="computer_call_output"?{type:"computer_call_output",output:(()=>{if(typeof o.content=="string")return{type:"computer_screenshot",image_url:o.content};if(Array.isArray(o.content)){let a=o.content.find(u=>u.type==="computer_screenshot");if(a)return a;let s=o.content.find(u=>u.type==="image_url");if(s)return{type:"computer_screenshot",image_url:typeof s.image_url=="string"?s.image_url:s.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:o.tool_call_id}:{type:"function_call_output",call_id:o.tool_call_id,id:o.id,output:typeof o.content!="string"?JSON.stringify(o.content):o.content}}if(n==="assistant"){let o=[];r.additional_kwargs.reasoning!=null&&(u=>typeof u=="object"&&u!=null&&"type"in u&&u.type==="reasoning")(r.additional_kwargs.reasoning)&&o.push(r.additional_kwargs.reasoning);let{content:i}=r;r.additional_kwargs.refusal!=null&&(typeof i=="string"&&(i=[{type:"output_text",text:i,annotations:[]}]),i=[...i,{type:"refusal",refusal:r.additional_kwargs.refusal}]),o.push({type:"message",role:"assistant",content:typeof i=="string"?i:i.flatMap(s=>s.type==="text"?{type:"output_text",text:s.text,annotations:s.annotations??[]}:s.type==="output_text"||s.type==="refusal"?s:[])});let a=r.additional_kwargs[HU];if(Oi(r)&&r.tool_calls?.length?o.push(...r.tool_calls.map(s=>({type:"function_call",name:s.name,arguments:JSON.stringify(s.args),call_id:s.id,id:a?.[s.id]}))):r.additional_kwargs.tool_calls!=null&&o.push(...r.additional_kwargs.tool_calls.map(s=>({type:"function_call",name:s.function.name,call_id:s.id,id:a?.[s.id],arguments:s.function.arguments}))),r.additional_kwargs.tool_outputs!=null){let u=r.additional_kwargs.tool_outputs?.filter(l=>l.type==="computer_call");u.length>0&&o.push(...u)}return o}return n==="user"?{type:"message",role:"user",content:typeof r.content=="string"?r.content:r.content.flatMap(o=>{if(o.type==="text")return{type:"input_text",text:o.text};if(o.type==="image_url"){let i=typeof o.image_url=="string"?o.image_url:o.image_url.url,a=typeof o.image_url=="string"?"auto":o.image_url.detail;return{type:"input_image",image_url:i,detail:a}}return o.type==="input_text"||o.type=
2025-07-05 20:48:33 +08:00
without CORS Error: `+ei(n)+`
2025-07-12 10:26:56 +08:00
with CORS Error: `+ei(o);throw new Error(i)}}}findModelByName(e){return ue().activeModels.find(n=>n.name===e)}};nr();gs();var VU=class{},f3t=(t,e)=>{if(e!==void 0)return t[e];let r=Object.keys(t);if(r.length===1)return t[r[0]]},Gle=(t,e)=>{let r=f3t(t,e);if(!r){let n=Object.keys(t);throw new Error(`input values have ${n.length} keys, you must specify an input key or pass only 1 key as input`)}return r},VLe=(t,e)=>{let r=f3t(t,e);if(!r&&r!==""){let n=Object.keys(t);throw new Error(`output values have ${n.length} keys, you must specify an output key or pass only 1 key as output`)}return r};yR();OR();var WLe=class extends gp{addUserMessage(e){return this.addMessage(new Os(e))}addAIChatMessage(e){return this.addMessage(new gn(e))}addAIMessage(e){return this.addMessage(new gn(e))}async addMessages(e){for(let r of e)await this.addMessage(r)}clear(){throw new Error("Not implemented.")}},WU=class extends WLe{constructor(e){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","stores","message","in_memory"]}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}};var gb=class extends VU{constructor(e){super(),Object.defineProperty(this,"chatHistory",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"returnMessages",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"inputKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.chatHistory=e?.chatHistory??new WU,this.returnMessages=e?.returnMessages??this.returnMessages,this.inputKey=e?.inputKey??this.inputKey,this.outputKey=e?.outputKey??this.outputKey}async saveContext(e,r){await this.chatHistory.addUserMessage(Gle(e,this.inputKey)),await this.chatHistory.addAIChatMessage(VLe(r,this.outputKey))}async clear(){await this.chatHistory.clear()}};var gW=class extends gb{constructor(e){super({chatHistory:e?.chatHistory,returnMessages:e?.returnMessages??!1,inputKey:e?.inputKey,outputKey:e?.outputKey}),Object.defineProperty(this,"humanPrefix",{enumerable:!0,configurable:!0,writable:!0,value:"Human"}),Object.defineProperty(this,"aiPrefix",{enumerable:!0,configurable:!0,writable:!0,value:"AI"}),Object.defineProperty(this,"memoryKey",{enumerable:!0,configurable:!0,writable:!0,value:"history"}),this.humanPrefix=e?.humanPrefix??this.humanPrefix,this.aiPrefix=e?.aiPrefix??this.aiPrefix,this.memoryKey=e?.memoryKey??this.memoryKey}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){let r=await this.chatHistory.getMessages();return this.returnMessages?{[this.memoryKey]:r}:{[this.memoryKey]:Rf(r,this.humanPrefix,this.aiPrefix)}}};gs();gs();KLe();qE();gs();var yW=class extends gb{constructor(e){super({returnMessages:e?.returnMessages??!1,chatHistory:e?.chatHistory,inputKey:e?.inputKey,outputKey:e?.outputKey}),Object.defineProperty(this,"humanPrefix",{enumerable:!0,configurable:!0,writable:!0,value:"Human"}),Object.defineProperty(this,"aiPrefix",{enumerable:!0,configurable:!0,writable:!0,value:"AI"}),Object.defineProperty(this,"memoryKey",{enumerable:!0,configurable:!0,writable:!0,value:"history"}),Object.defineProperty(this,"k",{enumerable:!0,configurable:!0,writable:!0,value:5}),this.humanPrefix=e?.humanPrefix??this.humanPrefix,this.aiPrefix=e?.aiPrefix??this.aiPrefix,this.memoryKey=e?.memoryKey??this.memoryKey,this.k=e?.k??this.k}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){let r=await this.chatHistory.getMessages();return this.returnMessages?{[this.memoryKey]:r.slice(-this.k*2)}:{[this.memoryKey]:Rf(r.slice(-this.k*2),this.humanPrefix,this.aiPrefix)}}};iie();Nhe();gs();yR();KLe();gs();gs();var bW=class t{constructor(){this.initMemory(),xa(()=>{let e=this.memory?.chatHistory;this.initMemory(e)})}static getInstance(){return t.instance||(t.instance
2025-07-05 20:48:33 +08:00
Answer the question with as detailed as possible based only on the following context:
{context}
Question: {question}
2025-07-12 10:26:56 +08:00
`;this.qaPrompt=xp.fromMessages([BE.fromTemplate(e)])}escapeTemplateString(e){return e.replace(/\{/g,"{{").replace(/\}/g,"}}")}getChatPrompt(){return this.chatPrompt}async getQAPrompt({question:e,context:r,systemMessage:n}){return await this.qaPrompt.format({question:e,context:r,system_message:n})}};var vW=class{constructor(e,r){this.retrievedDocuments=[];this.chatMessages=[];this.chatMessages=[],this.app=e,this.vectorStoreManager=r,this.memoryManager=bW.getInstance(),this.chatModelManager=ED.getInstance(),this.promptManager=_W.getInstance(),this.initialize(),xa(async()=>{await this.createChainWithNewModel()})}getRetrievedDocuments(){return this.retrievedDocuments}async initialize(){await this.createChainWithNewModel()}getChain(){return this.chain}getRetrievalChain(){return this.retrievalChain}validateChainType(e){if(e==null)throw new Error("No chain type set")}validateChatModel(){if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){let e="Chat model is not initialized properly, check your API key in Copilot setting and make sure you have API access.";throw new Jle.Notice(e),new Error(e)}}validateChainInitialization(){(!this.chain||!mVe(this.chain))&&(console.error("Chain is not initialized properly, re-initializing chain: ",Fh()),this.createChainWithNewModel({},!1))}storeRetrieverDocuments(e){this.retrievedDocuments=e}async createChainWithNewModel(e={},r=!0){let n=Fh(),o=Mc();if(n==="project"&&!o)return;let i=n==="project"?o?.projectModelKey:hJ();if(!i)throw new Jle.Notice("No model key found"),new Error("No model key found");try{if(r){let a=tJ(i,ue().activeModels);if(a||(console.error("Resetting default model. No model configuration found for: ",i),a=Zb[0],i=a.name+"|"+a.provider),n==="project"&&!a.projectEnabled){let u=ue().activeModels.find(l=>l.enabled&&l.projectEnabled);if(u)a=u,i=u.name+"|"+u.provider,new Jle.Notice(`Model ${a.name} is not available in project mode. Switching to ${u.name}.`);else throw new Error("No project-enabled models available. Please enable a model for project mode in settings.")}let s={...a,...o?.modelConfigs};await this.chatModelManager.setChatModel(s)}this.setChain(n,e),ie(`Setting model to ${i}`)}catch(a){fe(`createChainWithNewModel failed: ${a}`),ie(`modelKey: ${i}`)}}async setChain(e,r={}){if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){console.error("setChain failed: No chat model set.");return}this.validateChainType(e);let n=this.chatModelManager.getChatModel(),o=this.memoryManager.getMemory(),i=this.promptManager.getChatPrompt();switch(e){case"llm_chain":{this.chain=d4.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),UR("llm_chain");break}case"vault_qa":{await this.initializeQAChain(r);let a=new jx({minSimilarityScore:.01,maxK:ue().maxSourceChunks,salientTerms:[]});this.retrievalChain=d4.createConversationalRetrievalChain({llm:n,retriever:a,systemMessage:Yb()},this.storeRetrieverDocuments.bind(this),ue().debug),UR("vault_qa"),ue().debug&&(console.log("New Vault QA chain with hybrid retriever created for entire vault"),console.log("Set chain:","vault_qa"));break}case"copilot_plus":{await this.initializeQAChain(r),this.chain=d4.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),UR("copilot_plus");break}case"project":{await this.initializeQAChain(r),this.chain=d4.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),UR("project");break}default:this.validateChainType(e);break}}getChainRunner(){let e=Fh();switch(e){case"llm_chain":return new Hie(this);case"vault_qa":return new Vie(this);case"copilot_plus":return new t5(this);case"project":return new Wie(this);default:throw new Error(`Unsupported chain type: ${e}`)}}async initializeQAChain(e){e.refreshIndex&&await this.vectorStoreManager.indexVaultToVectorStore()}async runChain(e,r,n,o,i={}){let{debug:a=!1,ignoreSystemMessage:s=!1}=i;a&&console.log(`==== Step 0: Initial user message ====
`,e),this.validateChatModel(),this.validateChainInitialization();let u=this.chatModelManager.getChatModel();if(s||FR(u)){let c=xp.fromMessages([new Gb("history"),Jb.fromTemplate("{input}")]);FR(u)&&(c=xp.fromMessages([[Pi,Yb()||""],c])),this.createChainWithNewModel({prompt:c},!1)}return await this.getChainRunner().run(e,r,n,o,i)}async updateMemoryWithLoadedMessages(e){await this.memoryManager.clearChatMemory();for(let r=0;r<e.length;r+=2){let n=e[r],o=e[r+1];n&&o&&n.sender===Pi&&await this.memoryManager.getMemory().saveContext({input:n.message},{output:o.message})}}clearHistory(){this.chatMessages=[]}getChatMessages(){return this.chatMessages}setChatMessages(e){this.chatMessages=[...e]}addChatMessage(e){this.chatMessages.push(e)}};var ac=class t{constructor(e,r,n){this.defaultProjectKey="defaultProjectKey";this.app=e,this.plugin=n,this.currentProjectId=null,this.chainMangerInstance=new vW(e,r),this.projectContextCache=tb.getInstance(),this.chatMessageCache=new Map,this.fileParserManager=new oI(Fi.getInstance(),this.app.vault,!0,null),t8e(async()=>{await this.getCurrentChainManager().createChainWithNewModel()}),r8e(async()=>{HR()||await this.getCurrentChainManager().createChainWithNewModel({refreshIndex:ue().indexVaultToVectorStore==="ON MODE SWITCH"&&(Fh()==="vault_qa"||Fh()==="copilot_plus")})}),xF(async o=>{await this.switchProject(o)}),this.setupProjectListChangeMonitor()}setupProjectListChangeMonitor(){xa(async(e,r)=>{if(!e||!r)return;let n=e.projectList||[],o=r.projectList||[];for(let i of o){let a=n.find(s=>s.id===i.id);a&&JSON.stringify(a)!==JSON.stringify(i)&&(await this.compareAndUpdateCache(a,i),this.currentProjectId===i.id&&await Promise.all([this.loadProjectContext(i),this.getCurrentChainManager().createChainWithNewModel()]))}})}static getInstance(e,r,n){return t.instance||(t.instance=new t(e,r,n)),t.instance}getCurrentChainManager(){return this.chainMangerInstance}async switchProject(e){try{if(GE(!0),ie("Project loading started..."),!e){await this.saveCurrentProjectMessage(),this.currentProjectId=null,await this.loadNextProjectMessage(),this.refreshChatView();return}let r=e.id;if(this.currentProjectId===r)return;await this.saveCurrentProjectMessage(),this.currentProjectId=r,await this.loadNextProjectMessage(),await this.getCurrentChainManager().createChainWithNewModel(),this.fileParserManager=new oI(Fi.getInstance(),this.app.vault,!0,e),await this.loadProjectContext(e),this.refreshChatView(),ie(`Switched to project: ${e.name}`)}catch(r){throw fe(`Failed to switch project: ${r}`),r}finally{GE(!1)}}async saveCurrentProjectMessage(){this.chatMessageCache.set(this.currentProjectId?this.currentProjectId:this.defaultProjectKey,this.getCurrentChainManager().getChatMessages()),await this.plugin.autosaveCurrentChat()}async loadNextProjectMessage(){let e=this.getCurrentChainManager(),r=this.chatMessageCache.get(this.currentProjectId?this.currentProjectId:this.defaultProjectKey)??[];e.setChatMessages(r),await vN(r,e.memoryManager)}async loadProjectContext(e){try{if(!e.contextSource)return Mh(`[loadProjectContext] Project ${e.name}: No contextSource. Aborting.`),null;ie(`[loadProjectContext] Starting for project: ${e.name}`);let r=await this.projectContextCache.get(e),n=r||{markdownContext:"",webContexts:{},youtubeContexts:{},fileContexts:{},timestamp:Date.now(),markdownNeedsReload:!0};r?ie(`[loadProjectContext] Project ${e.name}: Existing cache found. MarkdownNeedsReload: ${n.markdownNeedsReload}`):ie(`[loadProjectContext] Project ${e.name}: No existing cache found, building fresh context.`);let[o]=await Promise.all([this.processMarkdownFiles(e,n),this.processWebUrls(e,n),this.processYoutubeUrls(e,n)]);if(o.fileContexts){let i=Object.keys(o.fileContexts).length;if(ie(`[loadProjectContext] Project ${e.name}: Checking ${i} fileContexts for non-markdown processing.`),i>0){this.fileParserManager=new oI(Fi.getInstance(),this.app.vault,!0,e);let a=0;for(let s in o.fileContexts){let u=this.app.vault.getAbstractFileByPath(s);if(u instanceof wW.TFile&&u.extension!=="md"&&this.fileParserManager.supportsExtension(u.extension))tr
2025-07-05 20:48:33 +08:00
`).filter(m=>m.trim()),p=l.split(`
`).filter(m=>m.trim());for(let m of f)p.includes(m)||await this.projectContextCache.removeWebUrl(r,m)}let c=e.contextSource?.youtubeUrls||"",d=r.contextSource?.youtubeUrls||"";if(c!==d){let f=c.split(`
`).filter(m=>m.trim()),p=d.split(`
`).filter(m=>m.trim());for(let m of f)p.includes(m)||await this.projectContextCache.removeYoutubeUrl(r,m)}}catch(n){fe(`Error comparing project configurations: ${n}`)}}refreshChatView(){let e=this.app.workspace.getLeavesOfType(Es)[0]?.view;e&&e.updateView()}async getProjectContext(e){let r=ue().projectList.find(o=>o.id===e);if(!r)return Mh(`[getProjectContext] Project not found for ID: ${e}`),null;ie(`[getProjectContext] Getting context for project: ${r.name} (ID: ${e})`);let n=this.projectContextCache.getSync(r);if(!n||n.markdownNeedsReload){n?ie(`[getProjectContext] Project ${r.name}: Markdown needs reload. Triggering full load.`):ie(`[getProjectContext] Project ${r.name}: Memory cache miss. Triggering full load.`);let o=await this.loadProjectContext(r);if(!o)return fe(`[getProjectContext] Project ${r.name}: loadProjectContext returned null.`),null;n=o}else ie(`[getProjectContext] Project ${r.name}: Memory cache hit and markdown OK. Using existing context.`);return this.formatProjectContextWithFiles(n,r)}async formatProjectContextWithFiles(e,r){let n=[];if(e.markdownContext&&n.push(`## Markdown Files
${e.markdownContext}`),Object.keys(e.webContexts).length>0&&n.push(`## Web Content
${Object.values(e.webContexts).join(`
`)}`),Object.keys(e.youtubeContexts).length>0&&n.push(`## YouTube Content
${Object.values(e.youtubeContexts).join(`
`)}`),Object.keys(e.fileContexts).length>0){let o=Object.entries(e.fileContexts).filter(([i])=>i.split(".").pop()?.toLowerCase()!=="md");if(o.length>0){let i=o.map(async([s,u])=>{let l=s.split("/"),c=l[l.length-1],d=c.split(".").pop()||"",f=await this.projectContextCache.getFileContext(r,s)||"[Content not available]";return`[[${c}]]
path: ${s}
type: ${d}
modified: ${new Date(u.timestamp).toISOString()}
${f}`}),a=await Promise.all(i);a.length>0&&n.push(`## Other Files
${a.join(`
`)}`)}}return`
# Project Context
The following information is the relevant context for this project. Use this information to inform your responses when appropriate:
<ProjectContext>
${n.join(`
`)}
</ProjectContext>
`}formatProjectContext(e){let r=[];if(e.markdownContext&&r.push(`## Markdown Files
${e.markdownContext}`),Object.keys(e.webContexts).length>0&&r.push(`## Web Content
${Object.values(e.webContexts).join(`
`)}`),Object.keys(e.youtubeContexts).length>0&&r.push(`## YouTube Content
${Object.values(e.youtubeContexts).join(`
`)}`),Object.keys(e.fileContexts).length>0){let n="";for(let[o,i]of Object.entries(e.fileContexts)){let a=o.split("/"),s=a[a.length-1],u=s.split(".").pop()||"";n+=`[[${s}]]
path: ${o}
type: ${u}
modified: ${new Date(i.timestamp).toISOString()}
`}n&&r.push(`## Other Files
${n}`)}return`
# Project Context
The following information is the relevant context for this project. Use this information to inform your responses when appropriate:
<ProjectContext>
${r.join(`
`)}
</ProjectContext>
`}async processMarkdownFiles(e,r){ie(`[processMarkdownFiles] Starting for project: ${e.name}`);let n=Object.keys(r.fileContexts||{}).length;if(e.contextSource?.inclusions||e.contextSource?.exclusions){r=await this.projectContextCache.updateProjectFilesFromPatterns(e,r);let o=Object.keys(r.fileContexts||{}).length;if(o>n&&ie(`[processMarkdownFiles] Project ${e.name}: Added ${o-n} new file references via updateProjectFilesFromPatterns.`),r.markdownNeedsReload||!r.markdownContext||!r.markdownContext.trim()){ie(`[processMarkdownFiles] Project ${e.name}: Processing markdown content.`);let i=await this.processFileContext(e.contextSource.inclusions,e.contextSource.exclusions,e);r.markdownContext=i,r.markdownNeedsReload=!1,ie(`[processMarkdownFiles] Project ${e.name}: Markdown content updated.`)}else ie(`[processMarkdownFiles] Project ${e.name}: Markdown content already up-to-date.`)}return ie(`[processMarkdownFiles] Completed for project: ${e.name}. Total fileContexts: ${Object.keys(r.fileContexts||{}).length}`),r}async processFileContext(e,r,n){if(!e&&!r||!n)return"";let{inclusions:o,exclusions:i}=rf({inclusions:e,exclusions:r,isProject:!0}),a=this.app.vault.getFiles().filter(u=>u.extension==="md"&&eu(u,o,i));ie(`Found ${a.length} markdown files to process for project context`);let s=await Promise.all(a.map(async u=>{let l="",c="";try{let d=await this.app.vault.adapter.stat(u.path);c=`[[${u.basename}]]
path: ${u.path}
type: ${u.extension}
created: ${d?new Date(d.ctime).toISOString():"unknown"}
modified: ${d?new Date(d.mtime).toISOString():"unknown"}`,l=await this.app.vault.read(u),ie(`Completed processing markdown file: ${u.path}`)}catch(d){fe(`Error processing file ${u.path}: ${d}`),l=`[Error: ${ei(d)}]`}return`${c}
${l}`}));return ie("All markdown files processed for project context"),s.join(`
`)}async processWebUrls(e,r){ie(`[processWebUrls] Starting for project: ${e.name}`);let n=e.contextSource?.webUrls?.trim()||"";if(!n)return Object.keys(r.webContexts).length>0&&(ie(`[processWebUrls] Project ${e.name}: Clearing all Web contexts as none are configured.`),r.webContexts={}),r;let o=n.split(`
`).filter(c=>c.trim());ie(`[processWebUrls] Project ${e.name}: Found ${o.length} URLs in config.`);let i=Object.keys(r.webContexts),a=o.filter(c=>!r.webContexts[c]);a.length>0&&ie(`[processWebUrls] Project ${e.name}: Fetching content for ${a.length} new/updated Web URLs.`);let s=i.filter(c=>!o.includes(c));if(s.length>0){ie(`[processWebUrls] Project ${e.name}: Removing ${s.length} obsolete Web URL contexts.`);for(let c of s)delete r.webContexts[c]}let u=a.map(async c=>{let d=await this.processWebUrlsContext(c);return d&&ie(`[processWebUrls] Project ${e.name}: Successfully fetched content for URL: ${c.substring(0,50)}...`),{url:c,context:d}});return(await Promise.all(u)).forEach(c=>{c&&c.context?r.webContexts[c.url]=c.context:c&&!c.context&&Mh(`[processWebUrls] Project ${e.name}: Fetched empty content for Web URL: ${c.url}`)}),ie(`[processWebUrls] Completed for project: ${e.name}. Total Web contexts: ${Object.keys(r.webContexts).length}`),r}async processYoutubeUrls(e,r){ie(`[processYoutubeUrls] Starting for project: ${e.name}`);let n=e.contextSource?.youtubeUrls?.trim()||"";if(!n)return Object.keys(r.youtubeContexts).length>0&&(ie(`[processYoutubeUrls] Project ${e.name}: Clearing all YouTube contexts as none are configured.`),r.youtubeContexts={}),r;let o=n.split(`
2025-07-12 10:26:56 +08:00
`).filter(c=>c.trim());ie(`[processYoutubeUrls] Project ${e.name}: Found ${o.length} YouTube URLs in config.`);let i=Object.keys(r.youtubeContexts),a=o.filter(c=>!r.youtubeContexts[c]);a.length>0&&ie(`[processYoutubeUrls] Project ${e.name}: Fetching transcripts for ${a.length} new/updated YouTube URLs.`);let s=i.filter(c=>!o.includes(c));if(s.length>0){ie(`[processYoutubeUrls] Project ${e.name}: Removing ${s.length} obsolete YouTube URL contexts.`);for(let c of s)delete r.youtubeContexts[c]}let u=a.map(async c=>{let d=await this.processYoutubeUrlsContext(c);return d&&ie(`[processYoutubeUrls] Project ${e.name}: Successfully fetched transcript for YouTube URL: ${c.substring(0,50)}...`),{url:c,context:d}});return(await Promise.all(u)).forEach(c=>{c&&c.context?r.youtubeContexts[c.url]=c.context:c&&!c.context&&Mh(`[processYoutubeUrls] Project ${e.name}: Fetched empty transcript for YouTube URL: ${c.url}`)}),ie(`[processYoutubeUrls] Completed for project: ${e.name}. Total YouTube contexts: ${Object.keys(r.youtubeContexts).length}`),r}async processWebUrlsContext(e){if(!e?.trim())return"";try{let r=Oq.getInstance(),{urlContext:n}=await r.processUrls(e);return n||""}catch(r){return fe(`Failed to process web URLs: ${r}`),new wW.Notice(`Failed to process web URLs: ${ei(r)}`),""}}async processYoutubeUrlsContext(e){if(!e?.trim())return"";let n=e.split(`
2025-07-05 20:48:33 +08:00
`).filter(i=>i.trim()).map(async i=>{try{let a=await Fi.getInstance().youtube4llm(i);return a.response.transcript?`
YouTube transcript from ${i}:
2025-07-12 10:26:56 +08:00
${a.response.transcript}`:""}catch(a){return fe(`Failed to process YouTube URL ${i}: ${a}`),new wW.Notice(`Failed to process YouTube URL ${i}: ${ei(a)}`),""}});return(await Promise.all(n)).join("")}onunload(){this.projectContextCache.cleanup()}};Cl();$r();yo();nr();GLe();$r();mg();yo();nr();var Vg=require("@codemirror/view"),QP=require("@codemirror/state");function y3t(t,e,r=void 0){let n={force:()=>{}},o=null;async function*i(...a){o&&clearTimeout(o);let s=null;try{await new Promise(u=>{s=o=setTimeout(()=>u(),e),n.force=()=>{o&&clearTimeout(o),u()}})}catch{if(r!==void 0)throw r}for await(let u of t(...a)){if(s!==o)break;yield u}}return{debounced:i,force:()=>n.force()}}var Kwn=Object.defineProperty,Gwn=(t,e,r)=>e in t?Kwn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,KU=(t,e,r)=>(Gwn(t,typeof e!="symbol"?e+"":e,r),r),Yle=QP.StateField.define({create(){return{suggestion:null}},update(t,e){let r=e.effects.find(n=>n.is(QLe));return e.state.doc&&r&&(r.value.doc==null||e.state.doc==r.value.doc)?{suggestion:r.value.suggestion}:{suggestion:null}}}),QLe=QP.StateEffect.define();function Jwn(t,e){let r=t.state.selection.main.head,n=[],o=Vg.Decoration.widget({widget:new JLe(e),side:1});return n.push(o.range(r)),Vg.Decoration.set(n)}var JLe=class extends Vg.WidgetType{constructor(e){super(),KU(this,"suggestion"),this.suggestion=e}toDOM(){let e=document.createElement("span");return e.style.opacity="0.4",e.className="cm-inline-suggestion",e.textContent=this.suggestion,e}},YLe=t=>{let e=0;return Vg.ViewPlugin.fromClass(class{async update(r){let n=r.state.doc;if(!r.docChanged)return;let o=++e;for await(let i of t(r.state)){if(o!=e)return;r.view.dispatch({effects:QLe.of({suggestion:i,doc:n})})}}})},ZLe=class{constructor(){KU(this,"decorations"),this.decorations=Vg.Decoration.none}update(e){var r;let n=(r=e.state.field(Yle))==null?void 0:r.suggestion;if(!n){this.decorations=Vg.Decoration.none;return}this.decorations=Jwn(e.view,n.display_suggestion)}},b3t=Vg.ViewPlugin.fromClass(ZLe,{decorations:t=>t.decorations}),XLe=class{constructor(e,r){KU(this,"suggestFn"),KU(this,"keymap"),KU(this,"completionId"),KU(this,"run",n=>{var o,i;let a=(o=n.state.field(Yle))==null?void 0:o.suggestion;return a?(n.dispatch({...Ywn(n.state,a.complete_suggestion,n.state.selection.main.head,n.state.selection.main.head)}),(i=a.accept_hook)==null||i.call(a),(async()=>{if(this.suggestFn==null)return;let s=++this.completionId;for await(let u of this.suggestFn(n.state)){if(s!=this.completionId)return;n.dispatch({effects:QLe.of({suggestion:{complete_suggestion:u.complete_suggestion,display_suggestion:u.display_suggestion,accept_hook:u.accept_hook},doc:null})})}})(),!0):!1}),this.suggestFn=e,this.keymap=QP.Prec.highest(Vg.keymap.of([{key:r,run:n=>this.run(n)}])),this.completionId=0}};function Ywn(t,e,r,n){return{...t.changeByRange(o=>{if(o==t.selection.main)return{changes:{from:r,to:n,insert:e},range:QP.EditorSelection.cursor(r+e.length)};let i=n-r;return!o.empty||i&&t.sliceDoc(o.from-i,o.from)!=t.sliceDoc(r,n)?{range:o}:{changes:{from:o.from-i,to:o.from,insert:e},range:QP.EditorSelection.cursor(o.from-i+e.length)}}),userEvent:"input.complete"}}function _3t(t){return typeof t=="string"?{complete_suggestion:t,display_suggestion:t}:t}function Zwn(t){return async function*(e){let r=await t(e);if(typeof r=="string"||"complete_suggestion"in r){yield _3t(r);return}for await(let n of r)yield _3t(n)}}function Zle(t){let{delay:e=500,accept_shortcut:r="Tab"}=t,n=Zwn(t.fetchFn),{debounced:o,force:i}=y3t(n,e);return{extension:r?[Yle,YLe(o),b3t,new XLe(t.continue_suggesting?n:null,r).keymap]:[Yle,YLe(o),b3t],force_fetch:i}}var oFe=require("obsidian");var eFe=class{process(e){let{prefix:r,suffix:n}=e,{completion:o}=e;return o=this.removeWordOverlapPrefix(r,o),o=this.removeWordOverlapSuffix(o,n),o=this.removeCharacterOverlapPrefix(r,o),o=this.removeCharacterOverlapSuffix(o,n),o.startsWith(" ")&&this.endsWithMarker(r)&&(o=o.trimStart()),o}removeWordOverlapPrefix(e,r){let n=r.trimStart(),o=this.getPotentialPrefixSegments(e);for(let i of o)if(n.startsWith(i))return n.s
2025-07-05 20:48:33 +08:00
`)&&a.startsWith(`
2025-07-12 10:26:56 +08:00
`)&&(a=a.substring(1)),a}},rFe=class{process(e){let{completion:r,context:n}=e;if(n==="CodeBlock"){let o=r;return o=o.replace(/```[a-zA-Z]*[ \t]*\n?/g,""),o=o.replace(/\n?```[ \t]*\n?/g,""),o.endsWith(`
`)&&(o=o.slice(0,-1)),o}return r}},Xle=class{constructor(){this.processors=[];this.processors.push(new rFe),this.processors.push(new eFe),this.processors.push(new tFe)}process(e,r,n,o){let a={prefix:e,suffix:r,completion:n,context:o};for(let s of this.processors)a.completion=s.process(a);return a.completion}};f4();var v3t=require("obsidian");function w3t(t,e=20){let r=app.metadataCache.getFileCache(t),n=[];if(r?.links)for(let o of r.links){let i=app.metadataCache.getFirstLinkpathDest(o.link,t.path);if(i&&(n.push(i),n.length>=e))break}if(r?.embeds&&n.length<e)for(let o of r.embeds){let i=app.metadataCache.getFirstLinkpathDest(o.link,t.path);if(i&&(n.push(i),n.length>=e))break}return[...new Set(n)]}function S3t(t,e=20){let r=[],n=app.metadataCache.getBacklinksForFile(t);if(n?.data)for(let[o]of n.data){let i=app.vault.getAbstractFileByPath(o);if(i instanceof v3t.TFile&&(r.push(i),r.length>=e))break}return r}rie();nr();var nFe=require("obsidian"),Xwn=.4,Qwn=20,x3t=.7,Qle=.3;async function e0n(t,e){let r=ue().debug,n=await eP.getDocsByPath(e,t);if(!n)return r&&console.log("No hits found for note:",t),[];let o=[];for(let i of n){if(!i?.document?.embedding){r&&console.log("No embedding found for note:",t);continue}o.push(i.document.embedding)}return o}function t0n(t){if(t.length===0)return[];let e=t[0].length,r=Array(e).fill(0);return t.forEach(n=>{n.forEach((o,i)=>{r[i]+=o/e})}),r}function r0n(t,e){let r=new Map;for(let n of t){let o=r.get(n.document.path);o?n.score>o&&r.set(n.document.path,n.score):r.set(n.document.path,n.score)}return r.delete(e),r}async function n0n({db:t,filePath:e}){let r=ue().debug,n=await e0n(e,t),o=t0n(n);if(o.length===0)return r&&console.log("No embeddings found for note:",e),new Map;let i=await eP.getDocsByEmbedding(t,o,{limit:Qwn,similarity:Xwn});return r0n(i,e)}function o0n(t){let e=new Map,n=w3t(t).map(a=>a.path);for(let a of n)e.set(a,{links:!0,backlinks:!1});let i=S3t(t).map(a=>a.path);for(let a of i)e.has(a)?e.set(a,{links:!0,backlinks:!0}):e.set(a,{links:!1,backlinks:!0});return e}function i0n(t,e){let r=new Map,n=x3t+Qle;for(let[o,i]of t)r.set(o,i*x3t/n);for(let[o,i]of e){let a=0;i.links&&i.backlinks?a=Qle:(i.links||i.backlinks)&&(a=Qle*.8),r.set(o,(r.get(o)??0)+a)}return r}async function tce({db:t,filePath:e}){let r=app.vault.getAbstractFileByPath(e);if(!(r instanceof nFe.TFile))return[];let n=await n0n({db:t,filePath:e}),o=o0n(r),i=i0n(n,o);return Array.from(i.entries()).sort((s,u)=>{let l=s[0],c=u[0],d=ece(n.get(l)??0),f=ece(n.get(c)??0);return d!==f?f-d:u[1]-s[1]}).map(([s,u])=>{let l=app.vault.getAbstractFileByPath(s);return l instanceof nFe.TFile?{document:{path:s,title:l.basename},metadata:{score:u,similarityScore:n.get(s),hasOutgoingLinks:o.get(s)?.links??!1,hasBacklinks:o.get(s)?.backlinks??!1}}:null}).filter(s=>s!==null)}function ece(t){return t>.7?3:t>.55?2:1}Mx();var C3t=require("obsidian"),a0n={cjk:[[19968,40959],[13312,19903],[131072,173791],[173824,177983],[177984,178207],[178208,183983]],japanese:[[12352,12447],[12448,12543]],korean:[[44032,55215],[4352,4607]],other:[[3584,3711],[1536,1791],[2304,2431],[2432,2559],[2688,2815],[2944,3071]]};function s0n(t,e){let r=t.codePointAt(0);return r?e.some(([n,o])=>r>=n&&r<=o):!1}function O3t(t){let e=t.replace(/[\p{Emoji}\p{Symbol}\p{Punctuation}]/gu,"");if(!e)return!1;for(let r of e)if(Object.values(a0n).some(n=>s0n(r,n)))return!0;return!1}function P3t(t,e){let r="",n="",o=Math.max(0,e.line-5);for(let u=o;u<e.line;u++)r+=t.getLine(u)+`
2025-07-05 20:48:33 +08:00
`;let i=t.getLine(e.line);r+=i.slice(0,e.ch),(e.ch===0||e.ch===i.length&&i.trim()==="")&&(r+=`
`);let a=Math.max(0,e.line-50);for(let u=a;u<e.line;u++)n+=t.getLine(u)+`
`;n+=i.slice(0,e.ch)+"{{CURSOR}}"+i.slice(e.ch)+`
`;let s=Math.min(t.lineCount()-1,e.line+50);for(let u=e.line+1;u<=s;u++)n+=t.getLine(u)+`
2025-07-12 10:26:56 +08:00
`;return{prefix:r,noteContext:n}}var YI=class YI{constructor(){this.currentNotePath=null;this.cachedNotes=null;this.cachedNoteTitles=[]}static getInstance(){return YI.instance||(YI.instance=new YI),YI.instance}getRelevantNoteTitles(){return this.cachedNoteTitles}async getRelevantNotes(e){if(!e)return this.currentNotePath=null,this.cachedNotes=null,this.cachedNoteTitles=[],"";if(this.currentNotePath===e.path&&this.cachedNotes!==null)return this.cachedNotes;let r=await ma.getInstance().getDb(),o=(await tce({db:r,filePath:e.path})).slice(0,YI.MAX_RELEVANT_NOTES);this.cachedNoteTitles=o.map(a=>a.document.title);let i=await Promise.all(o.map(async a=>{let s=app.vault.getAbstractFileByPath(a.document.path);if(!(s instanceof C3t.TFile))return"";let u=await app.vault.cachedRead(s);if(!u)return"";let l=u.length>3e3?u.slice(0,3e3)+"...":u;return`[[${a.document.title}]]:
2025-07-05 20:48:33 +08:00
${l}`}));return this.currentNotePath=e.path,this.cachedNotes=i.join(`
2025-07-12 10:26:56 +08:00
`),this.cachedNotes}clearCache(){this.currentNotePath=null,this.cachedNotes=null,this.cachedNoteTitles=[]}};YI.MAX_RELEVANT_NOTES=3;var rce=YI;var TD=class{constructor(){this.MIN_WORD_LENGTH=4;this.STOP_WORDS=new Set(["a","ain","all","am","an","and","any","are","as","at","be","but","by","can","d","did","do","don","few","for","had","has","he","her","him","his","how","i","if","in","is","isn","it","its","ll","m","ma","me","my","no","nor","not","now","o","of","off","on","or","our","out","own","re","s","she","so","t","the","to","too","up","ve","was","we","who","why","won","y","you"])}extractWords(e){return(this.preprocessText(e).match(/\b[a-zA-Z]+(?:'[a-zA-Z]+)?\b/g)||[]).filter(o=>this.isValidWord(o))}isWordCharacter(e){return/[a-zA-Z']/.test(e)}isValidWord(e){return!(e.length<this.MIN_WORD_LENGTH||!/^[a-zA-Z]+(?:'[a-zA-Z]+)?$/.test(e)||this.STOP_WORDS.has(e.toLowerCase())||e===e.toUpperCase()&&e.length>4)}getLanguage(){return"en"}preprocessText(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`[^`]+`/g," ").replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/<[^>]+>/g," ").replace(/^#+\s+/gm,"").replace(/[*_]{1,2}([^*_]+)[*_]{1,2}/g,"$1").replace(/^\s*[-*+]\s+/gm,"").replace(/^\s*\d+\.\s+/gm,"").replace(/\s+/g," ").trim()}};var xW=class{constructor(e=5e4){this.wordCount=0;this.root=this.createNode(),this.maxSize=e}createNode(){return{children:new Map,isEndOfWord:!1,wordEntry:void 0}}addWord(e,r){if(!e||e.length<4||this.wordCount>=this.maxSize&&!this.hasWord(e))return;let n=this.root;for(let o of e)n.children.has(o)||n.children.set(o,this.createNode()),n=n.children.get(o);n.isEndOfWord?n.wordEntry&&(n.wordEntry.frequency++,n.wordEntry.lastSeen=Date.now(),r&&!n.wordEntry.contexts.includes(r)&&(n.wordEntry.contexts.push(r),n.wordEntry.contexts.length>10&&(n.wordEntry.contexts=n.wordEntry.contexts.slice(-10)))):(n.isEndOfWord=!0,n.wordEntry={word:e,frequency:1,contexts:r?[r]:[],lastSeen:Date.now()},this.wordCount++)}hasWord(e){let r=this.findNode(e);return r!==null&&r.isEndOfWord}getWordEntry(e){let r=this.findNode(e);return r&&r.isEndOfWord&&r.wordEntry?r.wordEntry:null}findNode(e){let r=this.root;for(let n of e){if(!r.children.has(n))return null;r=r.children.get(n)}return r}getSuggestions(e,r=10){if(!e)return[];let n=[],o=this.generatePrefixVariants(e);for(let a of o){let s=this.findNode(a);if(s&&(this.collectWords(s,a,n,r,e),n.length>=r))break}let i=this.deduplicateSuggestions(n);return i.sort((a,s)=>s.score-a.score),i.slice(0,r)}generatePrefixVariants(e){let r=new Set;return r.add(e),r.add(e.toLowerCase()),e.length>0&&r.add(e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()),r.add(e.toUpperCase()),Array.from(r)}deduplicateSuggestions(e){let r=new Map;for(let n of e){let o=n.word,i=r.get(o);(!i||n.score>i.score)&&r.set(o,n)}return Array.from(r.values())}collectWords(e,r,n,o,i){if(!(n.length>=o)){if(e.isEndOfWord&&e.wordEntry){let a=this.calculateScore(e.wordEntry)+this.getCaseMatchBonus(r,i);n.push({word:r,score:a,source:"vault"})}for(let[a,s]of e.children)this.collectWords(s,r+a,n,o,i)}}getCaseMatchBonus(e,r){if(e.length<r.length)return 0;let n=e.substring(0,r.length);return n===r?2:this.hasSameCasePattern(n,r)?1.5:1}hasSameCasePattern(e,r){if(e.length<r.length)return!1;for(let n=0;n<r.length;n++){let o=e[n],i=r[n],a=o===o.toUpperCase(),s=i===i.toUpperCase();if(a!==s)return!1}return!0}calculateScore(e){let r=Math.log(e.frequency+1)*10,n=Math.max(0,(Date.now()-e.lastSeen)/(1e3*60*60*24)),o=Math.max(0,10-n);return r+o}getStats(){let e=0,r=0,n=(o,i=0)=>{e++,r=Math.max(r,i);for(let a of o.children.values())n(a,i+1)};return n(this.root),{wordCount:this.wordCount,nodeCount:e,maxDepth:r}}clear(){this.root=this.createNode(),this.wordCount=0}getAllWords(){let e=[],r=n=>{n.isEndOfWord&&n.wordEntry&&e.push(n.wordEntry);for(let o of n.children.values())r(o)};return r(this.root),e}addWords(e,r){for(let n of e)this.addWord(n,r)}pruneByFrequency(e=2){let r=0,n=o=>{let i=[];for(let[a,s]of o.children)n(s)&&i.push(a);for(let a of i)o.children.delete(a);return o.isEndOfWord&&o.wordEntry&&o.wordEntry.frequency
2025-07-05 20:48:33 +08:00
`))return!1;let o=e.split(`
2025-07-12 10:26:56 +08:00
`),i=o[o.length-1];if(/^#{1,6}(\s*)$/.test(i))return!1;let a=e.trim().split(/\s+/).filter(u=>u.replace(/[\p{Emoji}\p{Symbol}\p{Punctuation}]/gu,"").length>0),s=a[a.length-1]||"";return O3t(s)?!0:e.endsWith(" ")}async*handleUnifiedCompletion(){if(!this.isActive)return;let e=app.workspace.getActiveViewOfType(oFe.MarkdownView);if(!e)return;await new Promise(c=>setTimeout(c,10));let r=e.editor,n=r.getCursor(),{prefix:o,noteContext:i}=P3t(r,n),a=r.getLine(n.line).substring(n.ch)||"";if(this.lastCursorPosition){let c=Math.abs(n.line-this.lastCursorPosition.line),d=Math.abs(n.ch-this.lastCursorPosition.ch);(c>0||d>5)&&this.clearActiveRequests()}this.lastCursorPosition={line:n.line,ch:n.ch};let s=Date.now();if(s-this.lastRequestTime<this.minRequestInterval)return;let u=ue();if(this.shouldUseWordCompletion(o,u)){let c=this.getCurrentWordFromPrefix(o);if(!c||c.length<2)return;let d=`word:${c}:${o.slice(-50)}`;if(this.activeRequests.has(d))return;let f=this.wordCompletionManager.getSuggestions(c);if(f.length===0)return;let p=f.some(b=>b.word===c),m=f.some(b=>b.word.length-c.length>=2);if(p&&!m)return;let h=p?f.filter(b=>b.word!==c):f;if(h.length===0)return;try{let b=h.map(E=>E.word),g=o.slice(-1e3),y=a.slice(0,500),S,x,O;if(this.cacheEnabled&&(x=this.cache.generateWordKey(g,y,b),O=this.cache.get(x)),O)S=O;else{let E=this.client.wordcomplete(g,y,b);this.activeRequests.set(d,E),this.lastRequestTime=s,S=await E,this.cacheEnabled&&x&&this.cache.set(x,S),this.activeRequests.delete(d)}let P=S.response.selected_word;if(P&&P!==c){let E=this.generateCaseMatchedCompletion(P,c);E&&(yield{display_suggestion:E,complete_suggestion:E})}}catch(b){this.activeRequests.delete(d),fe("[Copilot Autocomplete] Error with LLM word selection, falling back to trie:",b);let g=h[0],y=this.generateCaseMatchedCompletion(g.word,c);y&&(yield{display_suggestion:y,complete_suggestion:y})}}else{if(!u.enableAutocomplete||!this.shouldContinueSuggesting(o,a))return;let c=o.slice(-this.options.maxContextLength);if(c.length<this.options.minTriggerLength)return;let d=`sentence:${c.slice(-100)}`;if(this.activeRequests.has(d))return;try{let f=u.allowAdditionalContext,p="";f&&(p=await rce.getInstance().getRelevantNotes(e.file));let m=e.file?.basename||"",h=m?`[[${m}]]:
2025-07-05 20:48:33 +08:00
${c}`:c,b,g,y;if(this.cacheEnabled&&(g=this.cache.generateSentenceKey(h,i,p),y=this.cache.get(g)),y)b=y;else{let O=this.client.autocomplete(h,i,p);this.activeRequests.set(d,O),this.lastRequestTime=s,b=await O,this.cacheEnabled&&g&&this.cache.set(g,b),this.activeRequests.delete(d)}let S=b.response.completion,x=this.detectContext(o);S=this.postProcessor.process(c,a,S,x),yield{display_suggestion:S,complete_suggestion:S}}catch(f){this.activeRequests.delete(d),fe("[Copilot Autocomplete] Error fetching autocomplete suggestions:",f)}}}shouldUseWordCompletion(e,r){if(!r.enableWordCompletion||e.endsWith("[[")||/\[\[[^\]]*$/.test(e))return!1;let o=e.trim(),i=o[o.length-1];if(i&&/[a-zA-Z']/.test(i)){let a=this.getCurrentWordFromPrefix(e);if(a&&a.length>=2){let s=this.wordCompletionManager.getSuggestions(a);if(s.length===0)return!1;let u=s.some(c=>c.word===a),l=s.some(c=>c.word.length-a.length>=2);return!(u&&!l)}}return!1}getCurrentWordFromPrefix(e){let r=e.length;for(let o=e.length-1;o>=0;o--){let i=e[o];if(!/[a-zA-Z']/.test(i)){r=o+1;break}o===0&&(r=0)}let n=e.substring(r);return n.length>=2?n:null}generateCaseMatchedCompletion(e,r){if(e.length<=r.length)return"";let n=e.substring(r.length),o=r===r.toUpperCase(),i=r===r.toLowerCase(),a=r.length>0&&r[0]===r[0].toUpperCase()&&r.slice(1)===r.slice(1).toLowerCase();return o?n.toUpperCase():i||a?n.toLowerCase():n}detectContext(e){let r=e.split(`
2025-07-12 10:26:56 +08:00
`).pop()||"";if(/^\s*[-*+]\s/.test(r))return"UnorderedList";if(/^\s*\d+\.\s/.test(r))return"NumberedList";if(/^\s*[-*+]\s\[[ x]\]\s/.test(r))return"TaskList";if(e.includes("```")&&(e.split("```").length-1)%2===1)return"CodeBlock"}triggerCompletion(){this.isActive&&(this.clearActiveRequests(),this.forceFetch())}clearActiveRequests(){this.activeRequests.size>0&&this.activeRequests.clear()}getWordCompletionManager(){return this.wordCompletionManager}setCacheEnabled(e){this.cacheEnabled=e,e||this.cache.clear()}getCacheEnabled(){return this.cacheEnabled}};var oce=class t{constructor(e){this.plugin=e;let r=ue();this.cmIntegration=nce.getInstance({delay:Nh.DELAY_MS,minTriggerLength:Nh.MIN_TRIGGER_LENGTH,maxContextLength:Nh.MAX_CONTEXT_LENGTH}),this.unsubscribeSettings=xa((o,i)=>{let a=(o.enableAutocomplete||o.enableWordCompletion)&&o.isPlusUser===!0,s=(i.enableAutocomplete||i.enableWordCompletion)&&i.isPlusUser===!0;a!==s&&this.cmIntegration.setActive(s)});let n=(r.enableAutocomplete||r.enableWordCompletion)&&r.isPlusUser===!0;this.cmIntegration.setActive(n),this.registerExtension()}static getInstance(e){return t.instance||(t.instance=new t(e)),t.instance}registerExtension(){try{this.plugin.registerEditorExtension([this.cmIntegration.getExtension()])}catch(e){fe("[Copilot Autocomplete] Failed to register CodeMirror extension:",e)}}destroy(){this.unsubscribeSettings(),this.cmIntegration.setActive(!1),this.cmIntegration.destroy()}};Cl();Fd();var T3t=require("obsidian"),ice=class extends T3t.Modal{constructor(r,n){super(r);this.placeholderText="Please enter your custom ad-hoc prompt here, press enter to send.";this.onSubmit=n}onOpen(){let{contentEl:r}=this,n=createFragment(i=>{i.createEl("strong",{text:"- {} represents the selected text (not required). "}),i.createEl("br"),i.createEl("strong",{text:"- {[[Note Title]]} represents a note. "}),i.createEl("br"),i.createEl("strong",{text:"- {activeNote} represents the active note. "}),i.createEl("br"),i.createEl("strong",{text:"- {FolderPath} represents a folder of notes. "}),i.createEl("br"),i.createEl("strong",{text:"- {#tag1, #tag2} represents ALL notes with ANY of the specified tags in their property (an OR operation). "}),i.createEl("br"),i.createEl("br"),i.appendText("Tip: turn on debug mode to show the processed prompt in the chat window."),i.createEl("br"),i.createEl("br")});r.appendChild(n);let o=r.createEl("textarea",{attr:{placeholder:this.placeholderText}});o.style.width="100%",o.style.height="100px",o.style.padding="10px",o.style.resize="vertical",o.addEventListener("input",i=>{this.result=i.target.value}),o.addEventListener("keydown",i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),this.close(),this.onSubmit(this.result))})}onClose(){let{contentEl:r}=this;r.empty()}};F8();var ZI=require("obsidian"),ace=class extends ZI.Modal{constructor(e,r){super(e),this.plugin=r}onOpen(){let{contentEl:e}=this;e.empty(),e.createEl("h2",{text:"Debug: Search OramaDB"});let r=e.createEl("p");r.innerHTML='Enter a JSON search params object. Example:<br><pre>{<br> "term": "#tag",<br> "mode": "hybrid",<br> "limit": 10,<br> "includeVectors": true<br>}</pre>',this.searchInput=e.createEl("textarea",{attr:{placeholder:"Enter search params JSON...",rows:"10",style:"width: 100%; min-height: 200px; margin: 10px 0; padding: 10px; font-family: monospace;"}}),e.createEl("div",{cls:"search-button-container"}).createEl("button",{text:"Search",cls:"mod-cta"}).addEventListener("click",async()=>{try{let i=JSON.parse(this.searchInput.value);i.vector?.value&&!Array.isArray(i.vector.value)&&(i.vector.value=Object.values(i.vector.value));let a=await this.plugin.vectorStoreManager.getDb();if(!a){new ZI.Notice("Database not found");return}let s=await Xc(a,i),u=["## Search Parameters","```json",JSON.stringify(i,null,2),"```","","## Results",`Total hits: ${s.hits.length}`,"","### Hits","```json",JSON.stringify(s.hits,null,2),"```"].join(`
`),l="OramaDB-Debug-Search.md",c=this.app.vault.getAbstractFileByPath(l);c instanceof ZI.TFile?await this.app.vault.modify(c,u):await this.app.vault.create(l,u);let d=this.app.vault.getAbstractFileByPath(l);d instanceof ZI.TFile&&(await this.app.workspace.getLeaf().openFile(d),this.close())}catch(i){console.error("Error in debug search:",i),new ZI.Notice("Error executing search. Check console for details.")}})}onClose(){let{contentEl:e}=this;e.empty()}};yn();var OW=require("obsidian"),sce=class extends OW.Modal{constructor(e,r){super(e),this.plugin=r}onOpen(){let{contentEl:e}=this;e.empty(),e.createEl("h2",{text:"Inspect Copilot Index by Note Paths"}),this.searchInput=e.createEl("textarea",{attr:{placeholder:`Enter note paths as markdown list:
2025-07-05 20:48:33 +08:00
- [[Note 1]]
2025-07-12 10:26:56 +08:00
- [[Note 2]]`,rows:"10",style:"width: 100%; min-height: 200px; margin: 10px 0; padding: 10px; font-family: monospace;"}}),e.createEl("div",{cls:"search-button-container"}).createEl("button",{text:"Show Index Data",cls:"mod-cta"}).addEventListener("click",async()=>{let o=this.searchInput.value,i=DC(o,this.app.vault).map(a=>a.path);if(i.length===0){new OW.Notice("No valid note paths found. Use format: - [[Note Name]]");return}try{let s=await(await this.plugin.vectorStoreManager.getDbOps()).getDocsJsonByPaths(i),u="CopilotDB-Search-Results.md",l=["## Searched Paths",...i.map(f=>`- [[${f}]]`),"","## Index Data","```json",JSON.stringify(s,null,2),"```"].join(`
`),c=this.app.vault.getAbstractFileByPath(u);c?await this.app.vault.modify(c,l):await this.app.vault.create(u,l);let d=this.app.vault.getAbstractFileByPath(u);d&&await this.app.workspace.getLeaf().openFile(d),this.close()}catch(a){console.error("Error searching DB:",a),new OW.Notice("Error searching database. Check console for details.")}})}onClose(){let{contentEl:e}=this;e.empty()}};var PW=require("obsidian"),uce=class extends PW.Modal{constructor(r,n){super(r);this.filePaths="";this.onSubmit=n}onOpen(){let{contentEl:r}=this;r.createEl("h2",{text:"Remove Files from Copilot Index"});let n=r.createDiv({cls:"remove-files-container"});new PW.Setting(n).setName("File paths").setDesc("Paste the markdown list of file paths to remove from the index. You can get the list by running the command `List all indexed files`.").setClass("remove-files-setting").addTextArea(o=>o.setPlaceholder(`- [[path/to/file1.md]]
- [[path/to/file2.md]]`).setValue(this.filePaths).onChange(i=>{this.filePaths=i})),new PW.Setting(n).addButton(o=>o.setButtonText("Remove").setCta().onClick(()=>{let i=this.filePaths.split(`
2025-07-05 20:48:33 +08:00
`).map(a=>{let s=a.match(/\[\[(.*?)\]\]/);return s?s[1].trim():""}).filter(a=>a.length>0);this.onSubmit(i),this.close()})),r.createEl("style",{text:`
.remove-files-container {
width: 100%;
margin-top: 12px;
}
.remove-files-setting {
display: block;
}
.remove-files-setting .setting-item-control {
padding: 0;
}
.remove-files-setting textarea {
width: 100%;
height: 300px;
margin-top: 12px;
}
.remove-files-setting textarea::placeholder {
opacity: 0.5;
}
2025-07-12 10:26:56 +08:00
`})}onClose(){let{contentEl:r}=this;r.empty()}};_g();nr();var Ji=require("obsidian");c2();$r();function df(t,e,r){t.addCommand({id:e,name:uge[e],callback:r})}function A3t(t,e,r){t.addCommand({id:e,name:uge[e],editorCallback:r})}function iFe(t,e,r){A3t(t,Br.COUNT_WORD_AND_TOKENS_SELECTION,async n=>{let o=await n.getSelection(),i=o.split(" ").length,a=await t.projectManager.getCurrentChainManager().chatModelManager.countTokens(o);new Ji.Notice(`Selected text contains ${i} words and ${a} tokens.`)}),df(t,Br.COUNT_TOTAL_VAULT_TOKENS,async()=>{try{let n=await e1t(t.app),o=await t.projectManager.getCurrentChainManager().chatModelManager.countTokens(n);new Ji.Notice(`Total tokens in your vault: ${o}`)}catch(n){console.error("Error counting tokens: ",n),new Ji.Notice("An error occurred while counting tokens.")}}),df(t,Br.TOGGLE_COPILOT_CHAT_WINDOW,()=>{t.toggleView()}),df(t,Br.OPEN_COPILOT_CHAT_WINDOW,()=>{t.activateView()}),df(t,Br.NEW_CHAT,()=>{t.newChat()}),df(t,Br.APPLY_ADHOC_PROMPT,async()=>{new ice(t.app,async o=>{try{t.processCustomPrompt(Br.APPLY_ADHOC_PROMPT,o)}catch(i){console.error(i),new Ji.Notice("An error occurred.")}}).open()}),df(t,Br.CLEAR_LOCAL_COPILOT_INDEX,async()=>{await t.vectorStoreManager.clearIndex()}),df(t,Br.GARBAGE_COLLECT_COPILOT_INDEX,async()=>{try{let n=await t.vectorStoreManager.garbageCollectVectorStore();new Ji.Notice(`${n} documents removed from Copilot index.`)}catch(n){console.error("Error garbage collecting the Copilot index:",n),new Ji.Notice("An error occurred while garbage collecting the Copilot index.")}}),df(t,Br.INDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let n=await t.vectorStoreManager.indexVaultToVectorStore();new Ji.Notice(`${n} vault files indexed to Copilot index.`)}catch(n){console.error("Error indexing vault to Copilot index:",n),new Ji.Notice("An error occurred while indexing vault to Copilot index.")}}),df(t,Br.FORCE_REINDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let n=await t.vectorStoreManager.indexVaultToVectorStore(!0);new Ji.Notice(`${n} vault files re-indexed to Copilot index.`)}catch(n){console.error("Error re-indexing vault to Copilot index:",n),new Ji.Notice("An error occurred while re-indexing vault to Copilot index.")}}),df(t,Br.LOAD_COPILOT_CHAT_CONVERSATION,()=>{t.loadCopilotChatHistory()}),df(t,Br.LIST_INDEXED_FILES,async()=>{try{let n=await t.vectorStoreManager.getIndexedFiles(),o=new Set(n),i=t.app.vault.getMarkdownFiles(),a=new Set,s=new Set,u=new Set,l=await t.vectorStoreManager.getDbOps();for(let h of i){let b=await t.app.vault.cachedRead(h);!b||b.trim().length===0?a.add(h.path):o.has(h.path)?await l.hasEmbeddings(h.path)||u.add(h.path):s.add(h.path)}if(n.length===0&&a.size===0&&s.size===0){new Ji.Notice("No files found to list.");return}let c=["# Copilot Files Status",`- Indexed files: ${n.length}`,` - Files missing embeddings: ${u.size}`,`- Unindexed files: ${s.size}`,`- Empty files: ${a.size}`,"","## Indexed Files",...n.map(h=>{let b=u.has(h);return`- [[${h}]]${b?" *(embedding missing)*":""}`}),"","## Unindexed Files",...s.size>0?Array.from(s).sort().map(h=>`- [[${h}]]`):["No unindexed files found."],"","## Empty Files",...a.size>0?Array.from(a).sort().map(h=>`- [[${h}]]`):["No empty files found."]].join(`
`),f=`${`Copilot-Indexed-Files-${new Date().toLocaleDateString().replace(/\//g,"-")}.md`}`,p=t.app.vault.getAbstractFileByPath(f);p instanceof Ji.TFile?await t.app.vault.modify(p,c):await t.app.vault.create(f,c);let m=t.app.vault.getAbstractFileByPath(f);m instanceof Ji.TFile&&(await t.app.workspace.getLeaf().openFile(m),new Ji.Notice(`Listed ${n.length} indexed files`))}catch(n){console.error("Error listing indexed files:",n),new Ji.Notice("Failed to list indexed files.")}}),r.debug&&(df(t,Br.INSPECT_COPILOT_INDEX_BY_NOTE_PATHS,()=>{new sce(t.app,t).open()}),df(t,Br.SEARCH_ORAMA_DB,()=>{new ace(t.app,t).open()}),df(t,Br.REMOVE_FILES_FROM_COPILOT_INDEX,async()=>{new uce(t.app,async n=>{let o=await t.vectorStoreManager.getDbOps();try{for(let i of n)await o.removeDocs(i);await o.saveDB(),new Ji.Notice(`Successfully removed ${n.length} files from the index.`)}catch(i){console.error("Error removing files from index:",i),new Ji.Notice("An error occurred while removing files from the index.")}}).open()})),df(t,Br.CLEAR_COPILOT_CACHE,async()=>{try{await t.fileParserManager.clearPDFCache(),await tb.getInstance().clearAllCache(),await Cq.getInstance().clear();let{AutocompleteCache:o}=await Promise.resolve().then(()=>(GLe(),g3t));o.getInstance().clear(),new Ji.Notice("All Copilot caches cleared successfully")}catch(n){console.error("Error clearing Copilot caches:",n),new Ji.Notice("Failed to clear Copilot caches")}}),df(t,Br.TOGGLE_AUTOCOMPLETE,()=>{let o=!ue().enableAutocomplete;dt("enableAutocomplete",o),new Ji.Notice(`Copilot autocomplete ${o?"enabled":"disabled"}`)}),A3t(t,Br.ADD_SELECTION_TO_CHAT_CONTEXT,async n=>{let o=Fh();if(o!=="copilot_plus"&&o!=="project"){new Ji.Notice("Selected text context is only available in Copilot Plus and Project modes");return}let i=n.getSelection();if(!i){new Ji.Notice("No text selected");return}let a=t.app.workspace.getActiveFile();if(!a){new Ji.Notice("No active file");return}let s=n.listSelections()[0];if(!s){new Ji.Notice("Could not determine selection range");return}let u=s.anchor.line+1,l=s.head.line+1,c={id:bC(),content:i,noteTitle:a.basename,notePath:a.path,startLine:Math.min(u,l),endLine:Math.max(u,l)};o8e(c),t.activateView()})}Cl();Fd();var aFe="{copilot-selection}";var XI={title:"",content:"",showInContextMenu:!1,showInSlashMenu:!1,order:Number.MAX_SAFE_INTEGER,modelKey:"",lastUsedMs:0},ID="copilot-command-context-menu-enabled",MD="copilot-command-slash-enabled",RD="copilot-command-context-menu-order",jD="copilot-command-model-key",ND="copilot-command-last-used",I3t=[{title:"Fix grammar and spelling",content:"Fix the grammar and spelling of {}. Preserve all formatting, line breaks, and special characters. Do not add or remove any content. Return only the corrected text.",showInContextMenu:!0,showInSlashMenu:!0,order:1e3,modelKey:"",lastUsedMs:0},{title:"Translate to Chinese",content:`Translate {} into Chinese:
2025-07-05 20:48:33 +08:00
1. Preserve the meaning and tone
2. Maintain appropriate cultural context
3. Keep formatting and structure
Return only the translated text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1010,modelKey:"",lastUsedMs:0},{title:"Summarize",content:"Create a bullet-point summary of {}. Each bullet point should capture a key point. Return only the bullet-point summary.",showInContextMenu:!0,showInSlashMenu:!0,order:1020,modelKey:"",lastUsedMs:0},{title:"Simplify",content:"Simplify {} to a 6th-grade reading level (ages 11-12). Use simple sentences, common words, and clear explanations. Maintain the original key concepts. Return only the simplified text.",showInContextMenu:!0,showInSlashMenu:!0,order:1030,modelKey:"",lastUsedMs:0},{title:"Explain like I am 5",content:`Explain {} in simple terms that a 5-year-old would understand:
1. Use basic vocabulary
2. Include simple analogies
3. Break down complex concepts
Return only the simplified explanation.`,showInContextMenu:!0,showInSlashMenu:!0,order:1040,modelKey:"",lastUsedMs:0},{title:"Emojify",content:`Add relevant emojis to enhance {}. Follow these rules:
1. Insert emojis at natural breaks in the text
2. Never place two emojis next to each other
3. Keep all original text unchanged
4. Choose emojis that match the context and tone
Return only the emojified text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1050,modelKey:"",lastUsedMs:0},{title:"Make shorter",content:`Reduce {} to half its length while preserving these elements:
1. Main ideas and key points
2. Essential details
3. Original tone and style
Return only the shortened text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1060,modelKey:"",lastUsedMs:0},{title:"Make longer",content:`Expand {} to twice its length by:
1. Adding relevant details and examples
2. Elaborating on key points
3. Maintaining the original tone and style
Return only the expanded text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1070,modelKey:"",lastUsedMs:0},{title:"Generate table of contents",content:"Generate a hierarchical table of contents for {}. Use appropriate heading levels (H1, H2, H3, etc.). Include page numbers if present. Return only the table of contents.",showInContextMenu:!1,showInSlashMenu:!1,order:1080,modelKey:"",lastUsedMs:0},{title:"Generate glossary",content:'Create a glossary of important terms, concepts, and phrases from {}. Format each entry as "Term: Definition". Sort entries alphabetically. Return only the glossary.',showInContextMenu:!1,showInSlashMenu:!1,order:1090,modelKey:"",lastUsedMs:0},{title:"Remove URLs",content:"Remove all URLs from {}. Preserve all other content and formatting. URLs may be in various formats (http, https, www). Return only the text with URLs removed.",showInContextMenu:!1,showInSlashMenu:!1,order:1100,modelKey:"",lastUsedMs:0},{title:"Rewrite as tweet",content:`Rewrite {} as a single tweet with these requirements:
1. Maximum 280 characters
2. Use concise, impactful language
3. Maintain the core message
Return only the tweet text.`,showInContextMenu:!1,showInSlashMenu:!1,order:1110,modelKey:"",lastUsedMs:0},{title:"Rewrite as tweet thread",content:`Convert {} into a Twitter thread following these rules:
1. Each tweet must be under 240 characters
2. Start with "THREAD START" on its own line
3. Separate tweets with "
---
"
4. End with "THREAD END" on its own line
5. Make content engaging and clear
2025-07-12 10:26:56 +08:00
Return only the formatted thread.`,showInContextMenu:!1,showInSlashMenu:!1,order:1120,modelKey:"",lastUsedMs:0}];var GU=require("obsidian");nr();u4();u4();var eE=cF(),tE=Ih([]);function lce(t){let e=eE.get(tE);e.some(r=>r.title===t)||eE.set(tE,[...e,{...XI,title:t}])}function EW(t){let e=eE.get(tE);eE.set(tE,e.filter(r=>r.title!==t))}function TW(t,e){let r=eE.get(tE),n;(e?r.findIndex(i=>i.title===e):-1)!==-1?n=r.map(i=>i.title===e?t:i):n=[...r,t],eE.set(tE,n)}function cce(t){eE.set(tE,t)}function M3t(){return a4(tE,{store:eE})}function Jx(){return eE.get(tE)}f4();yn();$r();function JU(t,e,r){let n=t.trim();return r&&n===r?null:/[#<>:"/\\|?*[\]^\x00-\x1F]/g.test(n)?'Command name contains invalid characters. Avoid using: < > : " / \\ | ? * [ ] ^':e.some(i=>i.title.toLowerCase()===n.toLowerCase())?"A command with this name already exists":null}function YU(t){return encodeURIComponent(t.toLowerCase())}function QI(){return(0,GU.normalizePath)(ue().customPromptsFolder)}function DD(t){return`${QI()}/${t}.md`}function ZU(t){if(!(t instanceof GU.TFile)||t.extension!=="md")return!1;let e=QI();return!(!t.path.startsWith(e+"/")||t.path.slice(e.length+1).includes("/"))}function l0n(t){if(t.startsWith("---")){let e=t.indexOf("---",3);if(e!==-1)return t.slice(e+3).trimStart()}return t}async function AW(t){let e=await app.vault.read(t),r=l0n(e),n=app.metadataCache.getFileCache(t),o=n?.frontmatter?.[ID]??XI.showInContextMenu,i=n?.frontmatter?.[MD]??XI.showInSlashMenu,a=n?.frontmatter?.[ND]??XI.lastUsedMs,s=n?.frontmatter?.[RD]??XI.order,u=n?.frontmatter?.[jD]??XI.modelKey;return{title:t.basename,modelKey:u,content:r,showInContextMenu:o,showInSlashMenu:i,order:s,lastUsedMs:a}}async function dce(){let t=app.vault.getFiles().filter(r=>ZU(r)),e=await Promise.all(t.map(AW));return cce(e),e}function IW(t){return[...t].sort((e,r)=>e.order===r.order?e.title.localeCompare(r.title):e.order-r.order)}function c0n(t){return[...t].sort((e,r)=>e.lastUsedMs===r.lastUsedMs?e.title.localeCompare(r.title):r.lastUsedMs-e.lastUsedMs)}function d0n(t){return[...t].sort((e,r)=>e.title.localeCompare(r.title))}function R3t(t){switch(ue().promptSortStrategy){case"timestamp":return c0n(t);case"alphabetical":return d0n(t);case"manual":return IW(t);default:return t}}async function sFe(t,e,r=!1){let o=(await fce(t,e,app.vault,app.workspace.getActiveFile())).processedPrompt;if(o.includes("{selectedText}")||r)return o;let i=o.indexOf(aFe);return i===-1&&e.trim()?o+`
2025-07-05 20:48:33 +08:00
2025-07-12 10:26:56 +08:00
<selectedText>`+e+"</selectedText>":o.slice(0,i)+e+o.slice(i+aFe.length)}var f0n=/\{(?!copilot-selection\})([^}]+)\}/g;async function p0n(t,e,r){let n=new Map,o=new Set,i;for(;(i=f0n.exec(t))!==null;){let a=i[1].trim(),s={content:"",files:[]};if(a.toLowerCase()==="activenote")if(r){let u=await mF(r,e);u&&(s.content=`## ${eJ(r)}
2025-07-05 20:48:33 +08:00
2025-07-12 10:26:56 +08:00
${u}`,s.files.push(r))}else new GU.Notice("No active note found.");else if(a.startsWith("#")){let u=a.slice(1).split(",").map(d=>d.trim()),l=await pVe(e,u),c=[];for(let d of l){let f=await mF(d,e);f&&(c.push(`## ${eJ(d)}
2025-07-05 20:48:33 +08:00
${f}`),s.files.push(d))}s.content=c.join(`
2025-07-12 10:26:56 +08:00
`)}else{let u=gVe(a),l=await Xhe(e,u),c=[];for(let d of l){let f=await mF(d,e);f&&(c.push(`## ${eJ(d)}
2025-07-05 20:48:33 +08:00
${f}`),s.files.push(d))}s.content=c.join(`
2025-07-12 10:26:56 +08:00
`)}s.content?(n.set(a,s.content),s.files.forEach(u=>o.add(u))):a.toLowerCase()!=="activenote"&&(a.startsWith('"')||console.warn(`No notes found for variable: ${a}`))}return{variablesMap:n,includedFiles:o}}async function fce(t,e,r,n){let o=ue(),i=new Set;if(!o.enableCustomPromptTemplating)return t.includes("{}")&&!e&&n&&i.add(n),{processedPrompt:t+`
2025-07-05 20:48:33 +08:00
2025-07-12 10:26:56 +08:00
`,includedFiles:Array.from(i)};let{variablesMap:a,includedFiles:s}=await p0n(t,r,n);s.forEach(f=>i.add(f));let u=t,l="",c=null;u.includes("{}")&&(u=u.replace(/\{\}/g,"{selectedText}"),e?l+=`selectedText:
2025-07-05 20:48:33 +08:00
2025-07-12 10:26:56 +08:00
${e}`:n?(c=await mF(n,r),l+=`selectedText (entire active note):
2025-07-05 20:48:33 +08:00
${c}`,i.add(n)):l+=`selectedText:
(No selected text or active note available)`);for(let[f,p]of a.entries())f.toLowerCase()==="activenote"&&c!==null||(l?l+=`
${f}:
${p}`:l+=`${f}:
2025-07-12 10:26:56 +08:00
${p}`);let d=DC(u,r);for(let f of d)if(!i.has(f)){let p=await mF(f,r);if(p){let m=`<${p4}>
2025-07-05 20:48:33 +08:00
Title: [[${f.basename}]]
Path: ${f.path}
${p}
2025-07-12 10:26:56 +08:00
</${p4}>`;l&&(l+=`
2025-07-05 20:48:33 +08:00
`),l+=`${m}`,i.add(f)}}return{processedPrompt:l?`${u}
${l}`:`${u}
2025-07-12 10:26:56 +08:00
`,includedFiles:Array.from(i)}}Cl();Fd();ti();var j3t=require("obsidian"),LD=F(X()),N3t=F(Dc());function m0n({content:t,onConfirm:e,onCancel:r,confirmButtonText:n,cancelButtonText:o}){return LD.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-5"},LD.default.createElement("div",{className:"tw-whitespace-pre-wrap"},t),LD.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},o&&LD.default.createElement(ge,{variant:"secondary",onClick:r},o),n&&LD.default.createElement(ge,{variant:"default",onClick:e},n)))}var sd=class extends j3t.Modal{constructor(r,n,o,i,a="Continue",s="Cancel"){super(r);this.onConfirm=n;this.content=o;this.confirmButtonText=a;this.cancelButtonText=s;this.setTitle(i)}onOpen(){let{contentEl:r}=this;this.root=(0,N3t.createRoot)(r);let n=()=>{this.onConfirm(),this.close()},o=()=>{this.close()};this.root.render(LD.default.createElement(m0n,{content:this.content,onConfirm:n,onCancel:o,confirmButtonText:this.confirmButtonText,cancelButtonText:this.cancelButtonText}))}onClose(){this.root.unmount()}};ti();var $i=F(X());var $l=F(X(),1);function MW(t,e,{checkForDefaultPrevented:r=!0}={}){return function(o){if(t?.(o),r===!1||!o.defaultPrevented)return e?.(o)}}var h0n=F(X(),1);function D3t(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function pce(...t){return e=>{let r=!1,n=t.map(o=>{let i=D3t(o,e);return!r&&typeof i=="function"&&(r=!0),i});if(r)return()=>{for(let o=0;o<n.length;o++){let i=n[o];typeof i=="function"?i():D3t(t[o],null)}}}}var Wg=F(X(),1),uFe=F(pt(),1);function L3t(t,e){let r=Wg.createContext(e),n=i=>{let{children:a,...s}=i,u=Wg.useMemo(()=>s,Object.values(s));return(0,uFe.jsx)(r.Provider,{value:u,children:a})};n.displayName=t+"Provider";function o(i){let a=Wg.useContext(r);if(a)return a;if(e!==void 0)return e;throw new Error(`\`${i}\` must be used within \`${t}\``)}return[n,o]}function Yi(t,e=[]){let r=[];function n(i,a){let s=Wg.createContext(a),u=r.length;r=[...r,a];let l=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[u]||s,b=Wg.useMemo(()=>m,Object.values(m));return(0,uFe.jsx)(h.Provider,{value:b,children:p})};l.displayName=i+"Provider";function c(d,f){let p=f?.[t]?.[u]||s,m=Wg.useContext(p);if(m)return m;if(a!==void 0)return a;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[l,c]}let o=()=>{let i=r.map(a=>Wg.createContext(a));return function(s){let u=s?.[t]||i;return Wg.useMemo(()=>({[`__scope${t}`]:{...s,[t]:u}}),[s,u])}};return o.scopeName=t,[n,g0n(o,...e)]}function g0n(...t){let e=t[0];if(t.length===1)return e;let r=()=>{let n=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let a=n.reduce((s,{useScope:u,scopeName:l})=>{let d=u(i)[`__scope${l}`];return{...s,...d}},{});return Wg.useMemo(()=>({[`__scope${e.scopeName}`]:a}),[a])}};return r.scopeName=e.scopeName,r}var eM=F(X(),1);var XU=F(X(),1);function Ur(t){let e=XU.useRef(t);return XU.useEffect(()=>{e.current=t}),XU.useMemo(()=>(...r)=>e.current?.(...r),[])}function ud({prop:t,defaultProp:e,onChange:r=()=>{}}){let[n,o]=y0n({defaultProp:e,onChange:r}),i=t!==void 0,a=i?t:n,s=Ur(r),u=eM.useCallback(l=>{if(i){let d=typeof l=="function"?l(t):l;d!==t&&s(d)}else o(l)},[i,t,o,s]);return[a,u]}function y0n({defaultProp:t,onChange:e}){let r=eM.useState(t),[n]=r,o=eM.useRef(n),i=Ur(e);return eM.useEffect(()=>{o.current!==n&&(i(n),o.current=n)},[n,o,i]),r}var F3t=F(X(),1),S0n=F(ds(),1);var ld=F(X(),1);var QU=F(pt(),1),cFe=ld.forwardRef((t,e)=>{let{children:r,...n}=t,o=ld.Children.toArray(r),i=o.find(_0n);if(i){let a=i.props.children,s=o.map(u=>u===i?ld.Children.count(a)>1?ld.Children.only(null):ld.isValidElement(a)?a.props.children:null:u);return(0,QU.jsx)(lFe,{...n,ref:e,children:ld.isValidElement(a)?ld.cloneElement(a,void 0,s):null})}return(0,QU.jsx)(lFe,{...n,ref:e,children:r})});cFe.displayName="Slot";var lFe=ld.forwardRef((t,e)=>{let{children:r,...n}=t;if(ld.isValidElement(r)){let o=w0n(r);return ld.cloneElement(r,{...v0n(n,r.props),ref:e?pce(e,o):o})}return ld.Children.count(r)>1?ld.Children.only(null):null});lFe.displayName="SlotClone";var b0n=({children:t})=>(0,Q
.`.concat($Fe,` {
2025-07-05 20:48:33 +08:00
overflow: hidden `).concat(n,`;
padding-right: `).concat(s,"px ").concat(n,`;
}
2025-07-12 10:26:56 +08:00
body[`).concat(uz,`] {
2025-07-05 20:48:33 +08:00
overflow: hidden `).concat(n,`;
overscroll-behavior: contain;
`).concat([e&&"position: relative ".concat(n,";"),r==="margin"&&`
padding-left: `.concat(o,`px;
padding-top: `).concat(i,`px;
padding-right: `).concat(a,`px;
margin-left:0;
margin-top:0;
margin-right: `).concat(s,"px ").concat(n,`;
`),r==="padding"&&"padding-right: ".concat(s,"px ").concat(n,";")].filter(Boolean).join(""),`
}
.`).concat(wb,` {
right: `).concat(s,"px ").concat(n,`;
}
.`).concat(Sb,` {
margin-right: `).concat(s,"px ").concat(n,`;
}
.`).concat(wb," .").concat(wb,` {
right: 0 `).concat(n,`;
}
.`).concat(Sb," .").concat(Sb,` {
margin-right: 0 `).concat(n,`;
}
2025-07-12 10:26:56 +08:00
body[`).concat(uz,`] {
`).concat(BFe,": ").concat(s,`px;
2025-07-05 20:48:33 +08:00
}
2025-07-12 10:26:56 +08:00
`)},RVt=function(){var t=parseInt(document.body.getAttribute(uz)||"0",10);return isFinite(t)?t:0},nxn=function(){lz.useEffect(function(){return document.body.setAttribute(uz,(RVt()+1).toString()),function(){var t=RVt()-1;t<=0?document.body.removeAttribute(uz):document.body.setAttribute(uz,t.toString())}},[])},KD=function(t){var e=t.noRelative,r=t.noImportant,n=t.gapMode,o=n===void 0?"margin":n;nxn();var i=lz.useMemo(function(){return VFe(o)},[o]);return lz.createElement(txn,{styles:rxn(i,!e,o,r?"":"!important")})};var WFe=!1;if(typeof window<"u")try{BW=Object.defineProperty({},"passive",{get:function(){return WFe=!0,!0}}),window.addEventListener("test",BW,BW),window.removeEventListener("test",BW,BW)}catch{WFe=!1}var BW,GD=WFe?{passive:!1}:!1;var oxn=function(t){return t.tagName==="TEXTAREA"},jVt=function(t,e){if(!(t instanceof Element))return!1;var r=window.getComputedStyle(t);return r[e]!=="hidden"&&!(r.overflowY===r.overflowX&&!oxn(t)&&r[e]==="visible")},ixn=function(t){return jVt(t,"overflowY")},axn=function(t){return jVt(t,"overflowX")},KFe=function(t,e){var r=e.ownerDocument,n=e;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var o=NVt(t,n);if(o){var i=DVt(t,n),a=i[1],s=i[2];if(a>s)return!0}n=n.parentNode}while(n&&n!==r.body);return!1},sxn=function(t){var e=t.scrollTop,r=t.scrollHeight,n=t.clientHeight;return[e,r,n]},uxn=function(t){var e=t.scrollLeft,r=t.scrollWidth,n=t.clientWidth;return[e,r,n]},NVt=function(t,e){return t==="v"?ixn(e):axn(e)},DVt=function(t,e){return t==="v"?sxn(e):uxn(e)},lxn=function(t,e){return t==="h"&&e==="rtl"?-1:1},LVt=function(t,e,r,n,o){var i=lxn(t,window.getComputedStyle(e).direction),a=i*n,s=r.target,u=e.contains(s),l=!1,c=a>0,d=0,f=0;do{var p=DVt(t,s),m=p[0],h=p[1],b=p[2],g=h-b-i*m;(m||g)&&NVt(t,s)&&(d+=g,f+=m),s instanceof ShadowRoot?s=s.host:s=s.parentNode}while(!u&&s!==document.body||u&&(e.contains(s)||e===s));return(c&&(o&&Math.abs(d)<1||!o&&a>d)||!c&&(o&&Math.abs(f)<1||!o&&-a>f))&&(l=!0),l};var $ce=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},FVt=function(t){return[t.deltaX,t.deltaY]},kVt=function(t){return t&&"current"in t?t.current:t},cxn=function(t,e){return t[0]===e[0]&&t[1]===e[1]},dxn=function(t){return`
2025-07-05 20:48:33 +08:00
.block-interactivity-`.concat(t,` {pointer-events: none;}
.allow-interactivity-`).concat(t,` {pointer-events: all;}
2025-07-12 10:26:56 +08:00
`)},fxn=0,cz=[];function $Vt(t){var e=ya.useRef([]),r=ya.useRef([0,0]),n=ya.useRef(),o=ya.useState(fxn++)[0],i=ya.useState(iE)[0],a=ya.useRef(t);ya.useEffect(function(){a.current=t},[t]),ya.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var h=sz([t.lockRef.current],(t.shards||[]).map(kVt),!0).filter(Boolean);return h.forEach(function(b){return b.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),h.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(o))})}}},[t.inert,t.lockRef.current,t.shards]);var s=ya.useCallback(function(h,b){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!a.current.allowPinchZoom;var g=$ce(h),y=r.current,S="deltaX"in h?h.deltaX:y[0]-g[0],x="deltaY"in h?h.deltaY:y[1]-g[1],O,P=h.target,E=Math.abs(S)>Math.abs(x)?"h":"v";if("touches"in h&&E==="h"&&P.type==="range")return!1;var A=KFe(E,P);if(!A)return!0;if(A?O=E:(O=E==="v"?"h":"v",A=KFe(E,P)),!A)return!1;if(!n.current&&"changedTouches"in h&&(S||x)&&(n.current=O),!O)return!0;var I=n.current||O;return LVt(I,b,h,I==="h"?S:x,!0)},[]),u=ya.useCallback(function(h){var b=h;if(!(!cz.length||cz[cz.length-1]!==i)){var g="deltaY"in b?FVt(b):$ce(b),y=e.current.filter(function(O){return O.name===b.type&&(O.target===b.target||b.target===O.shadowParent)&&cxn(O.delta,g)})[0];if(y&&y.should){b.cancelable&&b.preventDefault();return}if(!y){var S=(a.current.shards||[]).map(kVt).filter(Boolean).filter(function(O){return O.contains(b.target)}),x=S.length>0?s(b,S[0]):!a.current.noIsolation;x&&b.cancelable&&b.preventDefault()}}},[]),l=ya.useCallback(function(h,b,g,y){var S={name:h,delta:b,target:g,should:y,shadowParent:pxn(g)};e.current.push(S),setTimeout(function(){e.current=e.current.filter(function(x){return x!==S})},1)},[]),c=ya.useCallback(function(h){r.current=$ce(h),n.current=void 0},[]),d=ya.useCallback(function(h){l(h.type,FVt(h),h.target,s(h,t.lockRef.current))},[]),f=ya.useCallback(function(h){l(h.type,$ce(h),h.target,s(h,t.lockRef.current))},[]);ya.useEffect(function(){return cz.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,GD),document.addEventListener("touchmove",u,GD),document.addEventListener("touchstart",c,GD),function(){cz=cz.filter(function(h){return h!==i}),document.removeEventListener("wheel",u,GD),document.removeEventListener("touchmove",u,GD),document.removeEventListener("touchstart",c,GD)}},[]);var p=t.removeScrollBar,m=t.inert;return ya.createElement(ya.Fragment,null,m?ya.createElement(i,{styles:dxn(o)}):null,p?ya.createElement(KD,{gapMode:t.gapMode}):null)}function pxn(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var BVt=WD(kce,$Vt);var qVt=Bce.forwardRef(function(t,e){return Bce.createElement($W,yi({},t,{ref:e,sideCar:BVt}))});qVt.classNames=$W.classNames;var GFe=qVt;var Mr=F(pt(),1),JFe=["Enter"," "],mxn=["ArrowDown","PageUp","Home"],zVt=["ArrowUp","PageDown","End"],hxn=[...mxn,...zVt],gxn={ltr:[...JFe,"ArrowRight"],rtl:[...JFe,"ArrowLeft"]},yxn={ltr:["ArrowLeft"],rtl:["ArrowRight"]},HW="Menu",[UW,bxn,_xn]=U3t(HW),[JD,YFe]=Yi(HW,[_xn,TFe,FFe]),VW=TFe(),HVt=FFe(),[VVt,vM]=JD(HW),[vxn,WW]=JD(HW),WVt=t=>{let{__scopeMenu:e,open:r=!1,children:n,dir:o,onOpenChange:i,modal:a=!0}=t,s=VW(e),[u,l]=zt.useState(null),c=zt.useRef(!1),d=Ur(i),f=nM(o);return zt.useEffect(()=>{let p=()=>{c.current=!0,document.addEventListener("pointerdown",m,{capture:!0,once:!0}),document.addEventListener("pointermove",m,{capture:!0,once:!0})},m=()=>c.current=!1;return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",m,{capture:!0}),document.removeEventListener("pointermove",m,{capture:!0})}},[]),(0,Mr.jsx)(IFe,{...s,children:(0,Mr.jsx)(VVt,{scope:e,open:r,onOpenChange:d,content:u,onContentChange:l,children:(0,Mr.jsx)(vxn,{scope:e,onClose:zt.useCallback(()=>d(!1),[d]),isUsingKeyboardRef
2025-07-05 20:48:33 +08:00
Embedded PDF (${s}):
${l}
`)}catch(l){console.error(`Error processing embedded PDF ${s}:`,l),e=e.replace(a[0],`
Embedded PDF (${s}): [Error: Could not process PDF]
2025-07-12 10:26:56 +08:00
`)}}return e}async processContextNotes(e,r,n,o,i,a,s){let u="",l=async(d,f=p4)=>{try{if(e.has(d.path)){console.log(`Skipping note ${d.path} as it was included via custom prompt.`);return}if(console.log(`Processing note: ${d.path}, extension: ${d.extension}, chain: ${s}`),!r.supportsExtension(d.extension)){console.warn(`Unsupported file type: ${d.extension}`);return}if(s!=="copilot_plus"&&d.extension!=="md"&&d.extension!=="canvas"){console.warn(`File type ${d.extension} requires Copilot Plus mode for context processing.`);return}let p=await r.parseFile(d,n);d.extension==="md"&&s==="copilot_plus"&&(p=await this.processEmbeddedPDFs(p,n,r)),u+=`
2025-07-05 20:48:33 +08:00
<${f}>
Title: [[${d.basename}]]
Path: ${d.path}
${p}
</${f}>`}catch(p){console.error(`Error processing file ${d.path}:`,p),u+=`
<${f}_error>
Title: [[${d.basename}]]
Path: ${d.path}
[Error: Could not process file]
2025-07-12 10:26:56 +08:00
</${f}_error>`}},c=new Set;i&&a&&(await l(a,"active_note"),c.add(a.path));for(let d of o)c.has(d.path)||(await l(d),c.add(d.path));return u}async hasEmbeddedPDFs(e){return/!\[\[(.*?\.pdf)\]\]/g.test(e)}async addNoteToContext(e,r,n,o,i,a){if(n.some(l=>l.path===e.path))return;let s=await r.read(e),u=await this.hasEmbeddedPDFs(s);o&&e.path===o.path&&a(!0),i(l=>[...l,Object.assign(e,{wasAddedViaReference:!0,hasEmbeddedPDFs:u})])}processSelectedTextContexts(){let e=gJ();if(!e||e.length===0)return"";let r="";for(let n of e){let o=n.startLine===n.endLine?`L${n.startLine}`:`L${n.startLine}-${n.endLine}`;r+=`
2025-07-05 20:48:33 +08:00
<selected_text>
Title: [[${n.noteTitle}]]
Path: ${n.notePath}
Lines: ${o}
${n.content}
2025-07-12 10:26:56 +08:00
</selected_text>`}return r}};var rde=require("obsidian");wT();var lm=class t{static getInstance(){return t.instance||(t.instance=new t),t.instance}async createCommand(e,r,n=!1){n||lce(e);let o=QI(),i=DD(e);await app.vault.adapter.exists(o)||await app.vault.createFolder(o);let s=await app.vault.create(i,r);await app.fileManager.processFrontMatter(s,u=>{u[ID]=!1,u[MD]=!1,u[RD]=Number.MAX_SAFE_INTEGER,u[jD]="",u[ND]=0})}async recordUsage(e){this.updateCommand({...e,lastUsedMs:Date.now()},e.title)}async updateCommand(e,r,n=!1){n||TW(e,r);let o=app.vault.getAbstractFileByPath(DD(e.title));if(e.title!==r){let i=DD(e.title);if(app.vault.getAbstractFileByPath(i))throw new Rr("Error saving custom prompt. Please check if the title already exists.");let s=DD(r),u=app.vault.getAbstractFileByPath(s);u instanceof rde.TFile&&(await app.vault.rename(u,i),o=u)}o||(await this.createCommand(e.title,e.content,n),o=app.vault.getAbstractFileByPath(DD(e.title))),o instanceof rde.TFile&&(await app.vault.modify(o,e.content),await app.fileManager.processFrontMatter(o,i=>{i[ID]=e.showInContextMenu,i[MD]=e.showInSlashMenu,i[RD]=e.order,i[jD]=e.modelKey,i[ND]=e.lastUsedMs}))}async updateCommands(e){cce(e),await Promise.all(e.map(r=>this.updateCommand(r,r.title,!0)))}async deleteCommand(e){EW(e.title);let r=app.vault.getAbstractFileByPath(DD(e.title));r instanceof rde.TFile&&await app.vault.delete(r)}};nr();yn();bn();var CM=require("obsidian"),at=F(X());var wn=F(X()),Mi=F(r5t());function xM(t,e,r,n){function o(i){return i instanceof r?i:new r(function(a){a(i)})}return new(r||(r=Promise))(function(i,a){function s(c){try{l(n.next(c))}catch(d){a(d)}}function u(c){try{l(n.throw(c))}catch(d){a(d)}}function l(c){c.done?i(c.value):o(c.value).then(s,u)}l((n=n.apply(t,e||[])).next())})}var pOn=new Map([["1km","application/vnd.1000minds.decision-model+xml"],["3dml","text/vnd.in3d.3dml"],["3ds","image/x-3ds"],["3g2","video/3gpp2"],["3gp","video/3gp"],["3gpp","video/3gpp"],["3mf","model/3mf"],["7z","application/x-7z-compressed"],["7zip","application/x-7z-compressed"],["123","application/vnd.lotus-1-2-3"],["aab","application/x-authorware-bin"],["aac","audio/x-acc"],["aam","application/x-authorware-map"],["aas","application/x-authorware-seg"],["abw","application/x-abiword"],["ac","application/vnd.nokia.n-gage.ac+xml"],["ac3","audio/ac3"],["acc","application/vnd.americandynamics.acc"],["ace","application/x-ace-compressed"],["acu","application/vnd.acucobol"],["acutc","application/vnd.acucorp"],["adp","audio/adpcm"],["aep","application/vnd.audiograph"],["afm","application/x-font-type1"],["afp","application/vnd.ibm.modcap"],["ahead","application/vnd.ahead.space"],["ai","application/pdf"],["aif","audio/x-aiff"],["aifc","audio/x-aiff"],["aiff","audio/x-aiff"],["air","application/vnd.adobe.air-application-installer-package+zip"],["ait","application/vnd.dvb.ait"],["ami","application/vnd.amiga.ami"],["amr","audio/amr"],["apk","application/vnd.android.package-archive"],["apng","image/apng"],["appcache","text/cache-manifest"],["application","application/x-ms-application"],["apr","application/vnd.lotus-approach"],["arc","application/x-freearc"],["arj","application/x-arj"],["asc","application/pgp-signature"],["asf","video/x-ms-asf"],["asm","text/x-asm"],["aso","application/vnd.accpac.simply.aso"],["asx","video/x-ms-asf"],["atc","application/vnd.acucorp"],["atom","application/atom+xml"],["atomcat","application/atomcat+xml"],["atomdeleted","application/atomdeleted+xml"],["atomsvc","application/atomsvc+xml"],["atx","application/vnd.antix.game-component"],["au","audio/x-au"],["avi","video/x-msvideo"],["avif","image/avif"],["aw","application/applixware"],["azf","application/vnd.airzip.filesecure.azf"],["azs","application/vnd.airzip.filesecure.azs"],["azv","image/vnd.airzip.accelerator.azv"],["azw","application/vnd.amazon.ebook"],["b16","image/vnd.pco.b16"],["bat","application/x-msdownload"],["bcpio","application/x-bcpio"],["bdf","application/x-font-bdf"],["bdm","application/vnd.syncml.dm+wbxml"],["bdoc","application/x-bdoc"],["bed","application/vnd.realvnc.bed"],["bh2","applicatio
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function OOn(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function POn(t){if(Array.isArray(t))return Nke(t)}function c5t(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),r.push.apply(r,n)}return r}function d5t(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?c5t(Object(r),!0).forEach(function(n){m5t(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):c5t(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}function m5t(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function t9(t,e){return AOn(t)||TOn(t,e)||h5t(t,e)||EOn()}function EOn(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function h5t(t,e){if(t){if(typeof t=="string")return Nke(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Nke(t,e)}}function Nke(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function TOn(t,e){var r=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(r!=null){var n=[],o=!0,i=!1,a,s;try{for(r=r.call(t);!(o=(a=r.next()).done)&&(n.push(a.value),!(e&&n.length===e));o=!0);}catch(u){i=!0,s=u}finally{try{!o&&r.return!=null&&r.return()}finally{if(i)throw s}}return n}}function AOn(t){if(Array.isArray(t))return t}var IOn=typeof ode.default=="function"?ode.default:ode.default.default,MOn="file-invalid-type",ROn="file-too-large",jOn="file-too-small",NOn="too-many-files";var DOn=function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",r=e.split(","),n=r.length>1?"one of ".concat(r.join(", ")):r[0];return{code:MOn,message:"File type must be ".concat(n)}},f5t=function(e){return{code:ROn,message:"File is larger than ".concat(e," ").concat(e===1?"byte":"bytes")}},p5t=function(e){return{code:jOn,message:"File is smaller than ".concat(e," ").concat(e===1?"byte":"bytes")}},g5t={code:NOn,message:"Too many files"};function Dke(t,e){var r=t.type==="application/x-moz-file"||IOn(t,e);return[r,r?null:DOn(e)]}function Lke(t,e,r){if(eL(t.size))if(eL(e)&&eL(r)){if(t.size>r)return[!1,f5t(r)];if(t.size<e)return[!1,p5t(e)]}else{if(eL(e)&&t.size<e)return[!1,p5t(e)];if(eL(r)&&t.size>r)return[!1,f5t(r)]}return[!0,null]}function eL(t){return t!=null}function y5t(t){var e=t.files,r=t.accept,n=t.minSize,o=t.maxSize,i=t.multiple,a=t.maxFiles,s=t.validator;return!i&&e.length>1||i&&a>=1&&e.length>a?!1:e.every(function(u){var l=Dke(u,r),c=t9(l,1),d=c[0],f=Lke(u,n,o),p=t9(f,1),m=p[0],h=s?s(u):null;return d&&m&&!h})}function r9(t){return typeof t.isPropagationStopped=="function"?t.isPropagationStopped():typeof t.cancelBubble<"u"?t.cancelBubble:!1}function n9(t){return t.dataTransfer?Array.prototype.some.call(t.dataTransfer.types,function(e){return e==="Files"||e==="application/x-moz-file"}):!!t.target&&!!t.target.files}function Fke(t){t.preventDefault()}function LOn(t){return t.indexOf("MSIE")!==-1||t.indexOf("Trident/")!==-1}function FOn(t){return t.indexOf("Edge/")!==-1}function b5t(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.navigator.userAgent;return LOn(t)||FOn(t)}function Pb(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return function(n){for(var o=arguments.length,i=new Array(o>1?o-1:0),a=1;a<o;a++)i[a-1]=arguments[a];return e.some(function(s){return!r9(n)&&s&&s.apply(void 0,[n].concat(i)),r9(n)})}}function _5t(){return"showOpenFilePicker"in window}function v5t(t){if(eL(t)){var e=Object.entries(t).filter(function(r){var n=t9(r,2),o=n[0],i=n[1],a=!0;return C5t(o)||(console.warn('Skipped "'.concat(o,'" because it is not a valid MIME type. Check https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for a list of valid MIME types.')),a=!1),(!Array.isArray(i)||!i.every(O5t))&&(console.warn('Skipped "'.concat(o,'" because an invalid file extension was provided.')),a=!1),a}).reduce(function(r,n){var o=t9(n,2),i=o[0],a=o[1];return d5t(d5t({},r),{},m5t({},i,a))},{});return[{description:"Files",accept:e}]}return t}function w5t(t){if(eL(t))return Object.entries(t).reduce(function(e,r){var n=t9(r,2),o=n[0],i=n[1];return[].concat(l5t(e),[o],l5t(i))},[]).filter(function(e){return C5t(e)||O5t(e)}).join(",")}function S5t(t){return t instanceof DOMException&&(t.name==="AbortError"||t.code===t.ABORT_ERR)}function x5t(t){return t instanceof DOMException&&(t.name==="SecurityError"||t.code===t.SECURITY_ERR)}function C5t(t){return t==="audio/*"||t==="video/*"||t==="image/*"||t==="text/*"||t==="application/*"||/\w+\/[-+.\w]+/g.test(t)}function
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function HOn(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function VOn(t){if(Array.isArray(t))return $ke(t)}function kke(t,e){return GOn(t)||KOn(t,e)||T5t(t,e)||WOn()}function WOn(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function T5t(t,e){if(t){if(typeof t=="string")return $ke(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return $ke(t,e)}}function $ke(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function KOn(t,e){var r=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(r!=null){var n=[],o=!0,i=!1,a,s;try{for(r=r.call(t);!(o=(a=r.next()).done)&&(n.push(a.value),!(e&&n.length===e));o=!0);}catch(u){i=!0,s=u}finally{try{!o&&r.return!=null&&r.return()}finally{if(i)throw s}}return n}}function GOn(t){if(Array.isArray(t))return t}function P5t(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),r.push.apply(r,n)}return r}function ts(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?P5t(Object(r),!0).forEach(function(n){Bke(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):P5t(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}function Bke(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function ide(t,e){if(t==null)return{};var r=JOn(t,e),n,o;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(o=0;o<i.length;o++)n=i[o],!(e.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function JOn(t,e){if(t==null)return{};var r={},n=Object.keys(t),o,i;for(i=0;i<n.length;i++)o=n[i],!(e.indexOf(o)>=0)&&(r[o]=t[o]);return r}var Uke=(0,wn.forwardRef)(function(t,e){var r=t.children,n=ide(t,kOn),o=zke(n),i=o.open,a=ide(o,$On);return(0,wn.useImperativeHandle)(e,function(){return{open:i}},[i]),wn.default.createElement(wn.Fragment,null,r(ts(ts({},a),{},{open:i})))});Uke.displayName="Dropzone";var A5t={disabled:!1,getFilesFromEvent:Rke,maxSize:1/0,minSize:0,multiple:!0,maxFiles:0,preventDropOnDocument:!0,noClick:!1,noKeyboard:!1,noDrag:!1,noDragEventsBubbling:!1,validator:null,useFsAccessApi:!1,autoFocus:!1};Uke.defaultProps=A5t;Uke.propTypes={children:Mi.default.func,accept:Mi.default.objectOf(Mi.default.arrayOf(Mi.default.string)),multiple:Mi.default.bool,preventDropOnDocument:Mi.default.bool,noClick:Mi.default.bool,noKeyboard:Mi.default.bool,noDrag:Mi.default.bool,noDragEventsBubbling:Mi.default.bool,minSize:Mi.default.number,maxSize:Mi.default.number,maxFiles:Mi.default.number,disabled:Mi.default.bool,getFilesFromEvent:Mi.default.func,onFileDialogCancel:Mi.default.func,onFileDialogOpen:Mi.default.func,useFsAccessApi:Mi.default.bool,autoFocus:Mi.default.bool,onDragEnter:Mi.default.func,onDragLeave:Mi.default.func,onDragOver:Mi.default.func,onDrop:Mi.default.func,onDropAccepted:Mi.default.func,onDropRejected:Mi.default.func,onError:Mi.default.func,validator:Mi.default.func};var qke={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function zke(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=ts(ts({},A5t),t),r=e.accept,n=e.disabled,o=e.getFilesFromEvent,i=e.maxSize,a=e.minSize,s=e.multiple,u=e.maxFiles,l=e.onDragEnter,c=e.onDragLeave,d=e.onDragOver,f=e.onDrop,p=e.onDropAccepted,m=e.onDropRejected,h=e.onFileDialogCancel,b=e.onFileDialogOpen,g=e.useFsAccessApi,y=e.autoFocus,S=e.preventDropOnDocument,x=e.noClick,O=e.noKeyboard,P=e.noDrag,E=e.noDragEventsBubbling,A=e.onError,I=e.validator,R=(0,wn.useMemo)(function(){return w5t(r)},[r]),N=(0,wn.useMemo)(function(){return v5t(r)},[r]),j=(0,wn.useMemo)(function(){return typeof b=="function"?b:E5t},[b]),$=(0,wn.useMemo)(function(){return typeof h=="function"?h:E5t},[h]),k=(0,wn.useRef)(null),z=(0,wn.useRef)(null),V=(0,wn
`));var r=[],n=t.split(/(\n|\r\n)/);n[n.length-1]||n.pop();for(var o=0;o<n.length;o++){var i=n[o];o%2&&!e.newlineIsToken?r[r.length-1]+=i:r.push(i)}return r};cde.equals=function(t,e,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
2025-07-05 20:48:33 +08:00
`))&&(t=t.trim()),(!r.newlineIsToken||!e.includes(`
`))&&(e=e.trim())):r.ignoreNewlineAtEof&&!r.newlineIsToken&&(t.endsWith(`
`)&&(t=t.slice(0,-1)),e.endsWith(`
2025-07-12 10:26:56 +08:00
`)&&(e=e.slice(0,-1))),Eb.prototype.equals.call(this,t,e,r)};function W5t(t,e,r){var n=oPn(r,{ignoreWhitespace:!0});return cde.diff(t,e,n)}var iPn=new Eb;iPn.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var aPn=new Eb;aPn.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function Wke(t){"@babel/helpers - typeof";return Wke=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Wke(t)}var i9=new Eb;i9.useLongestToken=!0;i9.tokenize=cde.tokenize;i9.castInput=function(t,e){var r=e.undefinedReplacement,n=e.stringifyReplacer,o=n===void 0?function(i,a){return typeof a>"u"?r:a}:n;return typeof t=="string"?t:JSON.stringify(Kke(t,null,null,o),o," ")};i9.equals=function(t,e,r){return Eb.prototype.equals.call(i9,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"),r)};function Kke(t,e,r,n,o){e=e||[],r=r||[],n&&(t=n(o,t));var i;for(i=0;i<e.length;i+=1)if(e[i]===t)return r[i];var a;if(Object.prototype.toString.call(t)==="[object Array]"){for(e.push(t),a=new Array(t.length),r.push(a),i=0;i<t.length;i+=1)a[i]=Kke(t[i],e,r,n,o);return e.pop(),r.pop(),a}if(t&&t.toJSON&&(t=t.toJSON()),Wke(t)==="object"&&t!==null){e.push(t),a={},r.push(a);var s=[],u;for(u in t)Object.prototype.hasOwnProperty.call(t,u)&&s.push(u);for(s.sort(),i=0;i<s.length;i+=1)u=s[i],a[u]=Kke(t[u],e,r,n,u);e.pop(),r.pop()}else a=t;return a}var Gke=new Eb;Gke.tokenize=function(t){return t.slice()};Gke.join=Gke.removeEmpty=function(t){return t};var Sr=F(X()),X5t=F(Dc());var Tb=F(X());ti();bn();Tn();yo();bn();var sE=require("obsidian"),wr=F(X()),K5t=F(Dc());ti();var G5t=F(X());function sPn(t){return t.trim().split(`
2025-07-05 20:48:33 +08:00
`).map(r=>"- "+r).join(`
2025-07-12 10:26:56 +08:00
`)}function Jke(t){return t.map(r=>{let n=r.some(a=>a.added),o=r.some(a=>a.removed),i="";return n?i=r.map(a=>a.added?a.value:"").join(`
`):o?i=r.map(a=>a.removed?sPn(a.value):"").join(`
2025-07-05 20:48:33 +08:00
`):r.map(s=>s.value).join(`
`).trim().length>0&&(i="..."),i}).join(`
2025-07-12 10:26:56 +08:00
`)}function s9(t){let e=[],r=[];return t.forEach(n=>{n.added||n.removed?r.push(n):(r.length>0&&(e.push(r),r=[]),e.push([n]))}),r.length>0&&e.push(r),e}var u9="obsidian-copilot-apply-view",dde=class extends sE.ItemView{constructor(r){super(r);this.root=null;this.state=null}getViewType(){return u9}getDisplayText(){return"Preview Changes"}async setState(r){this.state=r,this.render()}async onOpen(){this.render()}async onClose(){this.root&&(this.root.unmount(),this.root=null)}render(){if(!this.state)return;let r=this.containerEl.children[1];r.empty();let n=r.createDiv();this.root||(this.root=(0,K5t.createRoot)(n)),this.root.render(wr.default.createElement(uPn,{app:this.app,state:this.state,close:()=>this.leaf.detach()}))}},J5t=(0,wr.memo)(({oldLine:t,newLine:e})=>{let r=H5t(t,e);return wr.default.createElement(wr.default.Fragment,null,r.map((n,o)=>n.added?wr.default.createElement("span",{key:o,className:"tw-text-success"},n.value):n.removed?wr.default.createElement("span",{key:o,className:"tw-text-error tw-line-through"},n.value):wr.default.createElement("span",{key:o},n.value)))});J5t.displayName="WordDiff";var uPn=({app:t,state:e,close:r})=>{let[n,o]=(0,G5t.useState)(()=>e.changes.map(p=>({...p,accepted:null}))),i=s9(n),a=(0,wr.useRef)([]);if(!e||!e.changes)return fe("Invalid state:",e),wr.default.createElement("div",{className:"tw-flex tw-h-full tw-flex-col tw-items-center tw-justify-center"},wr.default.createElement("div",{className:"tw-text-error"},"Error: Invalid state - missing changes"),wr.default.createElement(ge,{onClick:r,className:"tw-mt-4"},"Close"));let s=async()=>{try{let p=n.map(m=>m.accepted===null?{...m,accepted:!0}:m);await l(p)}catch(p){fe("Error applying changes:",p),new sE.Notice(`Error applying changes: ${p.message}`)}},u=async()=>{try{let p=n.map(m=>m.accepted===null?{...m,accepted:!1}:m);await l(p)}catch(p){fe("Error applying changes:",p),new sE.Notice(`Error applying changes: ${p.message}`)}},l=async p=>{let m=p.filter(b=>b.added?b.accepted===!0:b.removed?b.accepted===!1:!0).map(b=>b.value).join(""),h=t.vault.getAbstractFileByPath(e.path);if(!h||!(h instanceof sE.TFile)){new sE.Notice("File not found:"+e.path),r();return}await t.vault.modify(h,m),new sE.Notice("Changes applied successfully"),r()},c=p=>{if(!i)return;let m=-1;for(let h=p+1;h<i.length;h++){let b=i[h],g=b.some(S=>S.added||S.removed),y=b.some(S=>(S.added||S.removed)&&S.accepted===null);if(g&&y){m=h;break}}m!==-1&&a.current[m]&&a.current[m]?.scrollIntoView({behavior:"smooth",block:"center"})},d=p=>{o(m=>{let h=[...m],b=i?.[p];return b&&b.forEach(g=>{let y=h.findIndex(S=>S===g);y!==-1&&(h[y]={...h[y],accepted:!0})}),h}),setTimeout(()=>c(p),0)},f=p=>{o(m=>{let h=[...m],b=i?.[p];return b&&b.forEach(g=>{let y=h.findIndex(S=>S===g);y!==-1&&(h[y]={...h[y],accepted:!1})}),h}),setTimeout(()=>c(p),0)};return wr.default.createElement("div",{className:"tw-relative tw-flex tw-h-full tw-flex-col"},wr.default.createElement("div",{className:"tw-fixed tw-bottom-2 tw-left-1/2 tw-z-[1] tw-flex tw-gap-2 tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-secondary tw-p-2"},wr.default.createElement(ge,{variant:"destructive",size:"sm",onClick:u},wr.default.createElement(Vi,{className:"tw-size-4"}),"Reject"),wr.default.createElement(ge,{variant:"success",size:"sm",onClick:s},wr.default.createElement(Jl,{className:"tw-size-4"}),"Accept")),wr.default.createElement("div",{className:"tw-flex tw-items-center tw-border-b tw-border-solid tw-border-border tw-p-2 tw-text-sm tw-font-medium"},e.path),wr.default.createElement("div",{className:"tw-flex-1 tw-overflow-auto tw-p-2"},i?.map((p,m)=>{let h=p.some(g=>g.added||g.removed),b=h?p.every(g=>!g.added&&!g.removed||g.accepted===!0)?"accepted":p.every(g=>!g.added&&!g.removed||g.accepted===!1)?"rejected":"undecided":"unchanged";return wr.default.createElement("div",{key:m,ref:g=>a.current[m]=g,className:_e("tw-mb-4 tw-overflow-hidden tw-rounded-md")},b==="accepted"?wr.default.createElement("div",{className:"tw-flex-1 tw-whitespace-pre-wrap tw-px-2 tw-py-1 tw-font-mono tw-text-sm tw-text-normal"},p.filter(g=>!g.re
2025-07-05 20:48:33 +08:00
<summary style="${W}">Thought for a second</summary>
<div class="tw-text-muted" style="${Y}">${le.trim()}</div>
</details>
`),ee=ee.replace(/<think>([\s\S]*)$/,(Oe,le)=>`<div style="${U}">
<div style="${W}">Thinking...</div>
<div class="tw-text-muted" style="${Y}">${le.trim()}</div>
</div>`),ee;let ae=/<think>([\s\S]*?)<\/think>/g;return ee.replace(ae,(Oe,le)=>`<details style="${U}">
<summary style="${W}">Thought for a second</summary>
<div class="tw-text-muted" style="${Y}">${le.trim()}</div>
</details>
`)},V=ee=>{let U=W=>`\u23F3 Generating changes for ${W}...`;if(r){let W=/(\{[\s\S]*?"type"\s*:\s*"composer"[\s\S]*?)(?=\}|$)/g,Y;for(;(Y=W.exec(ee))!==null;){let ae=Y[1],Oe=Y.index,le=ae.match(/"path"\s*:\s*"([^"]+)"/),Be=le?le[1].trim():"...";ee=ee.substring(0,Oe)+U(Be);break}}return ee},Q=(ee,U,W)=>ee.split(/(```[\s\S]*?```|`[^`]*`)/g).map((ae,Oe)=>Oe%2===0?ae.replace(U,(le,Be)=>{let ze=e.metadataCache.getFirstLinkpathDest(Be,k);return ze?W(ze):le}):ae).join(""),J=j.replace(/\\\[\s*/g,"$$").replace(/\s*\\\]/g,"$$").replace(/\\\(\s*/g,"$").replace(/\s*\\\)/g,"$"),D=V(J),B=Q(D,/!\[\[(.*?)]]/g,ee=>`![](${e.vault.getResourcePath(ee)})`),q=z(B),K=y(q);return Q(K,/(?<!!)\[\[([^\]]+)]]/g,ee=>`<a href="obsidian://open?file=${encodeURIComponent(ee.path)}">${ee.basename}</a>`)},[e,r]),y=j=>{let $=j.split(`
#### Sources:
`);if($.length!==2)return j;let[k,z]=$,V=z.split(`
`).map(Q=>{let J=Q.match(/- \[\[(.*?)\]\]/);return J?`<li>[[${J[1]}]]</li>`:Q}).join(`
`);return k+`
<br/>
<details><summary>Sources</summary>
<ul>
`+V+`
</ul>
2025-07-12 10:26:56 +08:00
</details>`};(0,Sr.useEffect)(()=>{let j=[],$=!1;if(p.current&&t.sender!==Pi){p.current.innerHTML="",m.current||(m.current=new lE.Component);let k=g(t.message);if(!$&&(lE.MarkdownRenderer.renderMarkdown(k,p.current,"",m.current),!r)){let z=p.current.querySelectorAll("pre");z.length>0&&z.forEach(V=>{if($)return;let Q=V.querySelector("code");if(!Q)return;let J=Q.textContent||"";try{if(J.trim().startsWith("{")&&J.trim().endsWith("}")){let D=JSON.parse(J);if(D.type==="composer"&&D.path&&(typeof D.content=="string"||typeof D.canvas_json=="object")){let B;typeof D.content=="string"?B=D.content:B=JSON.stringify(D.canvas_json);let q=D.path.trim();q.startsWith("/")&&(q=q.slice(1));let K=document.createElement("div");V.parentNode?.replaceChild(K,V);let H=(0,X5t.createRoot)(K);j.push(H);let ee=e.vault.getAbstractFileByPath(q),U=[];(async()=>{if(ee instanceof lE.TFile){let W=await e.vault.read(ee);U=W5t(W,B,{newlineIsToken:!0})}else{let W=q.split("/").pop()?.split(".")[0],Y=B.split(`
2025-07-05 20:48:33 +08:00
`);(Y[0]===`# ${W}
`||Y[0]===`## ${W}`)&&Y.shift(),B=Y.join(`
2025-07-12 10:26:56 +08:00
`)}$||H.render(Sr.default.createElement(Z5t,{note_path:q,note_content:B,note_changes:U}))})()}}}catch(D){console.error("Failed to parse composer JSON:",D)}})}}return()=>{$=!0,setTimeout(()=>{m.current&&(m.current.unload(),m.current=null),j.forEach(k=>{try{k.unmount()}catch{}})},0)}},[t,e,m,r,g]),(0,Sr.useEffect)(()=>{l&&h.current&&S(h.current)},[l]),(0,Sr.useEffect)(()=>{f(t.message)},[t.message]);let S=j=>{j.style.height="auto",j.style.height=`${j.scrollHeight}px`},x=j=>{f(j.target.value),S(j.target)},O=j=>{j.nativeEvent.isComposing||(j.key==="Enter"&&!j.shiftKey?(j.preventDefault(),A()):j.key==="Escape"&&(j.preventDefault(),P()))},P=()=>{c(!1),f(t.message)},E=()=>{c(!0)},A=()=>{c(!1),o&&o(d)},I=()=>{t.sources&&t.sources.length>0&&new sde(e,t.sources).open()},R=()=>{let j=e.workspace.getMostRecentLeaf();if((!j||!(j.view instanceof lE.MarkdownView))&&(j=e.workspace.getLeaf(!1),!j||!(j.view instanceof lE.MarkdownView)))return;let k=j.view.editor.getSelection().length>0;c4(t.message,k)},N=()=>t.content?Sr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-3"},t.content.map((j,$)=>j.type==="text"?Sr.default.createElement("div",{key:$},t.sender===Pi&&l?Sr.default.createElement("textarea",{ref:h,value:d,onChange:x,onKeyDown:O,autoFocus:!0,className:"edit-textarea"}):t.sender===Pi?Sr.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-break-words tw-text-[calc(var(--font-text-size)_-_2px)] tw-font-normal"},t.message):Sr.default.createElement("div",{ref:p,className:t.isErrorMessage?"tw-text-error":""})):j.type==="image_url"?Sr.default.createElement("div",{key:$,className:"message-image-content"},Sr.default.createElement("img",{src:j.image_url.url,alt:"User uploaded image",className:"chat-message-image"})):null)):t.sender===Pi&&l?Sr.default.createElement("textarea",{ref:h,value:d,onChange:x,onKeyDown:O,autoFocus:!0,className:"edit-textarea"}):t.sender===Pi?Sr.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-break-words tw-text-[calc(var(--font-text-size)_-_2px)] tw-font-normal"},t.message):Sr.default.createElement("div",{ref:p,className:t.isErrorMessage?"tw-text-error":""});return Sr.default.createElement("div",{className:"tw-my-1 tw-flex tw-w-full tw-flex-col"},Sr.default.createElement("div",{className:_e("tw-group tw-mx-2 tw-flex tw-gap-2 tw-rounded-md tw-p-2",t.sender===Pi&&"tw-border tw-border-solid tw-border-border")},Sr.default.createElement("div",{className:"tw-w-6 tw-shrink-0"},t.sender===Pi?Sr.default.createElement(R3,null):Sr.default.createElement(s1,null)),Sr.default.createElement("div",{className:"tw-flex tw-max-w-full tw-grow tw-flex-col tw-gap-2 tw-overflow-hidden"},!l&&Sr.default.createElement(lPn,{context:t.context}),Sr.default.createElement("div",{className:"message-content"},N()),!r&&Sr.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between"},Sr.default.createElement("div",{className:"tw-text-xs tw-text-faint"},t.timestamp?.display),Sr.default.createElement(F5t,{message:t,onCopy:b,isCopied:s,onInsertIntoEditor:R,onRegenerate:n,onEdit:E,onDelete:i,onShowSources:I,hasSources:!!(t.sources&&t.sources.length>0)})))))},Yke=cPn;ti();var hd=F(X(),1);function Q5t(t,e,{checkForDefaultPrevented:r=!0}={}){return function(o){if(t?.(o),r===!1||!o.defaultPrevented)return e?.(o)}}var tWt=F(X(),1);function eWt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Zke(...t){return e=>{let r=!1,n=t.map(o=>{let i=eWt(o,e);return!r&&typeof i=="function"&&(r=!0),i});if(r)return()=>{for(let o=0;o<n.length;o++){let i=n[o];typeof i=="function"?i():eWt(t[o],null)}}}}function rWt(...t){return tWt.useCallback(Zke(...t),t)}var nWt=F(X(),1),hPn=F(ds(),1);var md=F(X(),1);var gz=F(pt(),1),Qke=md.forwardRef((t,e)=>{let{children:r,...n}=t,o=md.Children.toArray(r),i=o.find(fPn);if(i){let a=i.props.children,s=o.map(u=>u===i?md.Children.count(a)>1?md.Children.only(null):md.isValidElement(a)?a.props.children:null:u);return(0,gz.jsx)(Xke,{...n,ref:e,children:md.isValidElement(a)?md.cloneElement(a,void 0,s):null})}return(0,gz.jsx)(Xke,{...n,ref:e,children:r
2025-07-05 20:48:33 +08:00
.block-interactivity-`.concat(t,` {pointer-events: none;}
.allow-interactivity-`).concat(t,` {pointer-events: all;}
2025-07-12 10:26:56 +08:00
`)},oEn=0,bz=[];function KWt(t){var e=ba.useRef([]),r=ba.useRef([0,0]),n=ba.useRef(),o=ba.useState(oEn++)[0],i=ba.useState(iE)[0],a=ba.useRef(t);ba.useEffect(function(){a.current=t},[t]),ba.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var h=sz([t.lockRef.current],(t.shards||[]).map(WWt),!0).filter(Boolean);return h.forEach(function(b){return b.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),h.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(o))})}}},[t.inert,t.lockRef.current,t.shards]);var s=ba.useCallback(function(h,b){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!a.current.allowPinchZoom;var g=hde(h),y=r.current,S="deltaX"in h?h.deltaX:y[0]-g[0],x="deltaY"in h?h.deltaY:y[1]-g[1],O,P=h.target,E=Math.abs(S)>Math.abs(x)?"h":"v";if("touches"in h&&E==="h"&&P.type==="range")return!1;var A=S$e(E,P);if(!A)return!0;if(A?O=E:(O=E==="v"?"h":"v",A=S$e(E,P)),!A)return!1;if(!n.current&&"changedTouches"in h&&(S||x)&&(n.current=O),!O)return!0;var I=n.current||O;return HWt(I,b,h,I==="h"?S:x,!0)},[]),u=ba.useCallback(function(h){var b=h;if(!(!bz.length||bz[bz.length-1]!==i)){var g="deltaY"in b?VWt(b):hde(b),y=e.current.filter(function(O){return O.name===b.type&&(O.target===b.target||b.target===O.shadowParent)&&rEn(O.delta,g)})[0];if(y&&y.should){b.cancelable&&b.preventDefault();return}if(!y){var S=(a.current.shards||[]).map(WWt).filter(Boolean).filter(function(O){return O.contains(b.target)}),x=S.length>0?s(b,S[0]):!a.current.noIsolation;x&&b.cancelable&&b.preventDefault()}}},[]),l=ba.useCallback(function(h,b,g,y){var S={name:h,delta:b,target:g,should:y,shadowParent:iEn(g)};e.current.push(S),setTimeout(function(){e.current=e.current.filter(function(x){return x!==S})},1)},[]),c=ba.useCallback(function(h){r.current=hde(h),n.current=void 0},[]),d=ba.useCallback(function(h){l(h.type,VWt(h),h.target,s(h,t.lockRef.current))},[]),f=ba.useCallback(function(h){l(h.type,hde(h),h.target,s(h,t.lockRef.current))},[]);ba.useEffect(function(){return bz.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,nL),document.addEventListener("touchmove",u,nL),document.addEventListener("touchstart",c,nL),function(){bz=bz.filter(function(h){return h!==i}),document.removeEventListener("wheel",u,nL),document.removeEventListener("touchmove",u,nL),document.removeEventListener("touchstart",c,nL)}},[]);var p=t.removeScrollBar,m=t.inert;return ba.createElement(ba.Fragment,null,m?ba.createElement(i,{styles:nEn(o)}):null,p?ba.createElement(KD,{gapMode:t.gapMode}):null)}function iEn(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var GWt=WD(mde,KWt);var JWt=gde.forwardRef(function(t,e){return gde.createElement(c9,yi({},t,{ref:e,sideCar:GWt}))});JWt.classNames=c9.classNames;var x$e=JWt;var bl=F(pt(),1),C$e="Popover",[YWt,Zpi]=Yi(C$e,[g$e]),f9=g$e(),[aEn,EM]=YWt(C$e),ZWt=t=>{let{__scopePopover:e,children:r,open:n,defaultOpen:o,onOpenChange:i,modal:a=!1}=t,s=f9(e),u=Da.useRef(null),[l,c]=Da.useState(!1),[d=!1,f]=ud({prop:n,defaultProp:o,onChange:i});return(0,bl.jsx)(LWt,{...s,children:(0,bl.jsx)(aEn,{scope:e,contentId:hl(),triggerRef:u,open:d,onOpenChange:f,onOpenToggle:Da.useCallback(()=>f(p=>!p),[f]),hasCustomAnchor:l,onCustomAnchorAdd:Da.useCallback(()=>c(!0),[]),onCustomAnchorRemove:Da.useCallback(()=>c(!1),[]),modal:a,children:r})})};ZWt.displayName=C$e;var XWt="PopoverAnchor",sEn=Da.forwardRef((t,e)=>{let{__scopePopover:r,...n}=t,o=EM(XWt,r),i=f9(r),{onCustomAnchorAdd:a,onCustomAnchorRemove:s}=o;return Da.useEffect(()=>(a(),()=>s()),[a,s]),(0,bl.jsx)(b$e,{...i,...n,ref:e})});sEn.displayName=XWt;var QWt="PopoverTrigger",e9t=Da.forwardRef((t,e)=>{let{__scopePopover:r,...n}=t,o=EM(QWt,r),i=f9(r),a=Ab(e,o.triggerRef),s=(0,bl.jsx)(op.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":a9t(o.open),...n,ref:a,onClick:tC(t.
2025-07-05 20:48:33 +08:00
`).map(y=>{if(!y.trim())return y;try{return new URL(y.trim()),y}catch{return y}});p("contextSource.webUrls",g.join(`
`))},placeholder:"Enter web URLs, one per line",className:"tw-min-h-20 tw-w-full"})),Kt.default.createElement(Yn,{label:"YouTube URLs"},Kt.default.createElement(yE,{value:u.contextSource?.youtubeUrls,onChange:h=>{let g=h.target.value.split(`
`).map(y=>{if(!y.trim())return y;try{let S=new URL(y.trim());return S.hostname.includes("youtube.com")||S.hostname.includes("youtu.be"),y}catch{return y}});p("contextSource.youtubeUrls",g.join(`
2025-07-12 10:26:56 +08:00
`))},placeholder:"Enter YouTube URLs, one per line",className:"tw-min-h-20 tw-w-full"})))),Kt.default.createElement("div",{className:"tw-mt-4 tw-flex tw-items-center tw-justify-end tw-gap-2"},Kt.default.createElement(ge,{variant:"ghost",onClick:r,disabled:o},"Cancel"),Kt.default.createElement(ge,{onClick:m,disabled:o||!f()},o?"Saving...":"Save")))}var E9=class extends Bz.Modal{constructor(r,n,o){super(r);this.onSave=n;this.initialProject=o}onOpen(){let{contentEl:r}=this;this.root=(0,eGt.createRoot)(r);let n=async i=>{await this.onSave(i),this.close()},o=()=>{this.close()};this.root.render(Kt.default.createElement(cAn,{initialProject:this.initialProject,onSave:n,onCancel:o}))}onClose(){this.root.unmount()}};ti();var ji=F(X());var ct=F(X(),1),RBe=F(ds(),1);var ns=F(X(),1);var dBe=F(pt(),1),dAn="DismissableLayer",cBe="dismissableLayer.update",fAn="dismissableLayer.pointerDownOutside",pAn="dismissableLayer.focusOutside",tGt,nGt=ns.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),fBe=ns.forwardRef((t,e)=>{let{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:n,onPointerDownOutside:o,onFocusOutside:i,onInteractOutside:a,onDismiss:s,...u}=t,l=ns.useContext(nGt),[c,d]=ns.useState(null),f=c?.ownerDocument??globalThis?.document,[,p]=ns.useState({}),m=Ri(e,E=>d(E)),h=Array.from(l.layers),[b]=[...l.layersWithOutsidePointerEventsDisabled].slice(-1),g=h.indexOf(b),y=c?h.indexOf(c):-1,S=l.layersWithOutsidePointerEventsDisabled.size>0,x=y>=g,O=gAn(E=>{let A=E.target,I=[...l.branches].some(R=>R.contains(A));!x||I||(o?.(E),a?.(E),E.defaultPrevented||s?.())},f),P=yAn(E=>{let A=E.target;[...l.branches].some(R=>R.contains(A))||(i?.(E),a?.(E),E.defaultPrevented||s?.())},f);return oM(E=>{y===l.layers.size-1&&(n?.(E),!E.defaultPrevented&&s&&(E.preventDefault(),s()))},f),ns.useEffect(()=>{if(c)return r&&(l.layersWithOutsidePointerEventsDisabled.size===0&&(tGt=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),l.layersWithOutsidePointerEventsDisabled.add(c)),l.layers.add(c),rGt(),()=>{r&&l.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=tGt)}},[c,f,r,l]),ns.useEffect(()=>()=>{c&&(l.layers.delete(c),l.layersWithOutsidePointerEventsDisabled.delete(c),rGt())},[c,l]),ns.useEffect(()=>{let E=()=>p({});return document.addEventListener(cBe,E),()=>document.removeEventListener(cBe,E)},[]),(0,dBe.jsx)(ho.div,{...u,ref:m,style:{pointerEvents:S?x?"auto":"none":void 0,...t.style},onFocusCapture:xi(t.onFocusCapture,P.onFocusCapture),onBlurCapture:xi(t.onBlurCapture,P.onBlurCapture),onPointerDownCapture:xi(t.onPointerDownCapture,O.onPointerDownCapture)})});fBe.displayName=dAn;var mAn="DismissableLayerBranch",hAn=ns.forwardRef((t,e)=>{let r=ns.useContext(nGt),n=ns.useRef(null),o=Ri(e,n);return ns.useEffect(()=>{let i=n.current;if(i)return r.branches.add(i),()=>{r.branches.delete(i)}},[r.branches]),(0,dBe.jsx)(ho.div,{...t,ref:o})});hAn.displayName=mAn;function gAn(t,e=globalThis?.document){let r=Ur(t),n=ns.useRef(!1),o=ns.useRef(()=>{});return ns.useEffect(()=>{let i=s=>{if(s.target&&!n.current){let l=function(){oGt(fAn,r,c,{discrete:!0})};var u=l;let c={originalEvent:s};s.pointerType==="touch"?(e.removeEventListener("click",o.current),o.current=l,e.addEventListener("click",o.current,{once:!0})):l()}else e.removeEventListener("click",o.current);n.current=!1},a=window.setTimeout(()=>{e.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(a),e.removeEventListener("pointerdown",i),e.removeEventListener("click",o.current)}},[e,r]),{onPointerDownCapture:()=>n.current=!0}}function yAn(t,e=globalThis?.document){let r=Ur(t),n=ns.useRef(!1);return ns.useEffect(()=>{let o=i=>{i.target&&!n.current&&oGt(pAn,r,{originalEvent:i},{discrete:!1})};return e.addEventListener("focusin",o),()=>e.removeEventListener("focusin",o)},[e,r]),{onFocusCapture:()=>n.current=!0,onBlurCapture:()=>n.current=!1}}function rGt(){let t=new CustomEvent(cBe);document.dispatchEvent(t)}function oGt(t,e,r,{discrete:n}){let o=r.originalEvent.target,i=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:r}
2025-07-05 20:48:33 +08:00
.block-interactivity-`.concat(t,` {pointer-events: none;}
.allow-interactivity-`).concat(t,` {pointer-events: all;}
2025-07-12 10:26:56 +08:00
`)},JAn=0,Uz=[];function $Gt(t){var e=_a.useRef([]),r=_a.useRef([0,0]),n=_a.useRef(),o=_a.useState(JAn++)[0],i=_a.useState(iE)[0],a=_a.useRef(t);_a.useEffect(function(){a.current=t},[t]),_a.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var h=sz([t.lockRef.current],(t.shards||[]).map(kGt),!0).filter(Boolean);return h.forEach(function(b){return b.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),h.forEach(function(b){return b.classList.remove("allow-interactivity-".concat(o))})}}},[t.inert,t.lockRef.current,t.shards]);var s=_a.useCallback(function(h,b){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!a.current.allowPinchZoom;var g=efe(h),y=r.current,S="deltaX"in h?h.deltaX:y[0]-g[0],x="deltaY"in h?h.deltaY:y[1]-g[1],O,P=h.target,E=Math.abs(S)>Math.abs(x)?"h":"v";if("touches"in h&&E==="h"&&P.type==="range")return!1;var A=PBe(E,P);if(!A)return!0;if(A?O=E:(O=E==="v"?"h":"v",A=PBe(E,P)),!A)return!1;if(!n.current&&"changedTouches"in h&&(S||x)&&(n.current=O),!O)return!0;var I=n.current||O;return LGt(I,b,h,I==="h"?S:x,!0)},[]),u=_a.useCallback(function(h){var b=h;if(!(!Uz.length||Uz[Uz.length-1]!==i)){var g="deltaY"in b?FGt(b):efe(b),y=e.current.filter(function(O){return O.name===b.type&&(O.target===b.target||b.target===O.shadowParent)&&KAn(O.delta,g)})[0];if(y&&y.should){b.cancelable&&b.preventDefault();return}if(!y){var S=(a.current.shards||[]).map(kGt).filter(Boolean).filter(function(O){return O.contains(b.target)}),x=S.length>0?s(b,S[0]):!a.current.noIsolation;x&&b.cancelable&&b.preventDefault()}}},[]),l=_a.useCallback(function(h,b,g,y){var S={name:h,delta:b,target:g,should:y,shadowParent:YAn(g)};e.current.push(S),setTimeout(function(){e.current=e.current.filter(function(x){return x!==S})},1)},[]),c=_a.useCallback(function(h){r.current=efe(h),n.current=void 0},[]),d=_a.useCallback(function(h){l(h.type,FGt(h),h.target,s(h,t.lockRef.current))},[]),f=_a.useCallback(function(h){l(h.type,efe(h),h.target,s(h,t.lockRef.current))},[]);_a.useEffect(function(){return Uz.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,cL),document.addEventListener("touchmove",u,cL),document.addEventListener("touchstart",c,cL),function(){Uz=Uz.filter(function(h){return h!==i}),document.removeEventListener("wheel",u,cL),document.removeEventListener("touchmove",u,cL),document.removeEventListener("touchstart",c,cL)}},[]);var p=t.removeScrollBar,m=t.inert;return _a.createElement(_a.Fragment,null,m?_a.createElement(i,{styles:GAn(o)}):null,p?_a.createElement(KD,{gapMode:t.gapMode}):null)}function YAn(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var BGt=WD(Qde,$Gt);var qGt=tfe.forwardRef(function(t,e){return tfe.createElement(T9,yi({},t,{ref:e,sideCar:BGt}))});qGt.classNames=T9.classNames;var I9=qGt;var lr=F(pt(),1),ZAn=[" ","Enter","ArrowUp","ArrowDown"],XAn=[" ","Enter"],R9="Select",[nfe,ofe,QAn]=Yde(R9),[zz,Abi]=Yi(R9,[QAn,bBe]),ife=bBe(),[eIn,LM]=zz(R9),[tIn,rIn]=zz(R9),UGt=t=>{let{__scopeSelect:e,children:r,open:n,defaultOpen:o,onOpenChange:i,value:a,defaultValue:s,onValueChange:u,dir:l,name:c,autoComplete:d,disabled:f,required:p,form:m}=t,h=ife(e),[b,g]=ct.useState(null),[y,S]=ct.useState(null),[x,O]=ct.useState(!1),P=nM(l),[E=!1,A]=ud({prop:n,defaultProp:o,onChange:i}),[I,R]=ud({prop:a,defaultProp:s,onChange:u}),N=ct.useRef(null),j=b?m||!!b.closest("form"):!0,[$,k]=ct.useState(new Set),z=Array.from($).map(V=>V.props.value).join(";");return(0,lr.jsx)(OGt,{...h,children:(0,lr.jsxs)(eIn,{required:p,scope:e,trigger:b,onTriggerChange:g,valueNode:y,onValueNodeChange:S,valueNodeHasChildren:x,onValueNodeHasChildrenChange:O,contentId:hl(),value:I,onValueChange:R,open:E,onOpenChange:A,dir:P,triggerPointerDownPosRef:N,disabled:f,children:[(0,lr.jsx)(nfe.Provider,{scope:e,children:(0,lr.jsx)(tIn,{scope:t.__scopeSelect,onNativeOptionAdd:ct.useCallback(V=>{k(Q=>new Set(Q).add(V))},[]),onNativeOption
2025-07-05 20:48:33 +08:00
<output_format>
`+ir+`
2025-07-12 10:26:56 +08:00
</output_format>`);let{processedPrompt:ea,includedFiles:ta}=await fce(Je||"","",U.vault,U.workspace.getActiveFile()),xc=f==="copilot_plus"?await q.processUrls(h||""):{urlContext:"",imageUrls:[]},Cd=new Set(ta.map(_f=>_f.path)),qi=await K.processContextNotes(Cd,o,U.vault,se,I,ce,f),lp=K.processSelectedTextContexts(),yf=ea+xc.urlContext+qi+lp,bf=h;te&&(bf+=" "+te.join(`
`));let xn={message:yf,originalMessage:bf,sender:Pi,isVisible:!1,timestamp:Pe,content:oe,context:{notes:se,urls:f==="copilot_plus"?[...et||[],...xc.imageUrls]:et||[],selectedTextContexts:z}};l(xn),h&&n(h),a.autosaveChat&&Y(),await UBe(xn,e,l,m,y,{debug:a.debug,updateLoadingMessage:P}),a.autosaveChat&&Y(),x(!1),P(t_.DEFAULT)},Y=(0,xr.useCallback)(async()=>{if(!U){console.error("App instance is not available.");return}let te=t.getMessages().filter(Pe=>Pe.isVisible);if(te.length===0){new pm.Notice("No messages to save.");return}let et=te[0].timestamp?.epoch||Date.now(),Re=te.map(Pe=>`**${Pe.sender}**: ${Pe.message}
2025-07-05 20:48:33 +08:00
[Timestamp: ${Pe.timestamp?.display}]`).join(`
`);try{U.vault.getAbstractFileByPath(a.defaultSaveFolder)||await U.vault.createFolder(a.defaultSaveFolder);let{fileName:oe}=Vl(new Date(et)),se=te.find(qi=>qi.sender===Pi),ce=se?se.message.split(/\s+/).slice(0,10).join(" ").replace(/[\\/:*?"<>|]/g,"").trim():"Untitled Chat",Ce=a.defaultConversationNoteName||"{$date}_{$time}__{$topic}";Ce=Ce.replace("{$topic}",ce.slice(0,100).replace(/\s+/g,"_")).replace("{$date}",oe.split("_")[0]).replace("{$time}",oe.split("_")[1]);let Je=Ce.replace(/[\\/:*?"<>|]/g,"_"),ir=Mc(),ea=ir?`${ir.id}__`:"",ta=`${a.defaultSaveFolder}/${ea}${Je}.md`,xc=`---
epoch: ${et}
modelKey: ${d}
${ir?`projectId: ${ir.id}`:""}
${ir?`projectName: ${ir.name}`:""}
tags:
- ${a.defaultConversationTag}
${ir?` - project-${ir.name}`:""}
---
2025-07-12 10:26:56 +08:00
${Re}`,Cd=U.vault.getAbstractFileByPath(ta);Cd instanceof pm.TFile?await U.vault.modify(Cd,xc):(await U.vault.create(ta,xc),new pm.Notice(`Chat saved as note: ${ta}`))}catch(Pe){console.error("Error saving chat as note:",ei(Pe)),new pm.Notice("Failed to save chat as note. Check console for details.")}},[U,t,d,a.defaultConversationTag,a.defaultSaveFolder,a.defaultConversationNoteName]),ae=(0,xr.useCallback)(te=>{g&&(a.debug&&console.log(`stopping generation..., reason: ${te}`),g.abort(te),x(!1),P(t_.DEFAULT))},[g,a.debug]),Oe=(0,xr.useCallback)(async te=>{let et=te-1;if(et<0||u[et].sender!==Pi){new pm.Notice("Cannot regenerate the first message or a user message.");return}let Re=u[et],Pe=u.slice(0,te);c(),Pe.forEach(l),e.memoryManager.clearChatMemory();for(let oe=0;oe<Pe.length;oe+=2){let se=Pe[oe],ce=Pe[oe+1];se&&ce&&await e.memoryManager.getMemory().saveContext({input:se.message},{output:ce.message})}x(!0);try{await e.runChain(Re,new AbortController,m,l,{debug:a.debug})&&a.debug&&console.log("Message regenerated successfully")}catch(oe){console.error("Error regenerating message:",oe),new pm.Notice("Failed to regenerate message. Please try again.")}finally{x(!1)}a.autosaveChat&&Y()},[l,e,u,c,a.debug,a.autosaveChat,Y]),le=(0,xr.useCallback)(async(te,et)=>{let Re=u[te].message;if(Re===et)return;let Pe=[...u];for(let oe=te;oe<Pe.length;oe++)Pe[oe].originalMessage===Re&&(Pe[oe].message=et,Pe[oe].originalMessage=et,Pe[oe].context={notes:[],urls:[]});c(),Pe.forEach(l),await vN(Pe,e.memoryManager),Pe[te].sender===Pi&&te<Pe.length-1&&Oe(te+1),a.autosaveChat&&Y()},[l,e.memoryManager,u,c,Oe,a.autosaveChat,Y]);(0,xr.useEffect)(((te,et)=>()=>{let Re=ue().debug,Pe=async oe=>{let ce={message:await et(oe.detail.selectedText,oe.detail.eventSubtype),sender:Pi,isVisible:Re,timestamp:Vl(new Date)};Re&&l(ce),x(!0),await UBe(ce,e,l,m,y,{debug:Re,ignoreSystemMessage:!0}),x(!1)};return s?.addEventListener(te,Pe),()=>{s?.removeEventListener(te,Pe)}})(Br.APPLY_ADHOC_PROMPT,async(te,et)=>et?(await fce(et,te,U.vault,U.workspace.getActiveFile())).processedPrompt:te),[]),(0,xr.useEffect)(()=>{r&&r(Y)},[r,Y]);let ze=(0,xr.useCallback)(async te=>{let et=[...u];et.splice(te,1),c(),et.forEach(l),await vN(et,e.memoryManager)},[l,e.memoryManager,u,c]),rt=(0,xr.useCallback)(te=>{let et=a.projectList||[];if(et.findIndex(se=>se.name===te.name)>=0)throw new Error(`Project "${te.name}" already exists, please use a different name`);let Pe=[...et,te];return dt("projectList",Pe),Mc()?.id===te.id?Xce().then(()=>{new pm.Notice(`${te.name} added and context loaded`)}).catch(se=>{console.error("Error loading project context:",se),new pm.Notice(`${te.name} added but context loading failed`)}):new pm.Notice(`${te.name} added successfully`),!0},[a.projectList]),cr=(0,xr.useCallback)((te,et)=>{let Re=a.projectList||[];if(!Re.find(ce=>ce.name===te.name))throw new Error(`Project "${te.name}" does not exist`);let oe=Re.map(ce=>ce.name===te.name?et:ce);return dt("projectList",oe),Mc()?.id===te.id?(zR(et),Xce().then(()=>{new pm.Notice(`${te.name} updated and context reloaded`)}).catch(ce=>{console.error("Error reloading project context:",ce),new pm.Notice(`${te.name} updated but context reload failed`)})):new pm.Notice(`${te.name} updated successfully`),!0},[a.projectList]),Sn=(0,xr.useCallback)(te=>{b(et=>`${et} ${te} `)},[]),je=(0,xr.useCallback)(te=>{i8e(te)},[]),mt=(0,xr.useCallback)(async()=>{ae("new-chat"),await i.handleNewChat(),m(""),A([]),a8e(),J!=="copilot_plus"?R(!1):R(a.includeActiveNoteAsContext)},[ae,i,a.includeActiveNoteAsContext,J]),ht=(0,xr.useCallback)(()=>{i.loadCopilotChatHistory()},[i]);(0,xr.useEffect)(()=>{let te=et=>{let Re=et.detail?.reason||"new-chat";ae(Re)};return s?.addEventListener(Dh.ABORT_STREAM,te),()=>{s?.removeEventListener(Dh.ABORT_STREAM,te)}},[s,ae]),(0,xr.useEffect)(()=>{a.includeActiveNoteAsContext!==void 0&&(J==="copilot_plus"?R(a.includeActiveNoteAsContext):R(!1))},[a.includeActiveNoteAsContext,J]);let ft=()=>xr.default.createElement(xr.default.Fragment,null,xr.default.createElement("div",{className:"tw-flex tw-size-full tw-flex-col
2025-07-05 20:48:33 +08:00
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.
2025-07-12 10:26:56 +08:00
`},qIn={onDragStart(t){let{active:e}=t;return"Picked up draggable item "+e.id+"."},onDragOver(t){let{active:e,over:r}=t;return r?"Draggable item "+e.id+" was moved over droppable area "+r.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(t){let{active:e,over:r}=t;return r?"Draggable item "+e.id+" was dropped over droppable area "+r.id:"Draggable item "+e.id+" was dropped."},onDragCancel(t){let{active:e}=t;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function UIn(t){let{announcements:e=qIn,container:r,hiddenTextDescribedById:n,screenReaderInstructions:o=BIn}=t,{announce:i,announcement:a}=r7t(),s=bL("DndLiveRegion"),[u,l]=(0,Ae.useState)(!1);if((0,Ae.useEffect)(()=>{l(!0)},[]),kIn((0,Ae.useMemo)(()=>({onDragStart(d){let{active:f}=d;i(e.onDragStart({active:f}))},onDragMove(d){let{active:f,over:p}=d;e.onDragMove&&i(e.onDragMove({active:f,over:p}))},onDragOver(d){let{active:f,over:p}=d;i(e.onDragOver({active:f,over:p}))},onDragEnd(d){let{active:f,over:p}=d;i(e.onDragEnd({active:f,over:p}))},onDragCancel(d){let{active:f,over:p}=d;i(e.onDragCancel({active:f,over:p}))}}),[i,e])),!u)return null;let c=Ae.default.createElement(Ae.default.Fragment,null,Ae.default.createElement(e7t,{id:n,value:o.draggable}),Ae.default.createElement(t7t,{id:s,announcement:a}));return r?(0,SL.createPortal)(c,r):c}var Ul;(function(t){t.DragStart="dragStart",t.DragMove="dragMove",t.DragEnd="dragEnd",t.DragCancel="dragCancel",t.DragOver="dragOver",t.RegisterDroppable="registerDroppable",t.SetDroppableDisabled="setDroppableDisabled",t.UnregisterDroppable="unregisterDroppable"})(Ul||(Ul={}));function mfe(){}function Xz(t,e){return(0,Ae.useMemo)(()=>({sensor:t,options:e??{}}),[t,e])}function gfe(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return(0,Ae.useMemo)(()=>[...e].filter(n=>n!=null),[...e])}var jb=Object.freeze({x:0,y:0});function g7t(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}function y7t(t,e){let{data:{value:r}}=t,{data:{value:n}}=e;return r-n}function zIn(t,e){let{data:{value:r}}=t,{data:{value:n}}=e;return n-r}function n7t(t){let{left:e,top:r,height:n,width:o}=t;return[{x:e,y:r},{x:e+o,y:r},{x:e,y:r+n},{x:e+o,y:r+n}]}function sqe(t,e){if(!t||t.length===0)return null;let[r]=t;return e?r[e]:r}function o7t(t,e,r){return e===void 0&&(e=t.left),r===void 0&&(r=t.top),{x:e+t.width*.5,y:r+t.height*.5}}var H9=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=o7t(e,e.left,e.top),i=[];for(let a of n){let{id:s}=a,u=r.get(s);if(u){let l=g7t(o7t(u),o);i.push({id:s,data:{droppableContainer:a,value:l}})}}return i.sort(y7t)},b7t=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=n7t(e),i=[];for(let a of n){let{id:s}=a,u=r.get(s);if(u){let l=n7t(u),c=o.reduce((f,p,m)=>f+g7t(l[m],p),0),d=Number((c/4).toFixed(4));i.push({id:s,data:{droppableContainer:a,value:d}})}}return i.sort(y7t)};function HIn(t,e){let r=Math.max(e.top,t.top),n=Math.max(e.left,t.left),o=Math.min(e.left+e.width,t.left+t.width),i=Math.min(e.top+e.height,t.top+t.height),a=o-n,s=i-r;if(n<o&&r<i){let u=e.width*e.height,l=t.width*t.height,c=a*s,d=c/(u+l-c);return Number(d.toFixed(4))}return 0}var VIn=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=[];for(let i of n){let{id:a}=i,s=r.get(a);if(s){let u=HIn(s,e);u>0&&o.push({id:a,data:{droppableContainer:i,value:u}})}}return o.sort(zIn)};function WIn(t,e,r){return{...t,scaleX:e&&r?e.width/r.width:1,scaleY:e&&r?e.height/r.height:1}}function _7t(t,e){return t&&e?{x:t.left-e.left,y:t.top-e.top}:jb}function KIn(t){return function(r){for(var n=arguments.length,o=new Array(n>1?n-1:0),i=1;i<n;i++)o[i-1]=arguments[i];return o.reduce((a,s)=>({...a,top:a.top+t*s.y,bottom:a.bottom+t*s.y,left:a.left+t*s.x,right:a.right+t*s.x}),{...r})}}var GIn=KIn(1);function JIn(t){if(t.startsWith("matrix3d(")){let e=t.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(t.startsWith("matrix(")){let e=t.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}funct
2025-07-05 20:48:33 +08:00
If you want to hide the \`${e.titleName}\`, you can wrap it with our VisuallyHidden component.
2025-07-12 10:26:56 +08:00
For more information, see https://radix-ui.com/primitives/docs/components/${e.docsSlug}`;return Qi.useEffect(()=>{t&&(document.getElementById(t)||console.error(r))},[r,t]),null},IRn="DialogDescriptionWarning",MRn=({contentRef:t,descriptionId:e})=>{let n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${wYt(IRn).contentName}}.`;return Qi.useEffect(()=>{let o=t.current?.getAttribute("aria-describedby");e&&o&&(document.getElementById(e)||console.warn(n))},[n,t,e]),null},SYt=sYt,xYt=lYt,CYt=dYt,Sqe=fYt,xqe=pYt,Cqe=hYt,Oqe=yYt,OYt=_Yt;bn();Tn();var Tfe=SYt,PYt=xYt,jRn=CYt;var EYt=xd.forwardRef(({className:t,...e},r)=>xd.createElement(Sqe,{ref:r,className:_e("tw-fixed tw-inset-0 tw-z-modal data-[state=open]:tw-animate-in data-[state=closed]:tw-animate-out data-[state=closed]:tw-fade-out-0 data-[state=open]:tw-fade-in-0","tw-bg-overlay/50",t),...e}));EYt.displayName=Sqe.displayName;var X9=xd.forwardRef(({className:t,children:e,container:r,...n},o)=>xd.createElement(jRn,{container:r},xd.createElement(EYt,null),xd.createElement(xqe,{ref:o,className:_e("tw-fixed tw-left-1/2 tw-top-1/2 tw-z-modal tw-grid tw-w-full tw-max-w-lg -tw-translate-x-1/2 -tw-translate-y-1/2 tw-gap-4 tw-border tw-bg-primary tw-p-6 tw-shadow-lg tw-duration-200 data-[state=open]:tw-animate-in data-[state=closed]:tw-animate-out data-[state=closed]:tw-fade-out-0 data-[state=open]:tw-fade-in-0 data-[state=closed]:tw-zoom-out-95 data-[state=open]:tw-zoom-in-95 data-[state=closed]:tw-slide-out-to-left-1/2 data-[state=closed]:tw-slide-out-to-top-[48%] data-[state=open]:tw-slide-in-from-left-1/2 data-[state=open]:tw-slide-in-from-top-[48%] sm:tw-rounded-lg",t),...n},e,xd.createElement(OYt,{className:"clickable-icon tw-absolute tw-right-4 tw-top-4 tw-border-none tw-bg-transparent tw-text-faint tw-outline-none hover:tw-bg-transparent hover:tw-bg-opacity-100 hover:tw-text-normal focus-visible:tw-text-normal focus-visible:tw-outline-none focus-visible:tw-ring-0"},xd.createElement(Vi,{className:"tw-size-4"}),xd.createElement("span",{className:"tw-sr-only"},"Close")))));X9.displayName=xqe.displayName;var Q9=({className:t,...e})=>xd.createElement("div",{className:_e("tw-flex tw-flex-col tw-space-y-0.5 tw-text-center sm:tw-text-left",t),...e});Q9.displayName="DialogHeader";var NRn=({className:t,...e})=>xd.createElement("div",{className:_e("tw-flex tw-flex-col-reverse sm:tw-flex-row sm:tw-justify-end sm:tw-space-x-2",t),...e});NRn.displayName="DialogFooter";var eK=xd.forwardRef(({className:t,...e},r)=>xd.createElement(Cqe,{ref:r,className:_e("tw-mt-0 tw-text-lg tw-font-semibold tw-leading-none tw-tracking-tight",t),...e}));eK.displayName=Cqe.displayName;var tK=xd.forwardRef(({className:t,...e},r)=>xd.createElement(Oqe,{ref:r,className:_e("tw-text-sm tw-text-muted",t),...e}));tK.displayName=Oqe.displayName;yn();function hn(t){let{title:e,description:r,className:n,disabled:o}=t,{modalContainer:i}=Wz(),a="onChange"in t?t.onChange:void 0,s=(0,va.useMemo)(()=>{if(a)return rJ(l=>{a(l)},1e3)},[a]),u=()=>{switch(t.type){case"text":case"number":return va.default.createElement(mo,{type:t.type,defaultValue:t.value,onChange:l=>{s?.(l.target.value)},placeholder:t.placeholder,disabled:o,className:"tw-w-full sm:tw-w-[200px]"});case"password":return va.default.createElement(aC,{value:t.value!==void 0?String(t.value):void 0,onChange:l=>{s?.(l)},placeholder:t.placeholder,disabled:o,className:"tw-w-full sm:tw-w-[200px]"});case"textarea":return va.default.createElement(yE,{defaultValue:t.value,onChange:l=>{s?.(l.target.value)},placeholder:t.placeholder,rows:t.rows||3,disabled:o,className:"tw-min-h-[80px] tw-w-full sm:tw-w-[300px]"});case"switch":return va.default.createElement(dz,{checked:t.checked,onCheckedChange:t.onCheckedChange,disabled:o});case"select":return va.default.createElement("div",{className:"tw-group tw-relative tw-w-full sm:tw-w-[200px]"},va.default.createElement("select",{value:t.value?.toString(),onChange:l=>t.onChange?.(l.target.value),disabled:o,className:_e("tw-w-full tw-appearance-none","tw-flex tw-h-9 tw-rounded-md tw-border tw-border-solid tw-b
2025-07-05 20:48:33 +08:00
Original name: ${a.title}
2025-07-12 10:26:56 +08:00
${a.content}`}):e.push(a)}await lm.getInstance().updateCommands([...n.map(a=>({...a,showInSlashMenu:!0})),...e]);let i=`We have upgraded your commands to the new format. They are now also stored as notes in ${QI()}.`;r.length>0&&(await DRn(r),i+=`
2025-07-05 20:48:33 +08:00
2025-07-12 10:26:56 +08:00
We found ${r.length} unsupported commands. They are saved in ${QI()}/unsupported. To fix them, please resolve the errors and move the note file out of the unsupported folder.`),dt("inlineEditCommands",[]),new sd(app,()=>{},i,"\u{1F680} New Copilot Custom Commands","OK","").open()}async function Pqe(){let t=Jx(),e=I3t.filter(n=>!t.some(o=>o.title===n.title)),r=[...t,...e];lm.getInstance().updateCommands(r)}async function AYt(){if(ue().suggestedDefaultCommands)return;Jx().length===0&&(new sd(app,()=>{Pqe()},"Would you like to add Copilot recommended commands in your custom prompts folder? These commands will be available through the right-click context menu and slash commands in chat.","Welcome to Copilot","Confirm","Skip").open(),dt("suggestedDefaultCommands",!0))}var LRn=({command:t,commands:e,onUpdate:r,onRemove:n})=>{let{attributes:o,listeners:i,setNodeRef:a,transform:s,transition:u,isDragging:l}=J9({id:t.title}),c={transform:Rb.Transform.toString(s),transition:u},d=()=>{n(t)};return it.default.createElement(BM,{ref:a,style:c,className:_e("tw-transition-colors",l&&"tw-relative tw-z-[100] tw-cursor-grabbing tw-shadow-lg tw-backdrop-blur-sm tw-border-accent/50")},it.default.createElement(gf,{className:"tw-w-10"},it.default.createElement("div",{...o,...i,className:"tw-flex tw-cursor-grab tw-items-center tw-justify-center"},it.default.createElement(d_,{className:"tw-size-4"}))),it.default.createElement(gf,null,t.title),it.default.createElement(gf,{className:"tw-text-center"},it.default.createElement(wd,{checked:t.showInContextMenu,onCheckedChange:f=>{r({...t,showInContextMenu:f===!0},t.title)},className:"tw-mx-auto"})),it.default.createElement(gf,{className:"tw-text-center"},it.default.createElement(wd,{checked:t.showInSlashMenu,onCheckedChange:f=>r({...t,showInSlashMenu:f===!0},t.title),className:"tw-mx-auto"})),it.default.createElement(gf,{className:"tw-text-center"},it.default.createElement("div",{className:"tw-flex tw-justify-center tw-space-x-1"},it.default.createElement(ge,{variant:"ghost",size:"icon",onClick:()=>{new Ofe(app,e,t,async p=>{await r(p,t.title)}).open()}},it.default.createElement(p_,{className:"tw-size-4"})),it.default.createElement(ge,{variant:"ghost",size:"icon",onClick:()=>{new sd(app,d,`Are you sure you want to delete the command "${t.title}"? This will permanently remove the command file and cannot be undone.`,"Delete Command","Delete","Cancel").open()}},it.default.createElement(Rm,{className:"tw-size-4"})))))},IYt=()=>{let t=M3t(),e=(0,it.useMemo)(()=>IW([...t]),[t]),[r,n]=it.default.useState(""),o=Rn(),i=gfe(Xz(VM,{activationConstraint:{distance:8}}),Xz(HM,{coordinateGetter:xfe})),a=JU(r,e),s=!a&&r.trim()!=="",u=async()=>{if(s)try{await lm.getInstance().createCommand(r.trim(),""),n(""),new rK.Notice(`Command "${r.trim()}" created successfully!`)}catch(p){console.error("Failed to create command:",p),new rK.Notice("Failed to create command. Please try again.")}},l=async(p,m)=>{await lm.getInstance().updateCommand(p,m)},c=async p=>{try{await lm.getInstance().deleteCommand(p),new rK.Notice(`Command "${p.title}" deleted successfully!`)}catch(m){throw console.error("Failed to delete command:",m),new rK.Notice("Failed to delete command. Please try again."),m}},d=async p=>{let{active:m,over:h}=p;if(!h||m.id===h.id)return;let b=e.findIndex(x=>x.title===m.id),g=e.findIndex(x=>x.title===h.id);if(b===-1||g===-1)return;let y=[...e],[S]=y.splice(b,1);y.splice(g,0,S);for(let x=0;x<y.length;x++)y[x]={...y[x],order:x*10};await lm.getInstance().updateCommands(y)},f=Y9();return it.default.createElement("div",{className:"tw-space-y-4"},it.default.createElement("section",null,it.default.createElement("div",{className:"tw-mb-4 tw-flex tw-flex-col tw-gap-2"},it.default.createElement("div",{className:"tw-text-xl tw-font-bold"},"Custom Commands"),it.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Custom commands are preset prompts that you can trigger in the editor by right-clicking and selecting them from the context menu or by using a ",it.default.createElement("code",null,"/")," command in the cha
2025-07-05 20:48:33 +08:00
detail: `+q)}return B}finally{clearTimeout(D)}},k;try{k=await $(!1)}catch(Q){console.log("First fetch attempt failed, trying with safeFetch...");try{k=await $(!0)}catch(J){let D=`
without CORS Error: `+ei(Q)+`
2025-07-12 10:26:56 +08:00
with CORS Error: `+ei(J);throw new Error(D)}}let z=await k.json(),V=DYt(I,z);l(Q=>({...Q,[I]:V})),d(null)}catch(N){console.error(`Error fetching models for ${I}:`,N),p(I),d(null),new Db.Notice(`Failed to load models for ${kf(I)}: ${ei(N)}`,5e3)}},A=async()=>{if(!m){new Db.Notice("Please select a model first");return}g(!0);try{let I=S(m.provider),R={name:m.name,provider:m.provider,apiKey:I,enabled:!0};if(await ac.instance.getCurrentChainManager().chatModelManager.ping(R),e.activeModels.find(j=>j.name===m.name&&j.provider===m.provider))new Db.Notice(`Model ${m.name} verified successfully! It already exists in your models list.`);else{let j=[...e.activeModels,R];dt("activeModels",j),new Db.Notice(`Model ${m.name} verified successfully and added to your models list!`)}}catch(I){console.error("Model verification failed:",I),new Db.Notice("Model verification failed: "+ei(I),1e4)}finally{g(!1)}};return Ht.default.createElement("div",{className:"tw-max-h-[600px] tw-overflow-y-auto tw-p-4 sm:tw-max-w-[500px]"},Ht.default.createElement("div",{className:"tw-mb-4"},Ht.default.createElement("h2",{className:"tw-text-xl tw-font-bold"},"AI Provider Settings"),Ht.default.createElement("p",{className:"tw-text-sm tw-text-muted"},"Configure your AI providers by adding their API keys.")),Ht.default.createElement("div",{className:"tw-space-y-6 tw-py-4"},Ht.default.createElement("div",{className:"tw-space-y-4"},x.map(I=>Ht.default.createElement(Ht.default.Fragment,{key:I.provider},Ht.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Ht.default.createElement("div",{className:"tw-flex tw-items-end tw-gap-2 tw-font-medium"},Ht.default.createElement("div",{className:"tw-truncate"},kf(I.provider))),Ht.default.createElement("div",{className:"tw-flex tw-flex-row tw-items-center tw-gap-2"},Ht.default.createElement("div",{className:"tw-flex-1"},Ht.default.createElement(aC,{className:"tw-max-w-full",value:I.apiKey,onChange:R=>O(I.provider,R),disabled:r.has(I.provider)})),Ht.default.createElement("div",{className:"tw-w-[72px]"},I.isVerified?Ht.default.createElement("span",{className:"tw-flex tw-h-9 tw-items-center tw-justify-center tw-text-sm tw-text-success"},"Verified"):Ht.default.createElement(ge,{onClick:()=>P(I.provider,I.apiKey),disabled:!I.apiKey||r.size>0,variant:"secondary",size:"sm",className:"tw-w-full tw-whitespace-nowrap"},r.has(I.provider)?Ht.default.createElement(Yl,{className:"tw-mr-2 tw-size-4 tw-animate-spin"}):"Verify")),Ht.default.createElement("div",{className:""},Ht.default.createElement(ge,{onClick:()=>{let R=a===I.provider?null:I.provider;s(R),R&&I.apiKey&&u[I.provider]===void 0&&c!==I.provider&&f!==I.provider&&E(I.provider,I.apiKey)},disabled:!I.apiKey||r.size>0,variant:"secondary",size:"sm",className:"tw-flex tw-w-full tw-items-center tw-justify-center tw-gap-1 tw-whitespace-nowrap tw-p-0.5"},"Add Model",a===I.provider?Ht.default.createElement(Ey,{className:"tw-ml-1 tw-size-4"}):Ht.default.createElement(Hi,{className:"tw-ml-1 tw-size-4"})))),Ht.default.createElement("div",null,Xb(I.provider).keyManagementURL&&Ht.default.createElement("a",{href:Xb(I.provider).keyManagementURL,target:"_blank",rel:"noopener noreferrer",className:"tw-text-[10px] tw-text-accent hover:tw-text-accent-hover sm:tw-text-xs"},"Get ",kf(I.provider)," Key"))),Ht.default.createElement(cE,{open:a===I.provider,className:"tw-mt-2"},Ht.default.createElement(dE,{className:"tw-rounded-md tw-p-3"},Ht.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Ht.default.createElement(Yn,{label:"Model",description:"Add the currently selected model to model List. After adding, please check the Model Tab."},Ht.default.createElement("div",null,Ht.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Ht.default.createElement("div",{className:"tw-flex-1"},Ht.default.createElement(Wde,{options:u[I.provider]?.sort((R,N)=>R.name.localeCompare(N.name)).map(R=>({label:R.name,value:R.id}))||[],onChange:R=>{let N=R.target.value,j=u[I.provider]?.find($=>$.id===N);j&&h({id:j.id,name:j.name,provider:I.provider})},onClick:()=>{I.
2025-07-05 20:48:33 +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
*)
react/cjs/react.production.min.js:
(**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
moment/moment.js:
(*! moment.js *)
(*! version : 2.29.4 *)
(*! authors : Tim Wood, Iskren Chernev, Moment.js contributors *)
(*! license : MIT *)
(*! momentjs.com *)
ieee754/index.js:
(*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)
buffer/index.js:
(*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*)
scheduler/cjs/scheduler.production.min.js:
(**
* @license React
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
react-dom/cjs/react-dom.production.min.js:
(**
* @license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
react/cjs/react-jsx-runtime.production.min.js:
(**
* @license React
* react-jsx-runtime.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/shared/src/utils.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/defaultAttributes.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/Icon.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/createLucideIcon.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/arrow-big-up.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/arrow-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/bot.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/check.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/chevron-down.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/chevron-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/chevron-up.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-help.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-plus.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-stop.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-x.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/clipboard.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/cog.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/command.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/copy.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/corner-down-left.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/cpu.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/database.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/download.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/ellipsis-vertical.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/ellipsis.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/external-link.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/eye-off.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/eye.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-audio.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-image.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-input.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-output.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-text.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file-video.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/folder.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/globe.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/grip-vertical.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/history.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/image.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/info.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/key.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/library-big.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/lightbulb.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/loader-circle.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/message-circle-plus.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/message-square.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/pen-line.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/pen.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/pencil-line.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/pencil.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/plus.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/refresh-ccw.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/refresh-cw.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/rotate-cw.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/search.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/sparkles.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/square-arrow-out-up-right.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/square-pen.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/tag.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/text-cursor-input.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/trash-2.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/triangle-alert.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/user.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/wrench.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/x.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/lucide-react.js:
(**
* @license lucide-react v0.462.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
tslib/tslib.es6.js:
(*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** *)
safe-buffer/index.js:
(*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
@langchain/core/dist/utils/js-sha1/hash.js:
(*
* [js-sha1]{@link https://github.com/emn178/js-sha1}
*
* @version 0.6.0
* @author Chen, Yi-Cyuan [emn178@gmail.com]
* @copyright Chen, Yi-Cyuan 2014-2017
* @license MIT
*)
@google/generative-ai/dist/index.mjs:
(**
* @license
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*)
crypto-js/ripemd160.js:
(** @preserve
(c) 2012 by Cédric Mesnil. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
crypto-js/mode-ctr-gladman.js:
(** @preserve
* Counter block mode compatible with Dr Brian Gladman fileenc.c
* derived from CryptoJS.mode.CTR
* Jan Hruby jhruby.web@gmail.com
*)
*/
/* nosourcemap */