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

1787 lines
3.7 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-08-12 16:40:13 +08:00
var Mlr=Object.create;var tH=Object.defineProperty;var Rlr=Object.getOwnPropertyDescriptor;var Nlr=Object.getOwnPropertyNames;var jlr=Object.getPrototypeOf,Dlr=Object.prototype.hasOwnProperty;var h6e=t=>{throw TypeError(t)};var Llr=(t,e,r)=>e in t?tH(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),Qd=(t,e)=>{for(var r in e)tH(t,r,{get:e[r],enumerable:!0})},g6e=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Nlr(e))!Dlr.call(t,o)&&o!==r&&tH(t,o,{get:()=>e[o],enumerable:!(n=Rlr(e,o))||n.enumerable});return t};var F=(t,e,r)=>(r=t!=null?Mlr(jlr(t)):{},g6e(e||!t||!t.__esModule?tH(r,"default",{value:t,enumerable:!0}):r,t)),dc=t=>g6e(tH({},"__esModule",{value:!0}),t);var Kc=(t,e,r)=>Llr(t,typeof e!="symbol"?e+"":e,r),Flr=(t,e,r)=>e.has(t)||h6e("Cannot "+r);var y6e=(t,e,r)=>e.has(t)?h6e("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r);var b6e=(t,e,r)=>(Flr(t,e,"access private method"),r);function Cye(){if(!B7&&(B7=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!B7))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return B7(klr)}var B7,klr,_6e=w(()=>{klr=new Uint8Array(16)});function v6e(t,e=0){return Gc[t[e+0]]+Gc[t[e+1]]+Gc[t[e+2]]+Gc[t[e+3]]+"-"+Gc[t[e+4]]+Gc[t[e+5]]+"-"+Gc[t[e+6]]+Gc[t[e+7]]+"-"+Gc[t[e+8]]+Gc[t[e+9]]+"-"+Gc[t[e+10]]+Gc[t[e+11]]+Gc[t[e+12]]+Gc[t[e+13]]+Gc[t[e+14]]+Gc[t[e+15]]}var Gc,w6e=w(()=>{Gc=[];for(let t=0;t<256;++t)Gc.push((t+256).toString(16).slice(1))});var $lr,Oye,x6e=w(()=>{$lr=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Oye={randomUUID:$lr}});function zlr(t,e,r){if(Oye.randomUUID&&!e&&!t)return Oye.randomUUID();t=t||{};let n=t.random||(t.rng||Cye)();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 v6e(n)}var Rp,S6e=w(()=>{x6e();_6e();w6e();Rp=zlr});var I1=w(()=>{S6e()});var kn,Pye,yt,I_,rH=w(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let i={};for(let a of o)i[a]=a;return i},t.getValidEnumValues=o=>{let i=t.objectKeys(o).filter(s=>typeof o[o[s]]!="number"),a={};for(let s of i)a[s]=o[s];return t.objectValues(a)},t.objectValues=o=>t.objectKeys(o).map(function(i){return o[i]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let i=[];for(let a in o)Object.prototype.hasOwnProperty.call(o,a)&&i.push(a);return i},t.find=(o,i)=>{for(let a of o)if(i(a))return a},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,i=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=n,t.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(kn||(kn={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Pye||(Pye={}));yt=kn.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),I_=t=>{switch(typeof t){case"undefined":return yt.undefined;case"string":return yt.string;case"number":return Number.isNaN(t)?yt.nan:yt.number;case"boolean":return yt.boolean;case"function":return yt.function;case"bigint":return yt.bigint;case"symbol":return yt.symbol;case"object":return Array.isArray(t)?yt.array:t===null?yt.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?yt.promise:typeof Map<"u"&&t instanceof Map?yt.map:typeof Set<"u"&&t instanceof Set?yt.set:typeof Date<"u"&&t instanceof Date?yt.date:yt.object;default:return yt.unknown}}});var ze,Blr,Np,U7=w(()=>{rH();ze=kn.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","inval
Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function nZ(t){return typeof t=="function"&&"langsmith:traceable"in t}var $ye,kye,pdr,zye,mdr,m2n,r8e=w(()=>{$ye=class{getStore(){}run(e,r){return r()}},kye=Symbol.for("ls:tracing_async_local_storage"),pdr=new $ye,zye=class{getInstance(){return globalThis[kye]??pdr}initializeGlobalInstance(e){globalThis[kye]===void 0&&(globalThis[kye]=e)}},mdr=new zye;m2n=Symbol.for("langsmith:traceable:root")});var Bye=w(()=>{r8e()});function iZ(t,e){return hdr.call(t,e)}function aZ(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)iZ(t,r)&&e.push(r);return e}function tf(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function sZ(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 N_(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function sH(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function oZ(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if(oZ(t[r]))return!0}else if(typeof t=="object"){let r=aZ(t),n=r.length;for(var e=0;e<n;e++)if(oZ(t[r[e]]))return!0}}return!1}function n8e(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 hdr,J1,uH=w(()=>{hdr=Object.prototype.hasOwnProperty;J1=class extends Error{constructor(e,r,n,o,i){super(n8e(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=n8e(e,{name:r,index:n,operation:o,tree:i})}}});var Uye={};Qd(Uye,{JsonPatchError:()=>vs,_areEquals:()=>lH,applyOperation:()=>Z1,applyPatch:()=>KT,applyReducer:()=>bdr,deepClone:()=>gdr,getValueByPointer:()=>uZ,validate:()=>o8e,validator:()=>lZ});function uZ(t,e){if(e=="")return t;var r={op:"_get",path:e};return Z1(t,r),r.value}function Z1(t,e,r=!1,n=!0,o=!0,i=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):lZ(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=uZ(t,e.from),e.op==="move"&&(a.removed=t),a;if(e.op==="test"){if(a.test=lH(t,e.value),a.test===!1)throw new vs("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 vs("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return a}}else{n||(t=tf(t));let s=(e.path||"").split("/"),u=t,l=1,c=s.length,d,f,p;for(typeof r=="function"?p=r:p=lZ;;){if(f=s[l],f&&f.indexOf("~")!=-1&&(f=sH(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&&!sZ(f))throw new vs("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);sZ(f)&&(f=~~f)}if(l>=c){if(r&&e.op==="add"&&f>u.length)throw new vs("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=ydr[e.op].call(e,u,f,t);if(m.test===!1)throw new vs("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return m}}else if(l>=c){let m=Wk[e.op].call(e,u,f,t);if(m.test===!1)throw new vs("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return m}if(u=u[f],r&&l<c&&(!u||typeof u!="object"))throw new vs("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function KT(t,e,r,n=!0,o=!0){if(r&&!Array.isArray(e))throw new vs("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=tf(t));let i=new Array(e.length);for(let a=0,s=e.length;a<s;a++)i[a]=Z1(t,e[a],r,!0,o,a),t=i[a].newDocument;return i.newDocument=t,i}function bdr(t,e,r){let n=Z1(t,e);if(n.test===!1)throw new vs("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function lZ(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new vs("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(Wk[t.op]){if(typeof t.path!="string")throw new vs("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new vs('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 vs("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
Context: ${e}`:""}`),FZ("[Unserializable]");$l("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
Context: ${e}`:""}`),typeof o>"u"&&(o=zmr()),kbe(t,"",0,[],void 0,0,o);let a;try{Jk.length===0?a=JSON.stringify(t,r,n):a=JSON.stringify(t,Umr(r),n)}catch{return FZ("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;kZ.length!==0;){let s=kZ.pop();s.length===4?Object.defineProperty(s[0],s[1],s[3]):s[0][s[1]]=s[2]}}return FZ(a)}}function Fbe(t,e,r,n){var o=Object.getOwnPropertyDescriptor(n,r);o.get!==void 0?o.configurable?(Object.defineProperty(n,r,{value:t}),kZ.push([n,r,e,o])):Jk.push([e,r,t]):(n[r]=t,kZ.push([n,r,e]))}function kbe(t,e,r,n,o,i,a){i+=1;var s;if(typeof t=="object"&&t!==null){for(s=0;s<n.length;s++)if(n[s]===t){Fbe(kmr,t,e,o);return}if(typeof a.depthLimit<"u"&&i>a.depthLimit){Fbe(X5e,t,e,o);return}if(typeof a.edgesLimit<"u"&&r+1>a.edgesLimit){Fbe(X5e,t,e,o);return}if(n.push(t),Array.isArray(t))for(s=0;s<t.length;s++)kbe(t[s],s,s,n,t,i,a);else{t=Q5e(t);var u=Object.keys(t);for(s=0;s<u.length;s++){var l=u[s];kbe(t[l],l,s,n,t,i,a)}}n.pop()}}function Umr(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(Jk.length>0)for(var n=0;n<Jk.length;n++){var o=Jk[n];if(o[1]===e&&o[0]===r){r=o[2],Jk.splice(n,1);break}}return t.call(this,e,r)}}var X5e,kmr,kZ,Jk,$mr,e9e=w(()=>{EO();X5e="[...]",kmr={result:"[Circular]"},kZ=[],Jk=[],$mr=new TextEncoder});function t9e(t){let e=hZ(),r=$8e(),n=t.extra??{},o=n.metadata;return t.extra={...n,runtime:{...e,...n?.runtime},metadata:{...r,...r.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??r.revision_id}:{},...o}},t}async function Vmr(t){let e=[];for await(let r of t)e.push(r);return e}function $be(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}function r9e(t){return typeof t=="number"?Number(t.toFixed(4)):t}function o9e(t){return"dataset_id"in t||"dataset_name"in t}var qmr,Hmr,Wmr,zbe,Kmr,Gmr,n9e,Y1,Zye=w(()=>{G1();q8e();sbe();eVe();tVe();EO();mZ();rVe();gbe();J5e();Lbe();fZ();e9e();qmr=t=>{let e=t?.toString()??$l("TRACING_SAMPLING_RATE");if(e===void 0)return;let r=parseFloat(e);if(r<0||r>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r},Hmr=t=>{let r=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"};Wmr=async t=>{if(t?.status===429){let e=parseInt(t.headers.get("retry-after")??"30",10)*1e3;if(e>0)return await new Promise(r=>setTimeout(r,e)),!0}return!1};zbe=class{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(e){let r,n=new Promise(i=>{r=i}),o=Fp(e.item,`Serializing run with id: ${e.item.id}`).length;return this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:r,itemPromise:n,size:o}),this.sizeBytes+=o,n}pop(e){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");let r=[],n=0;for(;n+(this.peek()?.size??0)<e&&this.items.length>0;){let o=this.items.shift();o&&(r.push(o),n+=o.size,this.sizeBytes-=o.size)}if(r.length===0&&this.items.length>0){let o=this.items.shift();r.push(o),n+=o.size,this.sizeBytes-=o.size}return[r.map(o=>({action:o.action,item:o.payload,otelContext:o.otelContext,apiKey:o.apiKey,apiUrl:o.apiUrl})),()=>r.forEach(o=>o.itemPromiseResolve())]}},Kmr=20971520,Gmr=2500,n9e="https://api.smith.langchain.com",Y1=class t{constructor(e={}){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,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tim
2025-07-05 20:48:33 +08:00
=== LangSmith Server Configuration ===
`+JSON.stringify(r,null,2)+`
2025-08-12 16:40:13 +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(e){console.warn(`[WARNING]: LangSmith failed to fetch info on supported operations with status code ${e.status}. 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)}_cloneCurrentOTELContext(){let e=yZ(),r=B8e();if(this.langSmithToOTELTranslator!==void 0){let n=e.getActiveSpan();if(n)return e.setSpan(r.active(),n)}}async createRun(e,r){if(!this._filterForSampling([e]).length)return;let n={...this.headers,"Content-Type":"application/json"},o=e.project_name;delete e.project_name;let i=await this.prepareRunCreateOrUpdateInputs({session_name:o,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){let u=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:i,otelContext:u,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}let a=t9e(i);r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey);let s=await this.caller.call(Vt(this.debug),`${r?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,body:Fp(a,`Creating run with id: ${a.id}`),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await nn(s,"create run",!0)}async batchIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let o=await Promise.all(e?.map(u=>this.prepareRunCreateOrUpdateInputs(u))??[]),i=await Promise.all(r?.map(u=>this.prepareRunCreateOrUpdateInputs(u))??[]);if(o.length>0&&i.length>0){let u=o.reduce((c,d)=>(d.id&&(c[d.id]=d),c),{}),l=[];for(let c of i)c.id!==void 0&&u[c.id]?u[c.id]={...u[c.id],...c}:l.push(c);o=Object.values(u),i=l}let a={post:o,patch:i};if(!a.post.length&&!a.patch.length)return;let s={post:[],patch:[]};for(let u of["post","patch"]){let l=u,c=a[l].reverse(),d=c.pop();for(;d!==void 0;)s[l].push(d),d=c.pop()}if(s.post.length>0||s.patch.length>0){let u=s.post.map(l=>l.id).concat(s.patch.map(l=>l.id)).join(",");await this._postBatchIngestRuns(Fp(s,`Ingesting runs with ids: ${u}`),n)}}async _postBatchIngestRuns(e,r){let n={...this.headers,"Content-Type":"application/json",Accept:"application/json"};r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey);let o=await this.batchIngestCaller.call(Vt(this.debug),`${r?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,body:e,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await nn(o,"batch create run",!0)}async multipartIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let o={},i=[];for(let d of e??[]){let f=await this.prepareRunCreateOrUpdateInputs(d);f.id!==void 0&&f.attachments!==void 0&&(o[f.id]=f.attachments),delete f.attachments,i.push(f)}let a=[];for(let d of r??[])a.push(await this.prepareRunCreateOrUpdateInputs(d));if(i.find(d=>d.trace_id===void 0||d.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(a.find(d=>d.trace_id===void 0||d.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(i.length>0&&a.length>0){let d=i.reduce((p,m)=>(m.id&&(p[m.id]=m),p),{}),f=[];for(let p of a)p.id!==void 0&&d[p.id]?d[p.id]={...d[p.id],...p}:f.push(p);i=Object.values(d),a=f}if(i.length===0&&a.length===0)return;let l=[],c=[];for(let[d,f]of[["post",i],["patch",a]])for(let p of f){let{inputs:m,outputs:h,events:b,attachments:g,...y}=p,x={inputs:m,outputs:h,events:b},S=Fp(y,`Serializing for multipart ingestion of run with id: ${y.id}`);c.push({name:`${d}.${y.id}`,payload:new Blob([S],{type:`application/json; length=${S.length}`})});for(let[O,E]of Object.entries(
`])),n.push(new Blob([`Content-Disposition: form-data; name="${a.name}"\r
`,`Content-Type: ${a.payload.type}\r
2025-07-05 20:48:33 +08:00
\r
2025-08-12 16:40:13 +08:00
`])),n.push(a.payload),n.push(new Blob([`\r
`]));return n.push(new Blob([`--${r}--\r
`])),await new Blob(n).arrayBuffer()}async _createMultipartStream(e,r){let n=new TextEncoder;return new ReadableStream({async start(i){let a=async s=>{typeof s=="string"?i.enqueue(n.encode(s)):i.enqueue(s)};for(let s of e){await a(`--${r}\r
`),await a(`Content-Disposition: form-data; name="${s.name}"\r
`),await a(`Content-Type: ${s.payload.type}\r
\r
`);let l=s.payload.stream().getReader();try{let c;for(;!(c=await l.read()).done;)i.enqueue(c.value)}finally{l.releaseLock()}await a(`\r
`)}await a(`--${r}--\r
`),i.close()}})}async _sendMultipartRequest(e,r,n){let o="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),i=F8e(),a=()=>this._createNodeFetchBody(e,o),s=()=>this._createMultipartStream(e,o),u=async l=>{let c={...this.headers,"Content-Type":`multipart/form-data; boundary=${o}`};return n?.apiKey!==void 0&&(c["x-api-key"]=n.apiKey),this.batchIngestCaller.call(Vt(this.debug),`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:c,body:l,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})};try{let l,c=!1;!i&&!this.multipartStreamingDisabled?(c=!0,l=await u(await s())):l=await u(await a()),(!this.multipartStreamingDisabled||c)&&l.status===422&&(n?.apiUrl??this.apiUrl)!==n9e&&(console.warn(`Streaming multipart upload to ${n?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${r}".`),this.multipartStreamingDisabled=!0,l=await u(await a())),await nn(l,"ingest multipart runs",!0)}catch(l){console.warn(`${l.message.trim()}
2025-07-05 20:48:33 +08:00
2025-08-12 16:40:13 +08:00
Context: ${r}`)}}async updateRun(e,r,n){Jr(e),r.inputs&&(r.inputs=await this.processInputs(r.inputs)),r.outputs&&(r.outputs=await this.processOutputs(r.outputs));let o={...r,id:e};if(!this._filterForSampling([o],!0).length)return;if(this.autoBatchTracing&&o.trace_id!==void 0&&o.dotted_order!==void 0){let s=this._cloneCurrentOTELContext();if(r.end_time!==void 0&&o.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:o,otelContext:s,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:o,otelContext:s,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}let i={...this.headers,"Content-Type":"application/json"};n?.apiKey!==void 0&&(i["x-api-key"]=n.apiKey);let a=await this.caller.call(Vt(this.debug),`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:i,body:Fp(r,`Serializing payload to update run with id: ${e}`),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await nn(a,"update run",!0)}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){Jr(e);let n=await this._get(`/runs/${e}`);return r&&(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:$l("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 Vmr(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),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.dotted_order?.startsWith(e.dotted_order??"")&&i.id!==e.id&&(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,order:x}=e,S=[];if(r&&(S=Array.isArray(r)?r:[r]),n){let A=Array.isArray(n)?n:[n],I=await Promise.all(A.map(R=>this.readProject({projectName:R}).then(N=>N.id)));S.push(...I)}let O=["app_path","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"],E={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||O,is_root:l,order:x},P=0;for await(let A of this._getCursorPaginatedList("/runs/query",E))if(g){if(P>=g)break;if(A.length+P>g){yield*A.slice(0,g-P);break}P+=A.length,yield*A}else yield*A}async*listGroupRuns(e){let{projectId:r,projectName:n,groupBy:o,filter:i,startTime:a,endTime:s,limit:u,offset:l}=e,d={session_id:r||(await this.readProject({projectName:n})).id,group_by:o,filter:i,start_time:a?a.toISOString():null,end_time:s?s.toISOString():null,limit:Number(u)||100},f=Number(l)||0,p="/runs/group",m=`${this.apiUrl}${p}`;for(;;){let h={...d,offset:f},b=Object.fromEntries(Object.entries(h).filter(([O,E])=>E!==void 0)),g=await this.caller.call(Vt(),m,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(b),signal:AbortSignal.timeout(this.timeout_ms),...this.fet
2025-07-05 20:48:33 +08:00
Status: ${i.status}
2025-08-12 16:40:13 +08:00
Message: ${Array.isArray(a.detail)?a.detail.join(`
`):"Unspecified error"}`):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 nn(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 nn(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)Jr(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)Jr(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,Jr(n);let o=await this.caller.call(Vt(this.debug),`${this.a
`).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;Jr(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 nn(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;Jr(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 nn(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)Jr(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 nn(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),Jr(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 nn(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),Jr(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 nn(a,"fetch similar examples"),(await a.json()).examples}async createExample(e,r,n){if(o9e(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;o9e(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]??_s())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let y=e,x=y[0].dataset_id,S=y[0].dataset_name;if(x===void 0&&S===void 0)throw new Error("Must provide either datasetName or datasetId");if(x!==void 0&&S!==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-08-12 16:40:13 +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]=IO(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 nn(a,`${r?"like":"unlike"} prompt`),await a.json()}async _getPromptUrl(e){let[r,n,o]=IO(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]=IO(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 nn(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
2025-08-12 16:40:13 +08:00
creating a LangChain Hub handle.
2025-07-05 20:48:33 +08:00
You can add a handle by creating a public prompt at:
2025-08-12 16:40:13 +08:00
https://smith.langchain.com/prompts`);let[o,i,a]=IO(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 nn(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]=IO(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 nn(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=Fp(l,`Serializing body for example with id: ${u}`),d=new Blob([c],{type:"application/json"});if(n.append(u,d),s.inputs){let f=Fp(s.inputs,`Serializing inputs for example with id: ${u}`),p=new Blob([f],{type:"application/json"});n.append(`${u}.inputs`,p)}if(s.outputs){let f=Fp(s.outputs,`Serializing outputs whle updating example with id: ${u}`),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=Fp(s.attachments_operations,`Serializing attachments while updating example with id: ${u}`),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}${this._getPlatformEndpointPath(`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??_s()).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=Fp(u,`Serializing body for uploaded example with id: ${s}`),c=new Blob([l],{type:"application/json"});if(n.append(s,c),a.inputs){let d=Fp(a.inputs,`Serializing inputs for uploaded example with id: ${s}`),f=new Blob([d],{type:"application/json"});n.append(`${s}.inputs`,f)}if(a.outputs){let d=Fp(a.outputs,`Serializing outputs for uploaded example with id: ${s}`),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=
2025-07-05 20:48:33 +08:00
2025-08-12 16:40:13 +08:00
${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,r){e.child_runs.push(r)}_addRunToRunMap(e){let{dottedOrder:r,microsecondPrecisionDatestring:n}=Bbe(new Date(e.start_time).getTime(),e.id,e.execution_order),o={...e},i=this.getRunById(o.parent_run_id);if(o.parent_run_id!==void 0?i&&(this._addChildRun(i,o),i.child_execution_order=Math.max(i.child_execution_order,o.child_execution_order),o.trace_id=i.trace_id,i.dotted_order!==void 0&&(o.dotted_order=[i.dotted_order,r].join("."),o._serialized_start_time=n)):(o.trace_id=o.id,o.dotted_order=r,o._serialized_start_time=n),this.usesRunTreeMap){let a=Jbe(o,i);a!==void 0&&this.runTreeMap.set(o.id,a)}else this.runMap.set(o.id,o);return o}async _endTrace(e){let r=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);r?r.child_execution_order=Math.max(r.child_execution_order,e.child_execution_order):await this.persistRun(e),await this.onRunUpdate?.(e),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){let r=e!==void 0&&this.getRunById(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.getRunById(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.getRunById(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.getRunById(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.getRunById(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.getRunById(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.getRunById(r);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.outputs=Gbe(e,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=Gbe(i.inputs,"input")),await this.onChainEnd?.(a),await this._endTrace(a),a}async handleChainError(e,r,n,o,i){let a=this.getRunById(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=Gbe(i.inputs,"input")),await this.onChainError?.(a),await this._endTrace(a),a}_createRunFo
2025-07-05 20:48:33 +08:00
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
2025-08-12 16:40:13 +08:00
`,t}var xH=w(()=>{});function ZT(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="tool_call")}function N9e(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 nN,qZ=w(()=>{nN=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 Ybe(t,e=Yk){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-08-12 16:40:13 +08:00
`)&&(n=n.substring(1));let o=n.indexOf("```"),i=n;return o!==-1&&(i=n.substring(0,o)),e(i.trim())}function Yk(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 Xbe=w(()=>{});function Jy(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 j9e(t){return Jy(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}function D9e(t){return Jy(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}function L9e(t){if(Jy(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 Qbe(t){let e=t.split(";")[0].split("/");if(e.length!==2)throw new Error(`Invalid mime type: "${t}" - does not match type/subtype format.`);let r=e[0].trim(),n=e[1].trim();if(r===""||n==="")throw new Error(`Invalid mime type: "${t}" - type or subtype is empty.`);let o={};for(let i of t.split(";").slice(1)){let a=i.split("=");if(a.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${t}".`);let s=a[0].trim(),u=a[1].trim();if(s==="")throw new Error(`Invalid parameter syntax in mime type: "${t}".`);o[s]=u}return{type:r,subtype:n,parameters:o}}function Xk({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 SH(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 e_e=w(()=>{});function og(t,e){return typeof t=="string"?t===""?e:typeof e=="string"?t+e:Array.isArray(e)&&e.some(r=>Jy(r))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e]:Array.isArray(e)?CH(t,e)??[...t,...e]:e===""?t:Array.isArray(t)&&t.some(r=>Jy(r))?[...t,{type:"file",source_type:"text",text:e}]:[...t,{type:"text",text:e}]}function F9e(t,e){return t==="error"||e==="error"?"error":"success"}function ghr(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 Fs(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]=Fs(r[n],o);else if(Array.isArray(r[n]))r[n]=CH(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 CH(t,e){if(!(t===void 0&&e===void 0)){if(t===void 0||e===void 0)retur
2025-07-05 20:48:33 +08:00
Left ${typeof t}
2025-08-12 16:40:13 +08:00
Right ${typeof e}`);if(typeof t=="string"&&typeof e=="string")return t+e;if(Array.isArray(t)&&Array.isArray(e))return CH(t,e);if(typeof t=="object"&&typeof e=="object")return Fs(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-08-12 16:40:13 +08:00
Right ${e}`)}function $9e(t){return typeof t.role=="string"}function ig(t){return typeof t?._getType=="function"}function t_e(t){return ig(t)&&typeof t.concat=="function"}var zl,zp,ag=w(()=>{Q1();e_e();zl=class extends kp{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=ghr(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${r}`}};zp=class extends zl{}});function z9e(t){return t!=null&&typeof t=="object"&&"lc_direct_tool_output"in t&&t.lc_direct_tool_output===!0}function B9e(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 MO,sg,Qk=w(()=>{ag();MO=class extends zl{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,"metadata",{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,this.metadata=e.metadata}_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}}},sg=class t extends zp{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:og(this.content,e.content),additional_kwargs:Fs(this.additional_kwargs,e.a
2025-07-05 20:48:33 +08:00
2025-08-12 16:40:13 +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]=B9e(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}}};yr=class t extends zp{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=e.tool_call_chunks.reduce((a,s)=>{let u=s.id||`fallback-${s.index||0}`;return a[u]=a[u]??[],a[u].push(s),a},{}),o=[],i=[];for(let[a,s]of Object.entries(n)){let u={},l=s[0]?.name??"",c=s.map(p=>p.args||"").join(""),d=c.length?c:"{}",f=s[0]?.id||a;try{if(u=Yk(d),u===null||typeof u!="object"||Array.isArray(u))throw new Error("Malformed tool call chunk args.");o.push({name:l,args:u,id:f,type:"tool_call"})}catch{i.push({name:l,args:d,id:f,error:"Malformed args.",type:"invalid_tool_call"})}}r={...e,tool_calls:o,invalid_tool_calls:i,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:og(this.content,e.content),additional_kwargs:Fs(this.additional_kwargs,e.additional_kwargs),response_metadata:Fs(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=CH(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!=
2025-07-05 20:48:33 +08:00
2025-08-12 16:40:13 +08:00
Received: ${JSON.stringify(t,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Zy(t){if(typeof t=="string")return new $s(t);if(ig(t))return t;if(Array.isArray(t)){let[e,r]=t;return n_e({type:e,content:r})}else if($9e(t)){let{role:e,...r}=t;return n_e({...r,type:e})}else return n_e(t)}function Xf(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 o_e(t){let e=t._getType();if(e==="human")return new Yf({...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 yr({...r})}else{if(e==="system")return new of({...t});if(e==="function")return new Um({...t});if(ks.isInstance(t))return new Zf({...t});throw new Error("Unknown message type.")}}var YT=w(()=>{xH();qZ();oN();ag();HZ();VZ();OH();WZ();Qk()});var KZ=w(()=>{mZ()});var i_e,a_e,s_e=w(()=>{KZ();eN();a_e=()=>{if(i_e===void 0){let t=ct("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};i_e=new Y1(t)}return i_e}});var e$,U9e=w(()=>{KZ();BZ();Bye();rN();s_e();e$=class t extends rg{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}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"usesRunTreeMap",{enumerable:!0,configurable:!0,writable:!0,value:!0});let{exampleId:r,projectName:n,client:o,replicas:i}=e;this.projectName=n??cH(),this.replicas=i,this.exampleId=r,this.client=o??a_e();let a=t.getTraceableRunTree();a&&this.updateFromRunTree(a)}async persistRun(e){}async onRunCreate(e){await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){await this.getRunTreeWithTracingConfig(e.id)?.patchRun()}getRun(e){return this.runTreeMap.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.runTreeMap.set(i.id,i),i.child_runs&&o.push(...i.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(e){let r=this.runTreeMap.get(e);if(r)return new Gy({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return t8e(!0)}catch{return}}}});var q9e,iN,H9e,XT,PH=w(()=>{q9e=Symbol.for("ls:tracing_async_local_storage"),iN=Symbol.for("lc:context_variables"),H9e=t=>{globalThis[q9e]=t},XT=()=>globalThis[q9e]});function vhr(){let t="default"in GZ.default?GZ.default.default:GZ.default;return new t({autoStart:!0,concurrency:1})}function whr(){return typeof EH>"u"&&(EH=vhr()),EH}async function zs(t,e){if(e===!0){let r=XT();r!==void 0?await r.run(void 0,async()=>t()):await t()}else EH=whr(),EH.add(async()=>{let r=XT();r!==void 0?await r.run(void 0,async()=>t()):await t()})}var GZ,EH,V9e=w(()=>{GZ=F(SZ(),1);PH();s_e()});var W9e=w(()=>{V9e()});var K9e,G9e=w(()=>{eN();K9e=t=>t!==void 0?t:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(r=>ct(r)==="true")});function u_e(t){let e=XT();return e===void 0?void 0:e.getStore()?.[iN]?.[t]}var xhr,J9e,Z9e=w(()=>{BZ();PH();xhr=Symbol("lc:configure_hooks"),J9e=()=>u_e(xhr)||[]});function aN(t){return t?Array.isArray(t)||"name"in t?{callbacks:t}:t:{}}function TH(t){return"name"in t?t:tN.fromMethods(t)}var l_e,t$,c_e,JZ,d_e,f_e,ru,QT=w(()=>{G1();vH();R9e();YT();eN();U9e();W9e();G9e();rN();Z9e();l_e=class{setHandler(e){return this.setHandlers([e])}},t$=class{constructor(e,r,n,o,i,a,s,u){Object.defineProperty(this,"runId",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:
`;return e}function uWe(t,e,r){let{firstNode:n,lastNode:o,nodeColors:i,withStyles:a=!0,curveStyle:s="linear",wrapLabelNWords:u=9}=r??{},l=a?`%%{init: {'flowchart': {'curve': '${s}'}}}%%
graph TD;
`:`graph TD;
`;if(a){let p="default",m={[p]:"{0}({1})"};n!==void 0&&(m[n]="{0}([{1}]):::first"),o!==void 0&&(m[o]="{0}([{1}]):::last");for(let[h,b]of Object.entries(t)){let g=b.name.split(":").pop()??"",x=Thr.some(O=>g.startsWith(O)&&g.endsWith(O))?`<p>${g}</p>`:g;Object.keys(b.metadata??{}).length&&(x+=`<hr/><small><em>${Object.entries(b.metadata??{}).map(([O,E])=>`${O} = ${E}`).join(`
`)}</em></small>`);let S=(m[h]??m[p]).replace("{0}",y_e(h)).replace("{1}",x);l+=` ${S}
`}}let c={};for(let p of e){let m=p.source.split(":"),h=p.target.split(":"),b=m.filter((g,y)=>g===h[y]).join(":");c[b]||(c[b]=[]),c[b].push(p)}let d=new Set;function f(p,m){let h=p.length===1&&p[0].source===p[0].target;if(m&&!h){let b=m.split(":").pop();if(d.has(b))throw new Error(`Found duplicate subgraph '${b}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(b),l+=` subgraph ${b}
`}for(let b of p){let{source:g,target:y,data:x,conditional:S}=b,O="";if(x!==void 0){let E=x,P=E.split(" ");P.length>u&&(E=Array.from({length:Math.ceil(P.length/u)},(A,I)=>P.slice(I*u,(I+1)*u).join(" ")).join("&nbsp;<br>&nbsp;")),O=S?` -. &nbsp;${E}&nbsp; .-> `:` -- &nbsp;${E}&nbsp; --> `}else O=S?" -.-> ":" --> ";l+=` ${y_e(g)}${O}${y_e(y)};
`}for(let b in c)b.startsWith(`${m}:`)&&b!==m&&f(c[b],b);m&&!h&&(l+=` end
`)}f(c[""]??[],"");for(let p in c)!p.includes(":")&&p!==""&&f(c[p],p);return a&&(l+=Ahr(i??{})),l}async function lWe(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 Thr,cWe=w(()=>{Thr=["*","_","`"]});function i$(t,e,r){function n(s,u){var l;Object.defineProperty(s,"_zod",{value:s._zod??{},enumerable:!1}),(l=s._zod).traits??(l.traits=new Set),s._zod.traits.add(t),e(s,u);for(let c in a.prototype)c in s||Object.defineProperty(s,c,{value:a.prototype[c].bind(s)});s._zod.constr=a,s._zod.def=u}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:t});function a(s){var u;let l=r?.Parent?new i:this;n(l,s),(u=l._zod).deferred??(u.deferred=[]);for(let c of l._zod.deferred)c();return l}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:s=>r?.Parent&&s instanceof r.Parent?!0:s?._zod?.traits?.has(t)}),Object.defineProperty(a,"name",{value:t}),a}function a$(t){return t&&Object.assign(b_e,t),b_e}var E6n,T6n,eA,b_e,jH=w(()=>{E6n=Object.freeze({status:"aborted"});T6n=Symbol("zod_brand"),eA=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},b_e={}});function __e(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function fWe(t,e){return typeof e=="bigint"?e.toString():e}function pWe(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function s$(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function mWe(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function nY(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function rY(t){return typeof t=="string"?t:t?.message}function u$(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=rY(t.inst?._zod.def?.error?.(t))??rY(e?.error?.(t))??rY(r.customError?.(t))??rY(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}var v_e,Ihr,A6n,tA=w(()=>{v_e=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{},Ihr=pWe(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});A6n={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}});var hWe,gWe,DH,w_e=w(()=>{jH();tA();hWe=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,fWe,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},gWe=i$("$ZodError",hWe),DH=i$("$ZodError",hWe,{Parent:Error})});var Rhr,oY,Nhr,yWe,jhr,bWe,Dhr,_We,x_e=w(()=>{jH();w_e();tA();Rhr=t=>(e,r,n,o)=>{let i=n?Object.assign(n,{async:!1}):{async:!1},a=e._zod.run({value:r,issues:[]},i);if(a instanceof Promise)throw new eA;if(a.issues.length){let s=new(o?.Err??t)(a.issues.map(u=>u$(u,i,a$())));throw v_e(s,o?.callee),s}return a.value},oY=Rhr(DH),Nhr=t=>async(e,r,n,o)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},a=e._zod.run({value:r,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){let s=new(o?.Err??t)(a.issues.map(u=>u$(u,i,a$())));throw v_e(s,o?.callee),s}return a.value},yWe=Nhr(DH),jhr=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new eA;return i.issues.length?{success:!1,error:new(t??gWe)(i.issues.map(a=>u$(a,o,a$())))}:{success:!0,data:i.value}},bWe=jhr(DH),Dhr=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{succe
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let c of this.seen.entries()){let d=c[1];if(e===c[0]){a(c);continue}if(n.external){let p=n.external.registry.get(c[0])?.id;if(e!==c[0]&&p){a(c);continue}}if(this.metadataRegistry.get(c[0])?.id){a(c);continue}if(d.cycle){a(c);continue}if(d.count>1&&n.reused==="ref"){a(c);continue}}let s=(c,d)=>{let f=this.seen.get(c),p=f.def??f.schema,m={...p};if(f.ref===null)return;let h=f.ref;if(f.ref=null,h){s(h,d);let b=this.seen.get(h).schema;b.$ref&&d.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(b)):(Object.assign(p,b),Object.assign(p,m))}f.isParent||this.override({zodSchema:c,jsonSchema:p,path:f.path??[]})};for(let c of[...this.seen.entries()].reverse())s(c[0],{target:this.target});let u={};if(this.target==="draft-2020-12"?u.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?u.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let c=n.external.registry.get(e)?.id;if(!c)throw new Error("Schema is missing an `id` property");u.$id=n.external.uri(c)}Object.assign(u,o.def);let l=n.external?.defs??{};for(let c of this.seen.entries()){let d=c[1];d.def&&d.defId&&(l[d.defId]=d.def)}n.external||Object.keys(l).length>0&&(this.target==="draft-2020-12"?u.$defs=l:u.definitions=l);try{return JSON.parse(JSON.stringify(u))}catch{throw new Error("Error converting schema to JSON.")}}}});var MWe=w(()=>{});var aY=w(()=>{jH();x_e();w_e();OWe();wWe();S_e();tA();vWe();PWe();C_e();xWe();AWe();TWe();IWe();MWe()});var NWe,RWe,jWe,sY=w(()=>{NWe=Symbol("Let zodToJsonSchema decide on which parser to use"),RWe={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},jWe=t=>typeof t=="string"?{...RWe,name:t}:{...RWe,...t}});var DWe,O_e=w(()=>{sY();DWe=t=>{let e=jWe(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function P_e(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function to(t,e,r,n,o){t[e]=r,P_e(t,e,n,o)}var rA=w(()=>{});var Qf=w(()=>{aH();aH()});function LWe(){return{}}var E_e=w(()=>{});function FWe(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==re.ZodAny&&(r.items=br(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&to(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&to(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(to(r,"minItems",t.exactLength.value,t.exactLength.message,e),to(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var T_e=w(()=>{Qf();rA();nu()});function kWe(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?to(r,"minimum",n.value,n.message,e):to(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),to(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?to(r,"maximum",n.value,n.message,e):to(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),to(r,"maximum",n.value,n.message,e));break;case"multipleOf":to(r,"multipleOf",n.value,n.message,e);break}return r}var A_e=w(()=>{rA()});function $We(){return{type:"boolean"}}var I_e=w(()=>{});function uY(t,e){return br(t.type._def,e)}var lY=w(()=>{nu()});var zWe,M_e=w(()=>{nu();zWe=(t,e)=>br(t.innerType._def,e)});function R_e(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,i)=>R_e(t,e,o))};switch(n){case"
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-08-12 16:40:13 +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 $_e,Xy,qhr,dY=w(()=>{rA();Xy={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:()=>($_e===void 0&&($_e=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),$_e),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-_]*$/};qhr=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function fY(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===re.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:br(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:br(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===re.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=cY(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===re.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===re.ZodBranded&&t.keyType._def.type._def.typeName===re.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=uY(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var pY=w(()=>{Qf();nu();dY();lY()});function KWe(t,e){if(e.mapStrategy==="record")return fY(t,e);let r=br(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=br(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 B_e=w(()=>{nu();pY()});function GWe(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 U_e=w(()=>{});function JWe(){return{not:{}}}var q_e
Known schemas:
- ${Object.keys(n).join(`
- `)}`,new Error(Pe)}let ue=`${s}/$ref`,pe=da(t,Ne,r,n,o,i,a,ue,u);if(pe.valid||ce.push({instanceLocation:a,keyword:"$ref",keywordLocation:ue,error:"A subschema had errors."},...pe.errors),r==="4"||r==="7")return{valid:ce.length===0,errors:ce}}if(Array.isArray(m)){let Ze=m.length,Ne=!1;for(let ue=0;ue<Ze;ue++)if(c===m[ue]||m[ue]==="integer"&&c==="number"&&t%1===0&&t===t){Ne=!0;break}Ne||ce.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)&&ce.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m}".`}):m!==void 0&&c!==m&&ce.push({instanceLocation:a,keyword:"type",keywordLocation:`${s}/type`,error:`Instance type "${c}" is invalid. Expected "${m}".`});if(h!==void 0&&(c==="object"||c==="array"?jO(t,h)||ce.push({instanceLocation:a,keyword:"const",keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):t!==h&&ce.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(Ze=>jO(t,Ze))||ce.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`}):b.some(Ze=>t===Ze)||ce.push({instanceLocation:a,keyword:"enum",keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(b)}.`})),y!==void 0){let Ze=`${s}/not`;da(t,y,r,n,o,i,a,Ze).valid&&ce.push({instanceLocation:a,keyword:"not",keywordLocation:Ze,error:'Instance matched "not" schema.'})}let qt=[];if(x!==void 0){let Ze=`${s}/anyOf`,Ne=ce.length,ue=!1;for(let pe=0;pe<x.length;pe++){let Pe=x[pe],Ae=Object.create(u),ot=da(t,Pe,r,n,o,p===!0?i:null,a,`${Ze}/${pe}`,Ae);ce.push(...ot.errors),ue=ue||ot.valid,ot.valid&&qt.push(Ae)}ue?ce.length=Ne:ce.splice(Ne,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:Ze,error:"Instance does not match any subschemas."})}if(S!==void 0){let Ze=`${s}/allOf`,Ne=ce.length,ue=!0;for(let pe=0;pe<S.length;pe++){let Pe=S[pe],Ae=Object.create(u),ot=da(t,Pe,r,n,o,p===!0?i:null,a,`${Ze}/${pe}`,Ae);ce.push(...ot.errors),ue=ue&&ot.valid,ot.valid&&qt.push(Ae)}ue?ce.length=Ne:ce.splice(Ne,0,{instanceLocation:a,keyword:"allOf",keywordLocation:Ze,error:"Instance does not match every subschema."})}if(O!==void 0){let Ze=`${s}/oneOf`,Ne=ce.length,ue=O.filter((pe,Pe)=>{let Ae=Object.create(u),ot=da(t,pe,r,n,o,p===!0?i:null,a,`${Ze}/${Pe}`,Ae);return ce.push(...ot.errors),ot.valid&&qt.push(Ae),ot.valid}).length;ue===1?ce.length=Ne:ce.splice(Ne,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:Ze,error:`Instance does not match exactly one subschema (${ue} matches).`})}if((c==="object"||c==="array")&&Object.assign(u,...qt),E!==void 0){let Ze=`${s}/if`;if(da(t,E,r,n,o,i,a,Ze,u).valid){if(P!==void 0){let ue=da(t,P,r,n,o,i,a,`${s}/then`,u);ue.valid||ce.push({instanceLocation:a,keyword:"if",keywordLocation:Ze,error:'Instance does not match "then" schema.'},...ue.errors)}}else if(A!==void 0){let ue=da(t,A,r,n,o,i,a,`${s}/else`,u);ue.valid||ce.push({instanceLocation:a,keyword:"if",keywordLocation:Ze,error:'Instance does not match "else" schema.'},...ue.errors)}}if(c==="object"){if(g!==void 0)for(let pe of g)pe in t||ce.push({instanceLocation:a,keyword:"required",keywordLocation:`${s}/required`,error:`Instance does not have required property "${pe}".`});let Ze=Object.keys(t);if(k!==void 0&&Ze.length<k&&ce.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${k} properties.`}),H!==void 0&&Ze.length>H&&ce.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${H} properties.`}),V!==void 0){let pe=`${s}/propertyNames`;for(let Pe in t){let Ae=`${a}/${Hm(Pe)}`,ot=da(Pe,V,r,n,o,i,Ae,pe);ot.valid||ce.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:pe,error:`Property name "${Pe}" does not
2025-07-05 20:48:33 +08:00
data: ${JSON.stringify(o)}
`));n.enqueue(e.encode(`event: end
2025-08-12 16:40:13 +08:00
`)),n.close()}});return af.fromReadableStream(r)}var xKe=w(()=>{L_()});function uve(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}function _Y(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function*lve(t,e){for(;;){let{value:r,done:n}=Yc.runWithConfig(Up(t),e.next.bind(e),!0);if(n)break;yield r}}async function*vY(t,e){let r=e[Symbol.asyncIterator]();for(;;){let{value:n,done:o}=await Yc.runWithConfig(Up(t),r.next.bind(e),!0);if(o)break;yield n}}var SKe,CKe=w(()=>{sN();j_();SKe=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function"});function Ul(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function Ngr(t){if(nZ(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}function FO(t){if(typeof t=="function")return new tp({func:t});if(jn.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){let e={};for(let[r,n]of Object.entries(t))e[r]=FO(n);return new oA({steps:e})}else throw new Error(`Expected a Runnable, function or object.
Instead got an unsupported type.`)}function jgr(t,e){let r=e.name??t.getName(),n=e.description??nA(e.schema);return bY(e.schema)?new qH({name:r,description:n,schema:rn.object({input:rn.string()}).transform(o=>o.input),bound:t}):new qH({name:r,description:n,schema:e.schema,bound:t})}var cve,jn,$_,wY,UH,Pi,oA,dve,tp,xY,p$,SY,qH,sf=w(()=>{J7();cve=F(X7(),1);G1();Bye();nWe();iWe();Q1();L_();m_e();j_();o$();sWe();g_e();sN();vKe();xKe();CKe();qZ();LO();jn=class extends kp{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 $_({bound:this,kwargs:e,config:{}})}map(){return new wY({bound:this})}withRetry(e){return new UH({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new $_({bound:this,config:e,kwargs:{}})}withFallbacks(e){let r=Array.isArray(e)?e:e.fallbacks;return new xY({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(_n);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)=>_n(i===0?e:n))}return Array.from({length:r},()=>_n(e))}async batch(e,r,n){let o=this._getOptionsList(r??{},e.length),i=o[0]?.maxConcurrency??n?.maxConcurrency,a=new qm({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=_n(r),o=new NO({generator:this._streamIterator(e,n),config:n});return await o.setup,af.fromAsyncGenerator(o)}_separateRunnableConfigFromCallOptions(e){let r;e===void 0?r=_n(e):r=_n({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=_n(n),a=await(await Bp(o))?.handleChainStart(this.toJSON(),Ul(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 D_(u,n?.signal)}catch(u){throw await a?.handleChainError(u),u}return await a?.handleChainEnd(Ul(s,"output")),s}async _batchWithConfig(e,r,n,o){let i=this._getOptionsList(n??{},r.length),a=await Promise.all(i.map(Bp)),s=await Promise.all(a.map(async(l,c)=>{let d=await l?.handleChainStart(this.toJSON(),Ul(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 D_(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(Ul(u,"output")))),u}async*_transformStreamWithConfig(e,r,n){let o,i=!0,a,s=!0,u=_n(n),l=await Bp(u);async function*c(){for await(let f of e){if(i)if(o===void 0)o=f;else try{o=fc(o,f)}catch{o=void 0,i=!1}yield f}}let d;try{let f=await Q9e(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(oWe),m=f.output;p!==void 0&&d!==void 0&&(m=p.tapOutputIterable(d.runId,m));let h=d?.handlers.find(rWe);h!==void 0&&d!==void 0&&(m=h.tapOutputIterable(d.runId,m));for await(let b of m)if(yield b,s)if(
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
2025-08-12 16:40:13 +08:00
${JSON.stringify(Wp(this.schema))}
2025-07-05 20:48:33 +08:00
\`\`\`
2025-08-12 16:40:13 +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 f$(this.schema,JSON.parse(n))}catch(r){throw new Km(`Failed to parse. Text: "${e}". Error: ${r}`,e)}}}});var mve=w(()=>{qye()});var Qc,hve=w(()=>{iA();mve();Xbe();Qc=class extends pN{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?dZ(e,r):[{op:"replace",path:"",value:r}]}async parsePartialResult(e){return Ybe(e[0].text)}async parse(e){return Ybe(e,JSON.parse)}getFormatInstructions(){return""}}});var NKe=w(()=>{});var jKe=w(()=>{iA();mve();NKe()});var DKe=w(()=>{m$();AKe();IKe();MKe();RKe();iA();hve();jKe()});var eb=w(()=>{DKe()});var HH,h$,g$,PY,VH=w(()=>{Q1();OH();YT();HH=class extends kp{},h$=class extends HH{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 $s(this.value)]}},g$=class extends HH{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 Xf(this.messages)}toChatMessages(){return this.messages}},PY=class extends HH{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 $s({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}}});var kO,WH=w(()=>{VH();y$();kO=class extends z_{async formatPromptValue(e){let r=await this.format(e);return new h$(r)}}});function yve(t){return typeof t=="function"}function Lgr(t){return _$(t)?"array":typeof t}function gve(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function LKe(t,e){return t!=null&&typeof t=="object"&&e in t}function Fgr(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}function $gr(t,e){return kgr.call(t,e)}function Bgr(t){return!$gr(zgr,t)}function qgr(t){return String(t).replace(/[&<>"'`=\/]/g,function(r){return Ugr[r]})}function Ggr(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(Vgr,2)),!_$(A)||A.length!==2)throw new Error("Invalid tags: "+A);d=new RegExp(gve(A[0])+"\\s*"),f=new RegExp("\\s*"+gve(A[1])),p=new RegExp("\\s*"+gve("}"+A[1]))}m(e||lg.tags);for(var h=new GH(t),b,g,y,x,S,O;!h.eos();){if(b=h.pos,y=h.scanUntil(d),y)for(var E=0,P=y.length;E<P;++E)x=y.charAt(E),Bgr(x)?(i.push(o.length),u+=x):(s=!0,r=!0,u+=" "),o.push(["text",x,b,b+1]),b+=1,x===`
`&&(c(),u="",l=0,r=!1);if(!h.scan(d))break;if(a=!0,g=h.scan(Kgr)||"name",h.scan(Hgr),g==="="?(y=h.scanUntil(FKe),h.scan(FKe),h.scanUntil(f)):g==="{"?(y=h.scanUntil(p),h.scan(Wgr),h.scanUntil(f),g="&"):y=h.scanUntil(f),!h.scan(f))throw new Error("Unclosed tag at "+h.pos);if(g==">"?S=[g,y,b,h.pos,u,l,r]:S=[g,y,b,h.pos],l++,o.push(S),g==="#"||g==="^")n.push(S);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 Zgr(Jgr(o))}function Jgr(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 Zgr(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 GH(t){this.string=t,this.tail=t,this.pos=0}function b$(t,e){this.view=t,this.cache={".":this.view},this.parent=e}function rp(){this.templateCache={_cache:{},set:function(e,r){this._cache[e]=r},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}var Dgr,_$,kgr,zgr,Ugr,Hgr,Vgr,FKe,Wgr,Kgr,lg,KH,EY,kKe=w(()=>{Dgr=Object.prototype.toString,_$=Array.isArray||function(e){return Dgr.call(e)==="[object Array]"};kgr=RegExp.prototype.test;zgr=/\S/;Ugr={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};Hgr=/\s*/,Vgr=/\s+/,FKe=/\s*=/,Wgr=/\s*\}/,Kgr=/#|\^|\/|>|\{|&|=|!/;GH.prototype.eos=function(){return this.tail===""};GH.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};GH.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};b$.prototype.push=function(e){return new b$(e,this)};b$.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=LKe(i,a[s])||Fgr(i,a[s])),i=i[a[s++]];else i=o.view[e],u=LKe(o.view,e);if(u){n=i;break}o=o.parent}r[e]=n}return yve(n)&&(n=n.call(this.view)),n};rp.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};rp.prototype.parse=function(e,r){var n=this.templateCache,o=e+":"+(r||lg.tags).join(":"),i=typeof n<"u",a=i?n.get(o):void 0;return a==null&&(a=Ggr(e,r),i&&n.set(o,a)),a};rp.prototype.render=function(e,r,n,o){var i=this.getConfigTags(o),a=this.parse(e,i),s=r instanceof b$?r:new b$(r,void 0);return this.renderTokens(a,s,n,e,o)};rp.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};rp.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(_$(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(yve(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}};rp.prototype.renderInverted=function(e,r,n,o,i){var a=r.lookup(e[1]);if(!a||_$(a)&&a.length===0)return this.renderTokens(e[4],r,n,o,i)};rp.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-08-12 16:40:13 +08:00
`)};rp.prototype.renderPartial=function(e,r,n,o){if(n){var i=this.getConfigTags(o),a=yve(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)}}};rp.prototype.unescapedValue=function(e,r){var n=r.lookup(e[1]);if(n!=null)return n};rp.prototype.escapedValue=function(e,r,n){var o=this.getConfigEscape(n)||lg.escape,i=r.lookup(e[1]);if(i!=null)return typeof i=="number"&&o===lg.escape?String(i):o(i)};rp.prototype.rawValue=function(e){return e[1]};rp.prototype.getConfigTags=function(e){return _$(e)?e:e&&typeof e=="object"?e.tags:void 0};rp.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!_$(e))return e.escape};lg={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){KH.templateCache=t},get templateCache(){return KH.templateCache}},KH=new rp;lg.clearCache=function(){return KH.clearCache()};lg.parse=function(e,r){return KH.parse(e,r)};lg.render=function(e,r,n,o){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+Lgr(e)+'" was given as the first argument for mustache#render(template, view, partials)');return KH.render(e,r,n,o)};lg.escape=qgr;lg.Scanner=GH;lg.Context=b$;lg.Writer=rp;EY=lg});function $Ke(){EY.escape=t=>t}var JH,zKe,TY,Ygr,Xgr,bve,Qgr,Kp,ZH,mN,hN=w(()=>{kKe();xH();JH=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},zKe=t=>{let e=[];for(let r of t)if(r[0]==="name"){let n=r[1].includes(".")?r[1].split(".")[0]:r[1];e.push({type:"variable",name:n})}else if(["#","&","^",">"].includes(r[0])){if(e.push({type:"variable",name:r[1]}),r[0]==="#"&&r.length>4&&Array.isArray(r[4])){let n=zKe(r[4]);e.push(...n)}}else e.push({type:"literal",text:r[1]});return e},TY=t=>{$Ke();let e=EY.parse(t);return zKe(e)},Ygr=(t,e)=>JH(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},""),Xgr=(t,e)=>($Ke(),EY.render(t,e)),bve={"f-string":Ygr,mustache:Xgr},Qgr={"f-string":JH,mustache:TY},Kp=(t,e,r)=>{try{return bve[e](t,r)}catch(n){throw JT(n,"INVALID_PROMPT_INPUT")}},ZH=(t,e)=>Qgr[e](t),mN=(t,e,r)=>{if(!(e in bve)){let n=Object.keys(bve);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")Kp(o.text,e,n);else if(o.type==="image_url")if(typeof o.image_url=="string")Kp(o.image_url,e,n);else{let i=o.image_url.url;Kp(i,e,n)}else throw new Error(`Invalid message template received. ${JSON.stringify(o,null,2)}`)}):Kp(t,e,n)}catch(n){throw new Error(`Invalid prompt schema: ${n.message}`)}}});var _ve={};Qd(_ve,{PromptTemplate:()=>uf});var uf,v$=w(()=>{WH();hN();uf=class t extends kO{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))),mN(this.template,this.templateFormat,r)}}_getPromptType(){return"prompt"}async format(e){let r=await this.mergePartialAndUserVariables(e);return Kp(this.template,this.templateFormat,r)}static fromExamples(e,r,n,o=`
2025-07-05 20:48:33 +08:00
2025-08-12 16:40:13 +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 ZH(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 w$,vve=w(()=>{VH();y$();hN();w$=class t extends z_{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))),mN([{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]=Kp(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 PY(r)}}});function wve(t,e){let r=[];for(let n of Object.values(t))if(typeof n=="string")ZH(n,e).forEach(o=>{o.type==="variable"&&r.push(o.name)});else if(Array.isArray(n))for(let o of n)typeof o=="string"?ZH(o,e).forEach(i=>{i.type==="variable"&&r.push(i.name)}):typeof o=="object"&&r.push(...wve(o,e));else typeof n=="object"&&n!==null&&r.push(...wve(n,e));return Array.from(new Set(r))}function xve(t,e,r){let n={};for(let[o,i]of Object.entries(t))if(typeof i=="string")n[o]=Kp(i,r,e);else if(Array.isArray(i)){let a=[];for(let s of i)typeof s=="string"?a.push(Kp(s,r,e)):typeof s=="object"&&a.push(xve(s,e,r));n[o]=a}else typeof i=="object"&&i!==null?n[o]=xve(i,e,r):n[o]=i;return n}var YH,Sve=w(()=>{sf();hN();YH=class extends jn{static lc_name(){return"DictPromptTemplate"}constructor(e){let r=e.templateFormat??"f-string",n=wve(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 xve(this.template,e,this.template
2025-07-05 20:48:33 +08:00
2025-08-12 16:40:13 +08:00
`));throw a.name="InputFormatError",a.lc_error_code=o.lc_error_code,a}return n}},Cve=class extends XH{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)]}},QH=class extends z_{constructor(e){super(e)}async format(e){return(await this.formatPromptValue(e)).toString()}async formatPromptValue(e){let r=await this.formatMessages(e);return new g$(r)}},Ove=class extends Cve{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 ks(await this.prompt.format(e),this.role)}static fromTemplate(e,r,n){return new this(uf.fromTemplate(e,{templateFormat:n?.templateFormat}),r)}};e6=class extends XH{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(uf.fromTemplate(e,r));let n=[];for(let o of e)if(typeof o=="string")n.push(uf.fromTemplate(o,r));else if(o!==null)if(eyr(o)){let i="";typeof o.text=="string"&&(i=o.text??"");let a={...r,additionalContentFields:o};n.push(uf.fromTemplate(i,a))}else if(tyr(o)){let i=o.image_url??"",a,s=[];if(typeof i=="string"){let u;r?.templateFormat==="mustache"?u=TY(i):u=JH(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-08-12 16:40:13 +08:00
From: ${i}`);s=[l[0]]}else s=[];i={url:i},a=new w$({template:i,inputVariables:s,templateFormat:r?.templateFormat,additionalContentFields:o})}else if(typeof i=="object"){if("url"in i){let u;r?.templateFormat==="mustache"?u=TY(i.url):u=JH(i.url),s=u.flatMap(l=>l.type==="variable"?[l.name]:[])}else s=[];a=new w$({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 YH({template:o,templateFormat:r?.templateFormat}));return new this({prompt:n,additionalOptions:r})}async format(e){if(this.prompt instanceof kO){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 kO){let i=await n.format(o),a;"additionalContentFields"in n&&(a=n.additionalContentFields),r.push({...a,type:"text",text:i})}else if(n instanceof w$){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 YH){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)]}},U_=class extends e6{static _messageClass(){return $s}static lc_name(){return"HumanMessagePromptTemplate"}},Pve=class extends e6{static _messageClass(){return En}static lc_name(){return"AIMessagePromptTemplate"}},aA=class extends e6{static _messageClass(){return RO}static lc_name(){return"SystemMessagePromptTemplate"}};Gp=class t extends QH{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 zl))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 uf.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 zl)n.push(await this._parseImagePrompts(o,r));else{let i=o.inputVariables.reduce((s,u)=>{if(!(u in r)&&!(oyr(o)&&o.optional))throw JT(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=uf.fromTemplate(e,r),o=new U_({prompt:n});return this.fromMessages([o])}static fromMessages(e,r){let n=e.reduce((a,s)=>a.concat(s instanceof t?s.promptMessages:[nyr(s,r)]),[]
2025-07-05 20:48:33 +08:00
2025-08-12 16:40:13 +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))),mN(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 Kp(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 uf.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})}},Tve=class t extends QH{_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-08-12 16:40:13 +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))),mN(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 Kp(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 z_,y$=w(()=>{sf();z_=class extends jn{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(()=>(v$(),_ve));return r.deserialize(e)}case void 0:{let{PromptTemplate:r}=await Promise.resolve().then(()=>(v$(),_ve));return r.deserialize({...e,_type:"prompt"})}case"few_shot":{let{FewShotPromptTemplate:r}=await Promise.resolve().then(()=>(Ave(),BKe));return r.deserialize(e)}default:throw new Error(`Invalid prompt type in config: ${e._type}`)}}}});var UKe=w(()=>{y$();t6()});var qKe=w(()=>{});var HKe=w(()=>{sf();t6()});var VKe=w(()=>{y$();t6();Ave();UKe();v$();qKe();WH();hN();vve();HKe();Sve()});var sA=w(()=>{VKe()});var Jp=w(()=>{pve()});var Ive,Mve=w(()=>{Ive=t=>t.map(e=>e.pageContent).join(`
2025-07-05 20:48:33 +08:00
2025-08-12 16:40:13 +08:00
`)});var WKe=w(()=>{Mve()});function cg(t,e){let r=`atom${++iyr}`,n={toString(){return(Ia.env?Ia.env.MODE:void 0)!=="production"&&this.debugLabel?r+":"+this.debugLabel:r}};return typeof t=="function"?n.read=t:(n.init=t,n.read=ayr,n.write=syr),e&&(n.write=e),n}function ayr(t){return t(this)}function syr(t,e,r){return e(this,typeof r=="function"?r(t(this)):r)}var Ia,iyr,KKe,Rve,Nve,IY,Dve,uyr,lyr,Lve,GKe,AY,YKe,JKe,x$,jve,cyr,dyr,ZKe,uA,XKe,S$,r6,QKe,Fve=w(()=>{Ia={},iyr=0;KKe=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,Rve=t=>"init"in t,Nve=t=>!!t.write,IY=new WeakMap,Dve=t=>{var e;return Lve(t)&&!((e=IY.get(t))!=null&&e[1])},uyr=(t,e)=>{let r=IY.get(t);if(r)r[1]=!0,r[0].forEach(n=>n(e));else if((Ia.env?Ia.env.MODE:void 0)!=="production")throw new Error("[Bug] cancelable promise not found")},lyr=t=>{if(IY.has(t))return;let e=[new Set,!1];IY.set(t,e);let r=()=>{e[1]=!0};t.then(r,r),t.onCancel=n=>{e[0].add(n)}},Lve=t=>typeof t?.then=="function",GKe=t=>"v"in t||"e"in t,AY=t=>{if("e"in t)throw t.e;if((Ia.env?Ia.env.MODE:void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},YKe=(t,e,r)=>{r.p.has(t)||(r.p.add(t),e.then(()=>{r.p.delete(t)},()=>{r.p.delete(t)}))},JKe=(t,e,r,n,o)=>{var i;if((Ia.env?Ia.env.MODE:void 0)!=="production"&&n===e)throw new Error("[Bug] atom cannot depend on itself");r.d.set(n,o.n),Dve(r.v)&&YKe(e,r.v,o),(i=o.m)==null||i.t.add(e),t&&cyr(t,n,e)},x$=()=>[new Map,new Map,new Set],jve=(t,e,r)=>{t[0].has(e)||t[0].set(e,new Set),t[1].set(e,r)},cyr=(t,e,r)=>{let n=t[0].get(e);n&&n.add(r)},dyr=(t,e)=>t[0].get(e),ZKe=(t,e)=>{t[2].add(e)},uA=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},XKe=(...[t,e,r,n])=>{let o;(Ia.env?Ia.env.MODE:void 0)!=="production"&&(o=new Set);let i=(x,S,O)=>{let E="v"in S,P=S.v,A=Dve(S.v)?S.v:null;if(Lve(O)){lyr(O);for(let I of S.d.keys())YKe(x,O,t(I));S.v=O,delete S.e}else S.v=O,delete S.e;(!E||!Object.is(P,S.v))&&(++S.n,A&&uyr(A,O))},a=(x,S,O)=>{var E;let P=t(S);if(GKe(P)&&(P.m&&!O?.has(S)||Array.from(P.d).every(([$,k])=>a(x,$,O).n===k)))return P;P.d.clear();let A=!0,I=$=>{if(KKe(S,$)){let H=t($);if(!GKe(H))if(Rve($))i($,H,$.init);else throw new Error("no atom init");return AY(H)}let k=a(x,$,O);try{return AY(k)}finally{if(A)JKe(x,S,P,$,k);else{let H=x$();JKe(H,S,P,$,k),p(H,S,P),uA(H)}}},R,N,j={get signal(){return R||(R=new AbortController),R.signal},get setSelf(){return(Ia.env?Ia.env.MODE:void 0)!=="production"&&!Nve(S)&&console.warn("setSelf function cannot be used with read-only atom"),!N&&Nve(S)&&(N=(...$)=>{if((Ia.env?Ia.env.MODE:void 0)!=="production"&&A&&console.warn("setSelf function cannot be called in sync"),!A)return f(S,...$)}),N}};try{let $=e(S,I,j);if(i(S,P,$),Lve($)){(E=$.onCancel)==null||E.call($,()=>R?.abort());let k=()=>{if(P.m){let H=x$();p(H,S,P),uA(H)}};$.then(k,k)}return P}catch($){return delete P.v,P.e=$,++P.n,P}finally{A=!1}},s=x=>AY(a(void 0,x)),u=(x,S,O)=>{var E,P;let A=new Map;for(let I of((E=O.m)==null?void 0:E.t)||[])A.set(I,t(I));for(let I of O.p)A.set(I,t(I));return(P=dyr(x,S))==null||P.forEach(I=>{A.set(I,t(I))}),A};function l(x,S,O){let E=[],P=new Set,A=new Set,I=[[S,O]];for(;I.length>0;){let[R,N]=I[I.length-1];if(A.has(R)){I.pop();continue}if(P.has(R)){E.push([R,N,N.n]),A.add(R),I.pop();continue}P.add(R);for(let[j,$]of u(x,R,N))R!==j&&!P.has(j)&&I.push([j,$])}return[E,A]}let c=(x,S,O)=>{let[E,P]=l(x,S,O),A=new Set([S]);for(let I=E.length-1;I>=0;--I){let[R,N,j]=E[I],$=!1;for(let k of N.d.keys())if(k!==R&&A.has(k)){$=!0;break}$&&(a(x,R,P),p(x,R,N),j!==N.n&&(jve(x,R,N),A.add(R))),P.delete(R)}},d=(x,S,...O)=>{let E=!0,P=I=>AY(a(x,I)),A=(I,...R)=>{let N=t(I);try{if(KKe(S,I)){if(!Rve(I))throw new Error("atom not writable");let j=N.n,$=R[0];i(I,N,$),p(x,I,N),j!==N.n&&(jve(x,I,N),c(x,I,N));return}else return d(x,I,...R)}finally{E||uA(x)}};try{return r(S,P,A,...O)}finally{E=!1}},f=(x,...S)=>{let O=x$();tr
2025-07-05 20:48:33 +08:00
<user_custom_instructions>
${t}
2025-08-12 16:40:13 +08:00
</user_custom_instructions>`:e}function Iyr(t){return t.activeModels=gGe(t.activeModels,H_),t.activeEmbeddingModels=gGe(t.activeEmbeddingModels,yN),t}function Yr(t){return`${t.name}|${t.provider}`}function gGe(t,e){let r=new Map;return e.filter(n=>n.core).forEach(n=>{r.set(Yr(n),{...n})}),t.forEach(n=>{let o=Yr(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 ws,gN,er=w(()=>{a6();I1();Ur();ws=S$(),gN=cg(ed)});function J(...t){ae().debug&&console.log(...t)}function fe(...t){ae().debug&&console.error(...t)}function dg(...t){ae().debug&&console.warn(...t)}var Tn=w(()=>{er()});var xGe=v((Vve,O$)=>{(function(t,e){typeof Vve=="object"&&typeof O$<"u"?O$.exports=e():typeof define=="function"&&define.amd?define(e):t.moment=e()})(Vve,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 KHe(_,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=[],x=!1;function S(_,C){var T,M,L,X=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),X>0)for(T=0;T<X;T++)M=y[T],L=C[M],s(L)||(_[M]=L);return _}function O(_){S(this,_),this._d=new Date(_._d!=null?_._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),x===!1&&(x=!0,e.updateOffset(this),x=!1)}function E(_){return _ instanceof O||_!=null&&_._isAMomentObject!=null}function P(_){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,X,ge,ur=arguments.length;for(X=0;X<ur;X++){if(L="",typeof arguments[X]=="object"){L+=`
[`+X+"] ";for(ge in arguments[0])i(arguments[0],ge)&&(L+=ge+": "+arguments[0][ge]+", ");L=L.slice(0,-2)}else L=arguments[X];M.push(L)}P(_+`
2025-07-05 20:48:33 +08:00
Arguments: `+Array.prototype.slice.call(M).join("")+`
2025-08-12 16:40:13 +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[_]||(P(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 H;Object.keys?H=Object.keys:H=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 Z(_,C,T){var M=""+Math.abs(_),L=C-M.length,X=_>=0;return(X?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,z=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,B={},K={};function q(_,C,T,M){var L=M;typeof M=="string"&&(L=function(){return this[M]()}),_&&(K[_]=L),C&&(K[C[0]]=function(){return Z(L.apply(this,arguments),C[1],C[2])}),T&&(K[T]=function(){return this.localeData().ordinal(L.apply(this,arguments),_)})}function te(_){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]=te(C[T]);return function(L){var X="",ge;for(ge=0;ge<M;ge++)X+=N(C[ge])?C[ge].call(L,_):C[ge];return X}}function W(_,C){return _.isValid()?(C=Y(C,_.localeData()),B[C]=B[C]||U(C),B[C](_)):_.localeData().invalidDate()}function Y(_,C){var T=5;function M(L){return C.longDateFormat(L)||L}for(z.lastIndex=0;T>=0&&z.test(_);)_=_.replace(z,M),z.lastIndex=0,T-=1;return _}var se={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 Te(_){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 de="Invalid date";function Ue(){return this._invalidDate}var Ke="%d",at=/\d{1,2}/;function hr(_){return this._ordinal.replace("%d",_)}var Nn={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 De(_,C,T,M){var L=this._relativeTime[T];return N(L)?L(_,C,T,M):L.replace(/%d/i,_)}function _t(_,C){var T=this._relativeTime[_>0?"future":"past"];return N(T)?T(C):T.replace(/%s/i,C)}var Oe={};function $e(_,C){var T=_.toLowerCase();Oe[T]=Oe[T+"s"]=Oe[C]=_}function ce(_){return typeof _=="string"?Oe[_]||Oe[_.toLowerCase()]:void 0}function qt(_){var C={},T,M;for(M in _)i(_,M)&&(T=ce(M),T&&(C[T]=_[M]));return C}var Ze={};function Ne(_,C){Ze[_]=C}function ue(_){var C=[],T;for(T in _)i(_,T)&&C.push({unit:T,priority:Ze[T]});return C.sort(function(M,L){return M.priority-L.priority}),C}function pe(_){return _%4===0&&_%100!==0||_%400===0}function Pe(_){return _<0?Math.ceil(_)||0:Math.floor(_)}function Ae(_){var C=+_,T=0;return C!==0&&isFinite(C)&&(T=Pe(C)),T}function ot(_,C){return function(T){return T!=null?(ua(this,_,T),e.updateOffset(this,C),this):Nr(this,_)}}function Nr(_,C){return _.isValid()?_._d["get"+(_._isUTC?"UTC":"")+C]():NaN}function ua(_,C,T){_.isValid()&&!isNaN(T)&&(C==="FullYear"&&pe(_.year())
2025-07-05 20:48:33 +08:00
${t?.cause?"more message: "+t.cause.message:""}
2025-08-12 16:40:13 +08:00
${e?t.stack:""}`:JSON.stringify(t)}function s6(t,e){let r={...t};return e.forEach(n=>{delete r[n]}),r}function LY(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 V_(t){let e=A$[t];return{...e,label:e.label||t}}function op(t,e){let r=A$[t]?.label||t;return r+(e?.believerExclusive&&r==="Copilot Plus"?"(Believer)":"")}async function u6(t,e=!1){let r=app.workspace.getMostRecentLeaf();if(!r){new fg.Notice("No active leaf found.");return}if(r.view instanceof fg.MarkdownView||(r=app.workspace.getLeaf(!1),await r.setViewState({type:"markdown",state:r.view.getState()})),!(r.view instanceof fg.MarkdownView)){new fg.Notice("Failed to open a markdown view.");return}let n=r.view.editor,o=n.getCursor("from"),i=n.getCursor("to"),a=wN(t);e?n.replaceRange(a,o,i):n.replaceRange(a,i),new fg.Notice("Message inserted into the active note.")}function FY(t,e){let r;return(...n)=>{clearTimeout(r),r=setTimeout(()=>t(...n),e)}}function kY(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 RGe(){try{return{version:(await(0,fg.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 l6(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 Dyr(t){return typeof t=="string"?t.startsWith("gpt-5"):(t.modelName||t.model||"").startsWith("gpt-5")}function ewe(t){let e=typeof t=="string"?t:t.modelName||t.model||"",r=l6(e),n=Dyr(e),o=e.startsWith("claude-3-7-sonnet")||e.startsWith("claude-sonnet-4");return{isOSeries:r,isGPT5:n,isThinkingEnabled:o}}function $Y(t,e="system"){return l6(t)?"human":e}function twe(){let t=["3rd party (openai-format)","ollama","lm-studio","azure openai","copilot-plus","copilot-plus-jina"];return Object.entries(A$).filter(([e])=>!t.includes(e)).map(([e])=>e)}function T$(t,e){let r=!!twe().find(i=>i===t.provider),n=W_[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 Lyr(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>e.text).join(""):String(t||"")}function wN(t){let r=Lyr(t).replace(/<think>[\s\S]*?<\/think>/g,"");return r=r.replace(/<think>[\s\S]*$/g,""),r.trim()}function NGe(){return crypto.randomUUID()}async function rb(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 Gve,fg,Wve,Jve,Ryr,Nyr,PGe,Bs,Xve,on=w(()=>{td();Ur();Tn();Gve=F(xGe()),fg=require("obsidian"),Wve={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}`};Jve=(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})};Ryr=t=>t.last.bound.modelName||t.last.bound.model,Nyr=t=>t.last.bound.retriever!==void 0,PGe=t=>Ryr(t)||Nyr(t),Bs=(t,e="local")=>{let r=(0,Gve.default)(t);return e==="utc"&&r.utc(),{fileName:r.format("YYYYMMDD_HHmmss"),display:r.format("YYYY/MM/DD HH:mm:ss"),epoch:r.valueOf()}};Xve=/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|shorts\/)|youtu\.be\/)([^\s&]+)/});var I$,rwe,c6,td=w(()=>{eb();sA();Jp();WKe();on();I$=class I${static createNewLLMChain(e){let{llm:r,memory:n,prompt:o,abortController:i}=e,a=r.bind({signal:i?.signal}),s=Pi.from([{input:u=>u.input,memory:()=>n.loadMemoryVariables({})},{input:u=>u.input,history:u=>u.memory.history},o,a]);return I$.instances.set("llm_chain",s),console.log("New LLM chain created."),s}static getLLMChainFromMap(e){let r=I$.instances.get("llm_chain");return r||(r=I$.createNewLLMChain(e)),r}static createConversationalRetrievalChain(e,r,n){let{llm:o,retriever:i,systemMessage:a}=e,u=uf.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}
2025-08-12 16:40:13 +08:00
Standalone question:`),c=uf.fromTemplate(`{system_message}
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}
`),d=b=>b.map(y=>`Human: ${y[0]}
Assistant: ${y[1]}`).join(`
2025-08-12 16:40:13 +08:00
`),f=Pi.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 OY,b=>{let g=wN(b);return n&&console.log("Standalone Question: ",g),g}]),p=async b=>(r(b),Ive(b)),m=Pi.from([{context:i.pipe(p),question:new Eo,system_message:()=>a},c,o]);return f.pipe(m)}};I$.instances=new Map;rwe=I$,c6=rwe});var d6=w(()=>{});var dA,xs,Ei,mg,jGe,DGe,vGe,wGe,f6,zY,FGe,nwe,kGe,owe,iwe,K_,zO,pg,$O,fA,H_,cA,yN,Kve,A$,W_,$Ge,qr,awe,hg,ed,gg,Ur=w(()=>{I1();td();d6();dA="https://api.brevilabs.com/v1",xs="copilot-chat-view",Ei="user",mg="ai",jGe="copilot-conversations",DGe="copilot-custom-prompts",vGe=`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-08-12 16:40:13 +08:00
13. If the user mentions "tags", it most likely means tags in Obsidian note properties.`,wGe=`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-08-12 16:40:13 +08:00
- Edge fromNode and toNode must reference existing node IDs`,f6="note_context",zY=`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-08-12 16:40:13 +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.`,FGe=6e3,nwe=.4,kGe=.4,owe=15,iwe=448e3,K_={DEFAULT:"",READING_FILES:"Reading files",SEARCHING_WEB:"Searching the web",READING_FILE_TREE:"Reading file tree"},zO={SETTINGS:"settings",EXPIRED_MODAL:"expired_modal",CHAT_MODE_SELECT:"chat_mode_select",MODE_SELECT_TOOLTIP:"mode_select_tooltip"},pg={MAX_TOKENS:6e3,TEMPERATURE:.1},$O=(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))($O||{}),fA={reasoning:"This model supports general reasoning tasks.",vision:"This model supports image inputs.",websearch:"This model can access the internet."},H_=[{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-5",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"gpt-5-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"gpt-5-nano",provider:"openai",enabled:!0,isBuiltIn:!0,core:!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,capabilities:["vision"]},{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:"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:"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"]}],cA=(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))(cA||{}),yN=[{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},{name:"text-embedding-004",provider:"google",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"azure-openai",provider:"azure openai",enabled:!0,i
`+Dwe+t}var Lwe=!1;function Fwe(t,e){if(!t||Lwe)return"";Lwe=!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-08-12 16:40:13 +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{Lwe=!1,Error.prepareStackTrace=r}return(t=t?t.displayName||t.name:"")?P6(t):""}function Sbr(t){switch(t.tag){case 5:return P6(t.type);case 16:return P6("Lazy");case 13:return P6("Suspense");case 19:return P6("SuspenseList");case 0:case 2:case 15:return t=Fwe(t.type,!1),t;case 11:return t=Fwe(t.type.render,!1),t;case 1:return t=Fwe(t.type,!0),t;default:return""}}function s0e(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 z$:return"Fragment";case $$:return"Portal";case o0e:return"Profiler";case X0e:return"StrictMode";case i0e:return"Suspense";case a0e:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case B7e:return(t.displayName||"Context")+".Consumer";case z7e:return(t._context.displayName||"Context")+".Provider";case Q0e:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case exe:return e=t.displayName||null,e!==null?e:s0e(t.type)||"Memo";case yA:e=t._payload,t=t._init;try{return s0e(t(e))}catch{}}return null}function Cbr(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 s0e(e);case 8:return e===X0e?"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 MA(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function q7e(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function Obr(t){var e=q7e(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 nX(t){t._valueTracker||(t._valueTracker=Obr(t))}function H7e(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var r=e.getValue(),n="";return t&&(n=q7e(t)?t.checked?"true":"false":t.value),t=n,t!==r?(e.setValue(t),!0):!1}function MX(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 u0e(t,e){var r=e.checked;return Ya({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??t._wrapperState.initialChecked})}function DJe(t,e){var r=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;r=MA(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 V7e(t,e){e=e.checked,e!=null&&Y0e(t,"checked",e,!1)}function l0e(t,e){V7e(t,e);var r=MA(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")?c0e(t,e.type,r):e.hasOwnProperty("defaultValue")&&c0e(t,e.type,MA(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}function L
`).replace(N_r,"")}function hX(t,e,r){if(e=a7e(e),a7e(t)!==e&&r)throw Error(Ve(425))}function $X(){}var C0e=null,O0e=null;function P0e(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 E0e=typeof setTimeout=="function"?setTimeout:void 0,j_r=typeof clearTimeout=="function"?clearTimeout:void 0,s7e=typeof Promise=="function"?Promise:void 0,D_r=typeof queueMicrotask=="function"?queueMicrotask:typeof s7e<"u"?function(t){return s7e.resolve(null).then(t).catch(L_r)}:E0e;function L_r(t){setTimeout(function(){throw t})}function Kwe(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),H6(e);return}n--}else r!=="$"&&r!=="$?"&&r!=="$!"||n++;r=o}while(r);H6(e)}function PA(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 u7e(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 dz=Math.random().toString(36).slice(2),Q_="__reactFiber$"+dz,J6="__reactProps$"+dz,GO="__reactContainer$"+dz,T0e="__reactEvents$"+dz,F_r="__reactListeners$"+dz,k_r="__reactHandles$"+dz;function RN(t){var e=t[Q_];if(e)return e;for(var r=t.parentNode;r;){if(e=r[GO]||r[Q_]){if(r=e.alternate,e.child!==null||r!==null&&r.child!==null)for(t=u7e(t);t!==null;){if(r=t[Q_])return r;t=u7e(t)}return e}t=r,r=t.parentNode}return null}function o8(t){return t=t[Q_]||t[GO],!t||t.tag!==5&&t.tag!==6&&t.tag!==13&&t.tag!==3?null:t}function H$(t){if(t.tag===5||t.tag===6)return t.stateNode;throw Error(Ve(33))}function iQ(t){return t[J6]||null}var A0e=[],V$=-1;function jA(t){return{current:t}}function pa(t){0>V$||(t.current=A0e[V$],A0e[V$]=null,V$--)}function Yi(t,e){V$++,A0e[V$]=t.current,t.current=e}var RA={},mf=jA(RA),em=jA(!1),FN=RA;function oz(t,e){var r=t.type.contextTypes;if(!r)return RA;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 tm(t){return t=t.childContextTypes,t!=null}function zX(){pa(em),pa(mf)}function l7e(t,e,r){if(mf.current!==RA)throw Error(Ve(168));Yi(mf,e),Yi(em,r)}function NZe(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(Ve(108,Cbr(t)||"Unknown",o));return Ya({},r,n)}function BX(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||RA,FN=mf.current,Yi(mf,t),Yi(em,em.current),!0}function c7e(t,e,r){var n=t.stateNode;if(!n)throw Error(Ve(169));r?(t=NZe(t,e,FN),n.__reactInternalMemoizedMergedChildContext=t,pa(em),pa(mf),Yi(mf,t)):pa(em),Yi(em,r)}var qO=null,aQ=!1,Gwe=!1;function jZe(t){qO===null?qO=[t]:qO.push(t)}function $_r(t){aQ=!0,jZe(t)}function DA(){if(!Gwe&&qO!==null){Gwe=!0;var t=0,e=Ti;try{var r=qO;for(Ti=1;t<r.length;t++){var n=r[t];do n=n(!0);while(n!==null)}qO=null,aQ=!1}catch(o){throw qO!==null&&(qO=qO.slice(t+1)),iZe(rxe,DA),o}finally{Ti=e,Gwe=!1}}return null}var W$=[],K$=0,UX=null,qX=0,vg=[],wg=0,kN=null,HO=1,VO="";function IN(t,e){W$[K$++]=qX,W$[K$++]=UX,UX=t,qX=e}function DZe(t,e,r){vg[wg++]=HO,vg[wg++]=VO,vg[wg++]=kN,kN=t;var n=HO;t=VO;var o=32-lb(n)-1;n&=~(1<<o),r+=1;var i=32-lb(e)+o;if(30<i){var a=o-o%5;i=(n&(1<<a)-1).toString(32),n>>=a,o-=a,HO=1<<32-lb(e)+o|r<<o|n,VO=i+t}else HO=1<<i|r<<o|n,VO=t}function dxe(t){t.return!==null&&(IN(t,1),DZe(t,1,0))}function fxe(t){for(;t===UX;)UX=W$[--K$],W$[K$]=null,qX=W$[--K$],W$[K$]=null;for(;t===kN;)kN=vg[--wg],vg[wg]=null,VO=vg[--wg],vg[wg]=null,HO=vg[--wg],vg[wg]=null}var Zm=null,Jm=null,Ra=!1,ub=null;function LZe(t,e){var r=xg(5,null,null,0);r.elementT
2025-07-05 20:48:33 +08:00
Error generating stack: `+i.message+`
2025-08-12 16:40:13 +08:00
`+i.stack}return{value:t,source:e,stack:o,digest:null}}function Qwe(t,e,r){return{value:t,source:null,stack:r??null,digest:e??null}}function D0e(t,e){try{console.error(e.value)}catch(r){setTimeout(function(){throw r})}}var G_r=typeof WeakMap=="function"?WeakMap:Map;function cYe(t,e,r){r=WO(-1,r),r.tag=3,r.payload={element:null};var n=e.value;return r.callback=function(){YX||(YX=!0,V0e=n),D0e(t,e)},r}function dYe(t,e,r){r=WO(-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(){D0e(t,e)}}var i=t.stateNode;return i!==null&&typeof i.componentDidCatch=="function"&&(r.callback=function(){D0e(t,e),typeof n!="function"&&(TA===null?TA=new Set([this]):TA.add(this));var a=e.stack;this.componentDidCatch(e.value,{componentStack:a!==null?a:""})}),r}function v7e(t,e,r){var n=t.pingCache;if(n===null){n=t.pingCache=new G_r;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=uvr.bind(null,t,e,r),e.then(t,t))}function w7e(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 x7e(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=WO(-1,1),e.tag=2,EA(r,e,1))),r.lanes|=1),t):(t.flags|=65536,t.lanes=o,t)}var J_r=YO.ReactCurrentOwner,Qp=!1;function ap(t,e,r,n){e.child=t===null?qZe(e,null,r,n):az(e,t.child,r,n)}function S7e(t,e,r,n,o){r=r.render;var i=e.ref;return tz(e,o),n=Sxe(t,e,r,n,i,o),r=Cxe(),t!==null&&!Qp?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,ZO(t,e,o)):(Ra&&r&&dxe(e),e.flags|=1,ap(t,e,n,o),e.child)}function C7e(t,e,r,n,o){if(t===null){var i=r.type;return typeof i=="function"&&!jxe(i)&&i.defaultProps===void 0&&r.compare===null&&r.defaultProps===void 0?(e.tag=15,e.type=i,fYe(t,e,i,n,o)):(t=IX(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:W6,r(a,n)&&t.ref===e.ref)return ZO(t,e,o)}return e.flags|=1,t=IA(i,n),t.ref=e.ref,t.return=e,e.child=t}function fYe(t,e,r,n,o){if(t!==null){var i=t.memoizedProps;if(W6(i,n)&&t.ref===e.ref)if(Qp=!1,e.pendingProps=n=i,(t.lanes&o)!==0)(t.flags&131072)!==0&&(Qp=!0);else return e.lanes=t.lanes,ZO(t,e,o)}return L0e(t,e,r,n,o)}function pYe(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},Yi(Z$,Gm),Gm|=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,Yi(Z$,Gm),Gm|=t,null;e.memoizedState={baseLanes:0,cachePool:null,transitions:null},n=i!==null?i.baseLanes:r,Yi(Z$,Gm),Gm|=n}else i!==null?(n=i.baseLanes|r,e.memoizedState=null):n=r,Yi(Z$,Gm),Gm|=n;return ap(t,e,o,r),e.child}function mYe(t,e){var r=e.ref;(t===null&&r!==null||t!==null&&t.ref!==r)&&(e.flags|=512,e.flags|=2097152)}function L0e(t,e,r,n,o){var i=tm(r)?FN:mf.current;return i=oz(e,i),tz(e,o),r=Sxe(t,e,r,n,i,o),n=Cxe(),t!==null&&!Qp?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,ZO(t,e,o)):(Ra&&n&&dxe(e),e.flags|=1,ap(t,e,r,o),e.child)}function O7e(t,e,r,n,o){if(tm(r)){var i=!0;BX(e)}else i=!1;if(tz(e,o),e.stateNode===null)EX(t,e),BZe(e,r,n),j0e(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=Cg(l):(l=tm(r)?FN:mf.current,l=oz(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)&&g7e(e,a,n,l),bA=!1;var f=e.memoizedState;a.state=f,WX(e,n,a,o),u=e.memoizedState,s!==n||f!==u||em.current||bA?(typeof c=="function"&&(N0e(e,r,c,n),u=e.memoizedState),(s=bA||h7e(e,r,s,n,f,u,l))?(d||typeof a.UNSAFE_componentWillMount!="funct
`)}});var ast=v(oee=>{"use strict";Object.defineProperty(oee,"__esModule",{value:!0});oee.CohereTimeoutError=void 0;var nSe=class t extends Error{constructor(){super("Timeout"),Object.setPrototypeOf(this,t.prototype)}};oee.CohereTimeoutError=nSe});var Hs=v(vz=>{"use strict";Object.defineProperty(vz,"__esModule",{value:!0});vz.CohereTimeoutError=vz.CohereError=void 0;var Hwr=ist();Object.defineProperty(vz,"CohereError",{enumerable:!0,get:function(){return Hwr.CohereError}});var Vwr=ast();Object.defineProperty(vz,"CohereTimeoutError",{enumerable:!0,get:function(){return Vwr.CohereTimeoutError}})});var sst=v(uv=>{"use strict";var Wwr=uv&&uv.__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]}),Kwr=uv&&uv.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Gwr=uv&&uv.__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)&&Wwr(e,t,r);return Kwr(e,t),e};Object.defineProperty(uv,"__esModule",{value:!0});uv.BadRequestError=void 0;var Jwr=Gwr(Hs()),oSe=class t extends Jwr.CohereError{constructor(e){super({message:"BadRequestError",statusCode:400,body:e}),Object.setPrototypeOf(this,t.prototype)}};uv.BadRequestError=oSe});var ust=v(lv=>{"use strict";var Zwr=lv&&lv.__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]}),Ywr=lv&&lv.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Xwr=lv&&lv.__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)&&Zwr(e,t,r);return Ywr(e,t),e};Object.defineProperty(lv,"__esModule",{value:!0});lv.UnauthorizedError=void 0;var Qwr=Xwr(Hs()),iSe=class t extends Qwr.CohereError{constructor(e){super({message:"UnauthorizedError",statusCode:401,body:e}),Object.setPrototypeOf(this,t.prototype)}};lv.UnauthorizedError=iSe});var lst=v(cv=>{"use strict";var e0r=cv&&cv.__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]}),t0r=cv&&cv.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),r0r=cv&&cv.__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)&&e0r(e,t,r);return t0r(e,t),e};Object.defineProperty(cv,"__esModule",{value:!0});cv.ForbiddenError=void 0;var n0r=r0r(Hs()),aSe=class t extends n0r.CohereError{constructor(e){super({message:"ForbiddenError",statusCode:403,body:e}),Object.setPrototypeOf(this,t.prototype)}};cv.ForbiddenError=aSe});var cst=v(dv=>{"use strict";var o0r=dv&&dv.__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]}),i0r=dv&&dv.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),a0r=dv&&dv.__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)&&o0r(e,t,
`));return r(o)}});var Fdt,Qxr,eSr,tSr,rSr,nSr,kdt=w(()=>{Fdt=async t=>{let e=t?.Bucket||"";if(typeof t.Bucket=="string"&&(t.Bucket=e.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),nSr(e)){if(t.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!rSr(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},Qxr=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,eSr=/(\d+\.){3}\d+/,tSr=/\.\./,rSr=t=>Qxr.test(t)&&!eSr.test(t)&&!tSr.test(t),nSr=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 $dt=w(()=>{kdt()});var zdt,Bdt=w(()=>{zdt=(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 Udt,qdt=w(()=>{Udt=async t=>{}});function Hdt(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 Vdt=w(()=>{});var GA,Wee=w(()=>{Vdt();GA=t=>{if(typeof t=="string")return GA(new URL(t));let{hostname:e,pathname:r,port:n,protocol:o,search:i}=t,a;return i&&(a=Hdt(i)),{hostname:e,port:n?parseInt(n):void 0,protocol:o,path:r,query:a}}});var Kee,Gee=w(()=>{Wee();Kee=t=>typeof t=="object"?"url"in t?GA(t.url):t:GA(t)});var Wdt,oSr,XSe=w(()=>{$dt();Bdt();qdt();Gee();Wdt=async(t,e,r,n)=>{if(!r.endpoint){let a=await Udt(r.serviceId||"");a&&(r.endpoint=()=>Promise.resolve(Kee(a)))}let o=await oSr(t,e,r);if(typeof r.endpointProvider!="function")throw new Error("config.endpointProvider is not set.");return r.endpointProvider(o,n)},oSr=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 zdt(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 Fdt(n),n}});var Kdt=w(()=>{XSe();Gee()});var Gdt,QSe=w(()=>{yb();XSe();Gdt=({config:t,instructions:e})=>(r,n)=>async o=>{let i=await Wdt(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=wv(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 Jdt,eCe=w(()=>{Jdt=(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 Zdt,tCe=w(()=>{Zdt=(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 kt(t,e,r){return{applyToStack:n=>{n.add(Jdt(t,r),iSr),n.add(Zdt(t,e),B8)}}}var iSr,B8,Ydt=w(()=>{eCe();tCe();iSr={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},B8={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}});var mo=w(()=>{eCe();Ydt();tCe()});var rCe,$t,Xdt=w(()=>{mo();QSe();rCe={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:B8.name},$t=(t,e)=>({applyToStack:r=>{r.addRelativeTo(Gdt({config:t,instructions:e}),rCe)}})});var Jee,Qdt=w(()=>{yb();Gee();Jee=t=>{let e=t.tls??!0,{endpoint:r}=t,n=r!=null?async()=>Kee(await hf(r)()):void 0;return{...t,endpoint:n,tls:e,isCustomEndpoint:!!r,useDualstackEndpoint:hf(t.useDualstackEndpoint??!1),useFipsEndpoint:hf(t.useFipsEndpoint??!1)}}});var eft=w(()=>{});var ro=w(()=>{Kdt();QSe();Xdt();Qdt();eft()});var aSr,Zee,tft=w(()=>{ro();Vee();aSr={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:rCe.name},Zee=(t,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:r})=>({applyToStack:n=>{n.addRelativeTo(YSe(t,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:r}),aSr)}})});var Ido,rft=w(()=>{mo();Vee();Ido={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:B8.name}});var nft=w(()=>{Vee();tft();rft()});var oft=w(()=>{});var ift=w(()=>{oft()});var aft=w(()=>{su()});var sft=w(()=>{});var uft=w(()=>{});function sSr(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return{...e,[r]:Array.isArray(n)?[...n]:n}},{})}var dj,lft=w(()=>{dj=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=sSr(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 cft=w(()=>{});var dft=w(()=>{});var fft=w(()=>{});var U8=w(()=>{ift();aft();sft();uft();lft();cft();dft();fft()});var uSr,lSr,pft,nCe=w(()=>{U8();su();yb();uSr=t=>e=>{throw e},lSr=(t,e)=>{},pft=t=>(e,r)=>async n=>{if(!dj.isInstance(n.request))return e(n);let i=wv(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||uSr)(a));return(u.successHandler||lSr)(l.response,a),l}});var bb,xv,q8,Yee=w(()=>{(function(t){t.STANDARD="standard",t.ADAPTIVE="adaptive"})(bb||(bb={}));xv=3,q8=bb.STANDARD});var mft,hft,gft,yft,bft=w(()=>{mft=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],hft=["TimeoutError","RequestTimeout","RequestTimeoutException"],gft=[500,502,503,504],yft=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"]});var cSr,Pz,Xee,_ft,H8=w(()=>{bft();cSr=t=>t.$metadata?.clockSkewCorrected,Pz=t=>t.$metadata?.h
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 QA(i);if(o==="hex")return Cpt(i);if(o===void 0||o==="utf8"||o==="utf-8")return ate(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(Ppt);if(e=!0,Ept(t))return n(t);if(xCe(t))return t;throw new Error(`Cannot transform payload to web stream, got ${t}`)}})},Ept=t=>typeof Blob=="function"&&t instanceof Blob});var Ipt=w(()=>{});var Mpt=w(()=>{});var CCe=w(()=>{_Ce();ipt();Apt();Ipt();Mpt();SCe()});var tI,Rpt=w(()=>{CCe();tI=async(t=new Uint8Array,e)=>{if(t instanceof Uint8Array)return mP.mutate(t);if(!t)return mP.mutate(new Uint8Array);let r=e.streamCollector(t);return mP.mutate(await r)}});var Et,OCe,Npt=w(()=>{fCe();su();Et=class{constructor(){this.middlewareStack=Iz()}static classBuilder(){return new OCe}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,[Cz]:{commandInstance:this,...l},...c},{requestHandler:h}=r;return f.resolve(b=>h.handle(b.request,n||{}),m)}},OCe=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 Et{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 ute,jpt=w(()=>{ute="***SensitiveInformation***"});var lte,Dpt=w(()=>{lte=(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 yj,ySr,Lpt,bSr,Fpt,kpt,$pt,PCe,_Sr,Nz,vn,zpt,Bpt,vSr,J8,Z8,ECe,Upt,qpt,Hpt,TCe=w(()=>{yj=t=>{if(t!=null){if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return String(e)!==String(t)&&Hpt.warn(qpt(`Expected number but observed string: ${t}`)),e}if(typeof t=="number")return t;throw new TypeError(`Expected number, got ${typeof t}: ${t}`)}},ySr=Math.ceil(34028234663852886e22),Lpt=t=>{let e=yj(t);if(e!==void 0&&!Number.isNaN(e)&&e!==1/0&&e!==-1/0&&Math.abs(e)>ySr)throw new TypeError(`Expected 32-bit float, got ${t}`);return e},bSr=t=>{if(t!=null){if(Number.isInteger(t)&&!Number.isNaN(t))return t;throw new TypeError(`Expected integer, got ${typeof t}: ${t}`)}},Fpt=t=>PCe(t,32),kpt=t=>PCe(t,
2025-07-05 20:48:33 +08:00
`).slice(0,5).filter(e=>!e.includes("stackTraceWarning")).join(`
2025-08-12 16:40:13 +08:00
`),Hpt={warn:console.warn}});var wSr,xSr,Vpt,SSr,Wpt,Cho,Oho,Pho,cte,Kpt,Eho,CSr,OSr,PSr,bj,ESr,TSr,ACe,Gpt=w(()=>{TCe();wSr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],xSr=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),Vpt=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=xSr.exec(t);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");let[r,n,o,i,a,s,u,l]=e,c=ECe(ACe(n)),d=bj(o,"month",1,12),f=bj(i,"day",1,31);return Kpt(c,d,f,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l})},SSr=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),Wpt=t=>{if(t==null)return;if(typeof t!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let e=SSr.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=ECe(ACe(n)),f=bj(o,"month",1,12),p=bj(i,"day",1,31),m=Kpt(d,f,p,{hours:a,minutes:s,seconds:u,fractionalMilliseconds:l});return c.toUpperCase()!="Z"&&m.setTime(m.getTime()-TSr(c)),m},Cho=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$/),Oho=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$/),Pho=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})$/),cte=t=>{if(t==null)return;let e;if(typeof t=="number")e=t;else if(typeof t=="string")e=zpt(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))},Kpt=(t,e,r,n)=>{let o=e-1;return OSr(t,o,r),new Date(Date.UTC(t,o,r,bj(n.hours,"hour",0,23),bj(n.minutes,"minute",0,59),bj(n.seconds,"seconds",0,60),ESr(n.fractionalMilliseconds)))},Eho=50*365*24*60*60*1e3,CSr=[31,28,31,30,31,30,31,31,30,31,30,31],OSr=(t,e,r)=>{let n=CSr[e];if(e===1&&PSr(t)&&(n=29),r>n)throw new TypeError(`Invalid day for ${wSr[e]} in ${t}: ${r}`)},PSr=t=>t%4===0&&(t%100!==0||t%400===0),bj=(t,e,r,n)=>{let o=Upt(ACe(t));if(o<r||o>n)throw new TypeError(`${e} must be between ${r} and ${n}, inclusive`);return o},ESr=t=>t==null?0:Bpt("0."+t)*1e3,TSr=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},ACe=t=>{let e=0;for(;e<t.length-1&&t.charAt(e)==="0";)e++;return e===0?t:t.slice(e)}});var jz,Qa,ICe=w(()=>{jz=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 ASr,dte,ISr,Jpt=w(()=>{ICe();ASr=({output:t,parsedBody:e,exceptionCtor:r,errorCode:n})=>{let o=ISr(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)},dte=t=>({output:e,parsedBody:r,errorCode:n})=>{ASr({output:e,parsedBody:r,exceptionCtor:t,errorCode:n})},ISr=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 fte,Zpt=w(()=>{fte=t=>{switch(t){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region
`);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}=Ate(r),u=new this.sha256(await this.getSigningKey(i,a,s,o));return u.update(oI(e)),_b(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=Tte(e),{longDate:c,shortDate:d}=Ate(r),f=Ote(d,u,a??this.service);l.headers[KCe]=c,s.sessionToken&&(l.headers[bht]=s.sessionToken);let p=await oV(l,this.sha256);!Nht(nV,l.headers)&&this.applyChecksum&&(l.headers[nV]=p);let m=Pte(l,o,n),h=await this.getSignature(c,f,this.getSigningKey(s,u,d,a),this.createCanonicalRequest(l,m,p));return l.headers[WCe]=`${Ste} Credential=${s.accessKeyId}/${f}, SignedHeaders=${Fht(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-08-12 16:40:13 +08:00
${XCe(e)}
2025-07-05 20:48:33 +08:00
${o.map(i=>`${i}:${r[i]}`).join(`
`)}
${o.join(";")}
2025-08-12 16:40:13 +08:00
${n}`}async createStringToSign(e,r,n){let o=new this.sha256;o.update(oI(n));let i=await o.digest();return`${Ste}
2025-07-05 20:48:33 +08:00
${e}
${r}
2025-08-12 16:40:13 +08:00
${_b(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 Mg(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(oI(i)),_b(await a.digest())}getSigningKey(e,r,n,o){return Eht(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")}},Ate=t=>{let e=Dht(t).replace(/[\-:]/g,"");return{longDate:e,shortDate:e.slice(0,8)}},Fht=t=>Object.keys(t).sort().join(";")});var $ht=w(()=>{kht();YCe();QCe();eOe();nOe();oOe();ZCe()});var Ite,zht=w(()=>{rI();$ht();Ite=t=>{let e;t.credentials&&(e=Omt(t.credentials,Cmt,DCe)),e||(t.credentialDefaultProvider?e=Fz(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=Fz(t.signer):t.regionInfoProvider?i=()=>Fz(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||iV;return new d(c)}):i=async a=>{a=Object.assign({},{name:"sigv4",signingName:t.signingName||t.defaultSigningName,signingRegion:await Fz(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||iV;return new c(l)},{...t,systemClockOffset:n,signingEscapePath:r,credentials:e,signer:i}}});var Bht=w(()=>{aht();sht();zht()});var Uht=w(()=>{Bht()});var qht=w(()=>{});var Hht=w(()=>{dr()});var Mte,iOe=w(()=>{dr();Mte=(t,e)=>tI(t,e).then(r=>e.utf8Encoder(r))});var Vs,Vht,Wht,Kht=w(()=>{iOe();Vs=(t,e)=>Mte(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{}}),Vht=async(t,e)=>{let r=await Vs(t,e);return r.message=r.message??r.Message,r},Wht=(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 Rte=v(hP=>{"use strict";var Ght=":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",ZSr=Ght+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",Jht="["+Ght+"]["+ZSr+"]*",YSr=new RegExp("^"+Jht+"$"),XSr=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},QSr=function(t){let e=YSr.exec(t);return!(e===null||typeof e>"u")};hP.isExist=function(t){return typeof t<"u"};hP.isEmptyObject=function(t){return Object.keys(t).length===0};hP.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]]}};hP.getValue=function(t){return hP.isExist(t)?t:""};hP.isName=QSr;hP.getAllMatches=XSr;hP.nameRegexp=Jht});var sOe=v(egt=>{"use strict";var aOe=Rte(),eCr={allowBooleanAttributes:!1,unpairedTags:[]};egt.validate=function(t,e){e=Object.assign({},eCr,e);let r=
`&&t[i]!=="\r";i++)u+=t[i];if(u=u.trim(),u[u.length-1]==="/"&&(u=u.substring(0,u.length-1),i--),!uCr(u)){let d;return u.trim().length===0?d="Invalid space after '<'.":d="Tag '"+u+"' is an invalid name.",Ws("InvalidTag",d,cp(t,i))}let l=nCr(t,i);if(l===!1)return Ws("InvalidAttr","Attributes for '"+u+"' have open quote.",cp(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=Qht(c,e);if(f===!0)n=!0;else return Ws(f.err.code,f.err.msg,cp(t,d+f.err.line))}else if(s)if(l.tagClosed){if(c.trim().length>0)return Ws("InvalidTag","Closing tag '"+u+"' can't have attributes or invalid starting.",cp(t,a));if(r.length===0)return Ws("InvalidTag","Closing tag '"+u+"' has not been opened.",cp(t,a));{let d=r.pop();if(u!==d.tagName){let f=cp(t,d.tagStartPos);return Ws("InvalidTag","Expected closing tag '"+d.tagName+"' (opened in line "+f.line+", col "+f.col+") instead of closing tag '"+u+"'.",cp(t,a))}r.length==0&&(o=!0)}}else return Ws("InvalidTag","Closing tag '"+u+"' doesn't have proper closing.",cp(t,i));else{let d=Qht(c,e);if(d!==!0)return Ws(d.err.code,d.err.msg,cp(t,i-c.length+d.err.line));if(o===!0)return Ws("InvalidXml","Multiple possible root nodes found.",cp(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=Xht(t,i);continue}else if(t[i+1]==="?"){if(i=Yht(t,++i),i.err)return i}else break;else if(t[i]==="&"){let d=aCr(t,i);if(d==-1)return Ws("InvalidChar","char '&' is not expected.",cp(t,i));i=d}else if(o===!0&&!Zht(t[i]))return Ws("InvalidXml","Extra text at the end",cp(t,i));t[i]==="<"&&i--}}else{if(Zht(t[i]))continue;return Ws("InvalidChar","char '"+t[i]+"' is not expected.",cp(t,i))}if(n){if(r.length==1)return Ws("InvalidTag","Unclosed tag '"+r[0].tagName+"'.",cp(t,r[0].tagStartPos));if(r.length>0)return Ws("InvalidXml","Invalid '"+JSON.stringify(r.map(i=>i.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return Ws("InvalidXml","Start tag expected.",1);return!0};function Zht(t){return t===" "||t===" "||t===`
`||t==="\r"}function Yht(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 Ws("InvalidXml","XML declaration allowed only at the start of the document.",cp(t,e));if(t[e]=="?"&&t[e+1]==">"){e++;break}else continue}return e}function Xht(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 tCr='"',rCr="'";function nCr(t,e){let r="",n="",o=!1;for(;e<t.length;e++){if(t[e]===tCr||t[e]===rCr)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 oCr=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function Qht(t,e){let r=aOe.getAllMatches(t,oCr),n={};for(let o=0;o<r.length;o++){if(r[o][1].length===0)return Ws("InvalidAttr","Attribute '"+r[o][2]+"' has no space in starting.",aV(r[o]));if(r[o][3]!==void 0&&r[o][4]===void 0)return Ws("InvalidAttr","Attribute '"+r[o][2]+"' is without value.",aV(r[o]));if(r[o][3]===void 0&&!e.allowBooleanAttributes)return Ws("InvalidAttr","boolean attribute '"+r[o][2]+"' is not allowed.",aV(r[o]));let i=r[o][2];if(!sCr(i))return Ws("InvalidAttr","Attribute '"+i+"' is an invalid name.",aV(r[o]));if(!n.hasOwnProperty(i))n[i]=1;else return Ws("InvalidAttr","Attribute '"+i+"' is repeated.",aV(r[o]))}return!0}function iCr(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 aCr(t,e){if(e++,t[e]===";")return-1;if(t[e]==="#")return e++,iCr(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 Ws(t,e,r){return{err:{code:t,msg:e,line:r.line||r,col:r.col}}}function sCr(t){return aOe.isName(t)}function uCr(t){return aOe.isName(t)}function cp(t,e){let r=t.substring(0,e).split(/\r?\n/);return{line:r.length,col:r[r.length-1].length+1}}function aV(t){return t.startIndex+t[1].length}});var rgt=v(uOe=>{var tgt={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}},lCr=function(t){return Object.assign({},tgt,t)};uOe.buildOptions=lCr;uOe.defaultOptions=tgt});var ogt=v((Y_o,ngt)=>{"use strict";var lOe=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})}};ngt.exports=lOe});var agt=v((X_o,igt)=>{var cCr=Rte();function dCr(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&&mCr(t,e))e+=7,[entityName,val,e]=fCr(t,e+1),val.indexOf("&")===-1&&(r[bCr(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(o&&hCr(t,e))e+=8;else if(o&&gCr(t,e))e+=8;else if(o&&yCr(t,e))e+=9;else if(pCr)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)bre
`);let e=new sV("!xml"),r=e,n="",o="";for(let i=0;i<t.length;i++)if(t[i]==="<")if(t[i+1]==="/"){let s=wj(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=dOe(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 sV(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=wj(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=CCr(t,i);this.docTypeEntities=s.entities,i=s.i}else if(t.substr(i+1,2)==="!["){let s=wj(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=dOe(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 sV(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 sV(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 sV(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 RCr(t,e,r){let n=this.options.updateTag(e.tagname,r,e[":@"]);n===!1||(typeof n=="string"&&(e.tagname=n),t.addChild(e))}var NCr=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 jCr(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 DCr(t,e,r){let n="*
`;function KCr(t,e){let r="";return e.format&&e.indentBy.length>0&&(r=WCr),bgt(t,e,"",r)}function bgt(t,e,r,n){let o="",i=!1;for(let a=0;a<t.length;a++){let s=t[a],u=GCr(s);if(u===void 0)continue;let l="";if(r.length===0?l=u:l=`${r}.${u}`,u===e.textNodeName){let m=s[u];JCr(l,e)||(m=e.tagValueProcessor(u,m),m=_gt(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=ygt(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=ygt(s[":@"],e),f=n+`<${u}${d}`,p=bgt(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 GCr(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 ygt(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=_gt(o,e),o===!0&&e.suppressBooleanAttributes?r+=` ${n.substr(e.attributeNamePrefix.length)}`:r+=` ${n.substr(e.attributeNamePrefix.length)}="${o}"`}return r}function JCr(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 _gt(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}vgt.exports=KCr});var Sgt=v((ovo,xgt)=>{"use strict";var ZCr=wgt(),YCr={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 iI(t){this.options=Object.assign({},YCr,t),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=eOr),this.processTextOrObjNode=XCr,this.options.format?(this.indentate=QCr,this.tagEndChar=`>
2025-07-05 20:48:33 +08:00
`,this.newLine=`
2025-08-12 16:40:13 +08:00
`):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}iI.prototype.build=function(t){return this.options.preserveOrder?ZCr(t,this.options):(Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t}),this.j2x(t,0).val)};iI.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}};iI.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 XCr(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)}iI.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}};iI.prototype.closeTag=function(t){let e="";return this.options.unpairedTags.indexOf(t)!==-1?this.options.suppressUnpairedNode||(e="/"):this.options.suppressEmptyNode?e="/":e=`></${t}`,e};iI.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}};iI.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 QCr(t){return this.options.indentBy.repeat(t)}function eOr(t){return t.startsWith(this.options.attributeNamePrefix)&&t!==this.options.textNodeName?t.substr(this.attrPrefixLen):!1}xgt.exports=iI});var Ogt=v((ivo,Cgt)=>{"use strict";var tOr=sOe(),rOr=ggt(),nOr=Sgt();Cgt.exports={XMLParser:rOr,XMLValidator:tOr,XMLBuilder:nOr}});v
2025-07-05 20:48:33 +08:00
`)?"":void 0});n.addEntity("#xD","\r"),n.addEntity("#10",`
2025-08-12 16:40:13 +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]),RCe(s)}return{}}),Egt=async(t,e)=>{let r=await Cv(t,e);return r.Error&&(r.Error.message=r.Error.message??r.Error.Message),r}});var Agt=w(()=>{qht();Hht();Kht();Tgt()});var xj=w(()=>{Hmt();Uht();Agt()});function oOr(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"cognito-identity",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function Nte(t){return{schemeId:"smithy.api#noAuth"}}var Igt,Mgt,Rgt,mOe=w(()=>{xj();yb();Igt=async(t,e,r)=>({operation:wv(e).operation,region:await hf(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});Mgt=t=>{let e=[];switch(t.operation){case"GetCredentialsForIdentity":{e.push(Nte(t));break}case"GetId":{e.push(Nte(t));break}case"GetOpenIdToken":{e.push(Nte(t));break}case"UnlinkIdentity":{e.push(Nte(t));break}default:e.push(oOr(t))}return e},Rgt=t=>({...Ite(t)})});var Ngt,jr,ha=w(()=>{Ngt=t=>({...t,useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"cognito-identity"}),jr={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}}});var Dgt,jgt=w(()=>{Dgt={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","downl
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-08-12 16:40:13 +08:00
- EKS container host 169.254.170.23 or [fd00:ec2::23]`,{logger:e})}}});var e_t=w(()=>{});var t_t=w(()=>{e_t()});var r_t=w(()=>{su()});var n_t=w(()=>{});var o_t=w(()=>{});function UOr(t){return Object.keys(t).reduce((e,r)=>{let n=t[r];return{...e,[r]:Array.isArray(n)?[...n]:n}},{})}var Ore,i_t=w(()=>{Ore=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=UOr(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 a_t=w(()=>{});var s_t=w(()=>{});var u_t=w(()=>{});var l_t=w(()=>{t_t();r_t();n_t();o_t();i_t();a_t();s_t();u_t()});function c_t(t){return new Ore({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 d_t(t,e){let n=await Tpt(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 Wl("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:Vpt(o.Expiration)}}if(t.statusCode>=400&&t.statusCode<500){let o={};try{o=JSON.parse(n)}catch{}throw Object.assign(new Wl(`Server responded with status: ${t.statusCode}`,{logger:e}),{Code:o.Code,Message:o.Message})}throw new Wl(`Server responded with status: ${t.statusCode}`,{logger:e})}var f_t=w(()=>{cP();l_t();dr();CCe()});var p_t,m_t=w(()=>{p_t=(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 lPe,h_t=w(()=>{G8();cP();Qbt();f_t();m_t();lPe=(t={})=>{t.logger?.debug("@aws-sdk/credential-provider-http - fromHttp");let e,r=t.credentialsFullUri;if(r)e=r;else throw new Wl("No HTTP credential provider host provided.",{logger:t.logger});let n=new URL(e);Xbt(n,t.logger);let o=new eI;return p_t(async()=>{let i=c_t(n);t.authorizationToken&&(i.headers.Authorization=t.authorizationToken);let a=await o.handle(i);return d_t(a.response)},t.maxRetries??3,t.timeout??1e3)}});var g_t=w(()=>{h_t()});function qOr(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sts",region:t.region},propertiesExtractor:(e,r)=>({signingProperties:{config:e,context:r}})}}function y_t(t){return{schemeId:"smithy.api#noAuth"}}var b_t,__t,HOr,v_t,cPe=w(()=>{xj();yb();dV();b_t=async(t,e,r)=>({operation:wv(e).operation,region:await hf(t.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});__t=t=>{let e=[];switch(t.operation){case"AssumeRoleWithSAML":{e.push(y_t(t));break}case"AssumeRoleWithWebIdentity":{e.push(y_t(t));break}default:e.push(qOr(t))}return e},HOr=t=>({...t,stsClientCtor:Rg}),v_t=t=>{let e=HOr(t);return{...Ite(e)}}});var w_t,yf,Tv=w(()=>{w_t=t=>({...t,useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,useGlobalEndpoint:t.useGlobalEndpoint??!1,defaultSigningName:"sts"}),yf={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 S_t,x_t=w(()=>{S_t={name:"@aws-sdk/client-sts",description:"AWS SDK for JavaScript Sts Client for Node.js, Br
`);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}=Sne(r),u=new this.sha256(await this.getSigningKey(i,a,s,o));return u.update((0,DV.toUint8Array)(e)),(0,wne.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,wSt.prepareRequest)(e),{longDate:c,shortDate:d}=Sne(r),f=(0,xne.createScope)(d,u,a??this.service);l.headers[cd.AMZ_DATE_HEADER]=c,s.sessionToken&&(l.headers[cd.TOKEN_HEADER]=s.sessionToken);let p=await(0,JEe.getPayloadHash)(l,this.sha256);!(0,uAr.hasHeader)(cd.SHA256_HEADER,l.headers)&&this.applyChecksum&&(l.headers[cd.SHA256_HEADER]=p);let m=(0,vSt.getCanonicalHeaders)(l,o,n),h=await this.getSignature(c,f,this.getSigningKey(s,u,d,a),this.createCanonicalRequest(l,m,p));return l.headers[cd.AUTH_HEADER]=`${cd.ALGORITHM_IDENTIFIER} Credential=${s.accessKeyId}/${f}, SignedHeaders=${xSt(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-08-12 16:40:13 +08:00
${(0,sAr.getCanonicalQuery)(e)}
2025-07-05 20:48:33 +08:00
${o.map(i=>`${i}:${r[i]}`).join(`
`)}
${o.join(";")}
2025-08-12 16:40:13 +08:00
${n}`}async createStringToSign(e,r,n){let o=new this.sha256;o.update((0,DV.toUint8Array)(n));let i=await o.digest();return`${cd.ALGORITHM_IDENTIFIER}
2025-07-05 20:48:33 +08:00
${e}
${r}
2025-08-12 16:40:13 +08:00
${(0,wne.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,DV.toUint8Array)(i)),(0,wne.toHex)(await a.digest())}getSigningKey(e,r,n,o){return(0,xne.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")}};Cne.SignatureV4=ZEe;var Sne=t=>{let e=(0,cAr.iso8601)(t).replace(/[\-:]/g,"");return{longDate:e,shortDate:e.slice(0,8)}},xSt=t=>Object.keys(t).sort().join(";")});var OSt=v(om=>{"use strict";Object.defineProperty(om,"__esModule",{value:!0});om.prepareRequest=om.moveHeadersToQuery=om.getPayloadHash=om.getCanonicalQuery=om.getCanonicalHeaders=void 0;var CSt=(Aj(),dc(Tj));CSt.__exportStar(SSt(),om);var dAr=UEe();Object.defineProperty(om,"getCanonicalHeaders",{enumerable:!0,get:function(){return dAr.getCanonicalHeaders}});var fAr=HEe();Object.defineProperty(om,"getCanonicalQuery",{enumerable:!0,get:function(){return fAr.getCanonicalQuery}});var pAr=VEe();Object.defineProperty(om,"getPayloadHash",{enumerable:!0,get:function(){return pAr.getPayloadHash}});var mAr=KEe();Object.defineProperty(om,"moveHeadersToQuery",{enumerable:!0,get:function(){return mAr.moveHeadersToQuery}});var hAr=GEe();Object.defineProperty(om,"prepareRequest",{enumerable:!0,get:function(){return hAr.prepareRequest}});CSt.__exportStar(zEe(),om)});var PSt=v(YEe=>{"use strict";Object.defineProperty(YEe,"__esModule",{value:!0});var gAr=(Aj(),dc(Tj));gAr.__exportStar(OSt(),YEe)});var ns=v((tRo,ESt)=>{"use strict";ESt.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 cB=v((rRo,One)=>{"use strict";var{AbortController:TSt,AbortSignal:yAr}=typeof self<"u"?self:typeof window<"u"?window:void 0;One.exports=TSt;One.exports.AbortSignal=yAr;One.exports.default=TSt});var LV=v((nRo,XEe)=>{"use strict";var dB=typeof Reflect=="object"?Reflect:null,ASt=dB&&typeof dB.apply=="funct
`;super(r),this.name="AggregateError",this.errors=e}};eTe.exports={AggregateError:QEe,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 AAr},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:IAr,deprecate(t,e){return t},addAbortListener:LV().addAbortListener||function(e,r){if(e===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);zSt(e,"signal"),MAr(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[OAr]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[PAr](){var o;(o=n)===null||o===void 0||o()}}},AbortSignalAny:EAr.any||function(e){if(e.length===1)return e[0];let r=new TAr,n=()=>r.abort();return e.forEach(o=>{zSt(o,"signals"),o.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{e.forEach(o=>o.removeEventListener("abort",n))},{once:!0}),r.signal}};eTe.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var mp=v((iRo,qSt)=>{"use strict";var{format:RAr,inspect:Tne,AggregateError:NAr}=vf(),jAr=globalThis.AggregateError||NAr,DAr=Symbol("kIsNodeError"),LAr=["string","function","number","object","Function","Object","boolean","bigint","symbol"],FAr=/^([A-Z][a-z0-9]*)+$/,kAr="__node_internal_",Ane={};function jj(t,e){if(!t)throw new Ane.ERR_INTERNAL_ASSERTION(e)}function BSt(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 $Ar(t,e,r){if(typeof e=="function")return jj(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 jj(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:RAr(e,...r)}function dd(t,e,r){r||(r=Error);class n extends r{constructor(...i){super($Ar(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[DAr]=!0,Ane[t]=n}function USt(t){let e=kAr+t.name;return Object.defineProperty(t,"name",{value:e}),t}function zAr(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new jAr([e,t],e.message);return r.code=e.code,r}return t||e}var tTe=class extends Error{constructor(e="The operation was aborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new Ane.ERR_INVALID_ARG_TYPE("options","Object",r);super(e,r),this.code="ABORT_ERR",this.name="AbortError"}};dd("ERR_ASSERTION","%s",Error);dd("ERR_INVALID_ARG_TYPE",(t,e,r)=>{jj(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)jj(typeof u=="string","All expected entries have to be of type string"),LAr.includes(u)?o.push(u.toLowerCase()):FAr.test(u)?i.push(u):(jj(u!=="object",'The value "object" should be written as "Object"'),a.push(u));if(i.length>0
`)>=0)return!1;return!0}function mjr(t,e){var r;if(t.indent===" ")r=" ";else if(typeof t.indent=="number"&&t.indent>0)r=zv.call(Array(t.indent+1)," ");else return null;return{base:r,prev:zv.call(Array(e+1),r)}}function vAe(t,e){if(t.length===0)return"";var r=`
`+e.prev+e.base;return r+zv.call(t,","+r)+`
`+e.prev}function ioe(t,e){var r=_Ae(t),n=[];if(r){n.length=t.length;for(var o=0;o<t.length;o++)n[o]=AP(t,o)?e(t[o],t):""}var i=typeof mAe=="function"?mAe(t):[],a;if(OB){a={};for(var s=0;s<i.length;s++)a["$"+i[s]]=i[s]}for(var u in t)AP(t,u)&&(r&&String(Number(u))===u&&u<t.length||OB&&a["$"+u]instanceof Symbol||(JPt.call(/[^\w$]/,u)?n.push(e(u,t)+": "+e(t[u],t)):n.push(u+": "+e(t[u],t))));if(typeof mAe=="function")for(var l=0;l<i.length;l++)ZPt.call(t,i[l])&&n.push("["+e(i[l])+"]: "+e(t[i[l]],t));return n}});var oEt=v((jRo,nEt)=>{"use strict";var hjr=QV(),gjr=Wj(),uoe=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},yjr=function(t,e){if(t){var r=uoe(t,e);return r&&r.value}},bjr=function(t,e,r){var n=uoe(t,e);n?n.value=r:t.next={key:e,next:t.next,value:r}},_jr=function(t,e){return t?!!uoe(t,e):!1},vjr=function(t,e){if(t)return uoe(t,e,!0)};nEt.exports=function(){var e,r={assert:function(n){if(!r.has(n))throw new gjr("Side channel does not contain "+hjr(n))},delete:function(n){var o=e&&e.next,i=vjr(e,n);return i&&o&&o===i&&(e=void 0),!!i},get:function(n){return yjr(e,n)},has:function(n){return _jr(e,n)},set:function(n,o){e||(e={next:void 0}),bjr(e,n,o)}};return r}});var CAe=v((DRo,iEt)=>{"use strict";iEt.exports=Object});var sEt=v((LRo,aEt)=>{"use strict";aEt.exports=Error});var lEt=v((FRo,uEt)=>{"use strict";uEt.exports=EvalError});var dEt=v((kRo,cEt)=>{"use strict";cEt.exports=RangeError});var pEt=v(($Ro,fEt)=>{"use strict";fEt.exports=ReferenceError});var hEt=v((zRo,mEt)=>{"use strict";mEt.exports=SyntaxError});var yEt=v((BRo,gEt)=>{"use strict";gEt.exports=URIError});var _Et=v((URo,bEt)=>{"use strict";bEt.exports=Math.abs});var wEt=v((qRo,vEt)=>{"use strict";vEt.exports=Math.floor});var SEt=v((HRo,xEt)=>{"use strict";xEt.exports=Math.max});var OEt=v((VRo,CEt)=>{"use strict";CEt.exports=Math.min});var EEt=v((WRo,PEt)=>{"use strict";PEt.exports=Math.pow});var AEt=v((KRo,TEt)=>{"use strict";TEt.exports=Math.round});var MEt=v((GRo,IEt)=>{"use strict";IEt.exports=Number.isNaN||function(e){return e!==e}});var NEt=v((JRo,REt)=>{"use strict";var wjr=MEt();REt.exports=function(e){return wjr(e)||e===0?e:e<0?-1:1}});var DEt=v((ZRo,jEt)=>{"use strict";jEt.exports=Object.getOwnPropertyDescriptor});var OAe=v((YRo,LEt)=>{"use strict";var loe=DEt();if(loe)try{loe([],"length")}catch{loe=null}LEt.exports=loe});var kEt=v((XRo,FEt)=>{"use strict";var coe=Object.defineProperty||!1;if(coe)try{coe({},"a",{value:1})}catch{coe=!1}FEt.exports=coe});var zEt=v((QRo,$Et)=>{"use strict";$Et.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 qEt=v((e1o,UEt)=>{"use strict";var BEt=typeof Symbol<"u"&&Symbol,xjr=zEt();UEt.exports=function(){return typeof BEt!="function"||typeof Symbol!="function"||typeof BEt("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:xjr()}});var PAe=v((t1o,HEt)=>{"use strict";HEt.exports=typeof Reflect<"u"&&Reflect.getPrototypeOf||null});var EAe=v((r1o,VEt)=>{"use strict";var Sjr=CAe();VEt.exports=Sjr.getPrototypeOf||null});var GEt=v((n1o,KEt)=>{"use strict";var Cjr="Function.prototype.bind called on incompatible ",Ojr=Object.prototype.toString,Pjr=Math.max,Ejr="[object Function]",WEt=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},Tjr=function(e,r){f
`,this.streamTerminator=n.streamTerminator):this.messageTerminator=n.messageTerminator,o?.addEventListener("abort",()=>this.controller.abort())}iterMessages(){return wAt(this,arguments,function*(){var r,n;this.controller.signal;let o=xAt(this.stream),i="",a=!1;try{for(var s=vAt(o),u;u=yield Sb(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 Sb(void 0);let f=yield Sb(this.parse(JSON.parse(d)));yield yield Sb(f),a=!1}}}catch(l){r={error:l}}finally{try{u&&!u.done&&(n=s.return)&&(yield Sb(n.call(s)))}finally{if(r)throw r.error}}})}[Symbol.asyncIterator](){return wAt(this,arguments,function*(){var r,n;try{for(var o=vAt(this.iterMessages()),i;i=yield Sb(o.next()),!i.done;){let a=i.value;yield yield Sb(a)}}catch(a){r={error:a}}finally{try{i&&!i.done&&(n=o.return)&&(yield Sb(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 lFr.RUNTIME.type==="node"&&typeof e<"u"&&(r+=Buffer.isBuffer(e)?e:Buffer.from(e));return r}};im.Stream=XAe;function xAt(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{next(){return _At(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 _At(this,void 0,void 0,function*(){let r=e.cancel();return e.releaseLock(),yield r,{done:!0,value:void 0}})},[Symbol.asyncIterator](){return this}}}im.readableStreamAsyncIterable=xAt});var SAt=v(Eoe=>{"use strict";Object.defineProperty(Eoe,"__esModule",{value:!0});Eoe.Stream=void 0;var dFr=QAe();Object.defineProperty(Eoe,"Stream",{enumerable:!0,get:function(){return dFr.Stream}})});var PAt=v((V1o,OAt)=>{"use strict";var eIe=Object.defineProperty,fFr=Object.getOwnPropertyDescriptor,pFr=Object.getOwnPropertyNames,mFr=Object.prototype.hasOwnProperty,hFr=(t,e)=>{for(var r in e)eIe(t,r,{get:e[r],enumerable:!0})},gFr=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of pFr(e))!mFr.call(t,o)&&o!==r&&eIe(t,o,{get:()=>e[o],enumerable:!(n=fFr(e,o))||n.enumerable});return t},yFr=t=>gFr(eIe({},"__esModule",{value:!0}),t),CAt={};hFr(CAt,{Blob:()=>vFr,File:()=>wFr,FormData:()=>_Fr});OAt.exports=yFr(CAt);var bFr=function(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:window}(),{FormData:_Fr,Blob:vFr,File:wFr}=bFr});var $At=v((W1o,kAt)=>{"use strict";var nIe=Object.defineProperty,xFr=Object.getOwnPropertyDescriptor,SFr=Object.getOwnPropertyNames,CFr=Object.prototype.hasOwnProperty,OFr=(t,e)=>{for(var r in e)nIe(t,r,{get:e[r],enumerable:!0})},PFr=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of SFr(e))!CFr.call(t,o)&&o!==r&&nIe(t,o,{get:()=>e[o],enumerable:!(n=xFr(e,o))||n.enumerable});return t},EFr=t=>PFr(nIe({},"__esModule",{value:!0}),t),oIe=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},Os=(t,e,r)=>(oIe(t,e,"read from private field"),r?r.call(t):e.get(t)),Uv=(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)},s5=(t,e,r,n)=>(oIe(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),tIe=(t,e,r)=>(oIe(t,e,"access private method"),r),NAt={};OFr(NAt,{FormDataEncoder:()=>DFr,isFile:()=>Yj,isFormData:()=>LAt});kAt.exports=EFr(NAt);var MP=t=>typeof t=="function",TFr=t=>MP(t[Symbol.asyncIterator]),EAt=65536;function*jAt(t){if(t.byteLength<=EAt){yield t;return}let e=0;for(;e<t.byteLength;){let r=Math.min(t.byteLength-e,EAt),n=t.buffer.slice(e,e+r);e+=n.byteLength,yield new Uint8Array(n)}}async function*AFr(t){let e=t.getReader();for(;;){let{done:r,value:n}=await e.read();if(r)break;yield n}}async function*TAt(t){for await(let e of t)yield*jAt(e)}var IFr=t=>{if(TFr(t))return TAt(t);if(MP(t.getReader))return TAt(AFr(t));throw new TypeError("Unsup
2025-07-05 20:48:33 +08:00
`||e===`
`&&n[r-1]!=="\r"?`\r
2025-08-12 16:40:13 +08:00
`:e),RFr=t=>Object.prototype.toString.call(t).slice(8,-1).toLowerCase();function IAt(t){if(RFr(t)!=="object")return!1;let e=Object.getPrototypeOf(t);return e==null?!0:(e.constructor&&e.constructor.toString())===Object.toString()}function MAt(t,e){if(typeof e=="string"){for(let[r,n]of Object.entries(t))if(e.toLowerCase()===r.toLowerCase())return n}}var NFr=t=>new Proxy(t,{get:(e,r)=>MAt(e,r),has:(e,r)=>MAt(e,r)!==void 0}),LAt=t=>!!(t&&MP(t.constructor)&&t[Symbol.toStringTag]==="FormData"&&MP(t.append)&&MP(t.getAll)&&MP(t.entries)&&MP(t[Symbol.iterator])),RAt=t=>String(t).replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/"/g,"%22"),Yj=t=>!!(t&&typeof t=="object"&&MP(t.constructor)&&t[Symbol.toStringTag]==="File"&&MP(t.stream)&&t.name!=null),jFr={enableAdditionalHeaders:!1},Toe={writable:!1,configurable:!1},MI,u5,Aoe,l5,Zj,c5,d5,Ioe,Moe,iIe,rIe,FAt,DFr=class{constructor(t,e,r){if(Uv(this,Moe),Uv(this,rIe),Uv(this,MI,`\r
`),Uv(this,u5,void 0),Uv(this,Aoe,void 0),Uv(this,l5,"-".repeat(2)),Uv(this,Zj,new TextEncoder),Uv(this,c5,void 0),Uv(this,d5,void 0),Uv(this,Ioe,void 0),!LAt(t))throw new TypeError("Expected first argument to be a FormData instance.");let n;if(IAt(e)?r=e:n=e,n||(n=MFr()),typeof n!="string")throw new TypeError("Expected boundary argument to be a string.");if(r&&!IAt(r))throw new TypeError("Expected options argument to be an object.");s5(this,d5,Array.from(t.entries())),s5(this,Ioe,{...jFr,...r}),s5(this,u5,Os(this,Zj).encode(Os(this,MI))),s5(this,Aoe,Os(this,u5).byteLength),this.boundary=`form-data-boundary-${n}`,this.contentType=`multipart/form-data; boundary=${this.boundary}`,s5(this,c5,Os(this,Zj).encode(`${Os(this,l5)}${this.boundary}${Os(this,l5)}${Os(this,MI).repeat(2)}`));let o={"Content-Type":this.contentType},i=tIe(this,rIe,FAt).call(this);i&&(this.contentLength=i,o["Content-Length"]=i),this.headers=NFr(Object.freeze(o)),Object.defineProperties(this,{boundary:Toe,contentType:Toe,contentLength:Toe,headers:Toe})}*values(){for(let[t,e]of Os(this,d5)){let r=Yj(e)?e:Os(this,Zj).encode(DAt(e));yield tIe(this,Moe,iIe).call(this,t,r),yield r,yield Os(this,u5)}yield Os(this,c5)}async*encode(){for(let t of this.values())Yj(t)?yield*IFr(t.stream()):yield*jAt(t)}[Symbol.iterator](){return this.values()}[Symbol.asyncIterator](){return this.encode()}};MI=new WeakMap;u5=new WeakMap;Aoe=new WeakMap;l5=new WeakMap;Zj=new WeakMap;c5=new WeakMap;d5=new WeakMap;Ioe=new WeakMap;Moe=new WeakSet;iIe=function(t,e){let r="";if(r+=`${Os(this,l5)}${this.boundary}${Os(this,MI)}`,r+=`Content-Disposition: form-data; name="${RAt(t)}"`,Yj(e)&&(r+=`; filename="${RAt(e.name)}"${Os(this,MI)}`,r+=`Content-Type: ${e.type||"application/octet-stream"}`),Os(this,Ioe).enableAdditionalHeaders===!0){let n=Yj(e)?e.size:e.byteLength;n!=null&&!isNaN(n)&&(r+=`${Os(this,MI)}Content-Length: ${n}`)}return Os(this,Zj).encode(`${r}${Os(this,MI).repeat(2)}`)};rIe=new WeakSet;FAt=function(){let t=0;for(let[e,r]of Os(this,d5)){let n=Yj(r)?r:Os(this,Zj).encode(DAt(r)),o=Yj(n)?n.size:n.byteLength;if(o==null||isNaN(o))return;t+=tIe(this,Moe,iIe).call(this,e,n).byteLength,t+=o,t+=Os(this,Aoe)}return String(t+Os(this,c5).byteLength)}});var BAt=v((G1o,zAt)=>{zAt.exports=typeof self=="object"?self.FormData:window.FormData});var UAt=v(vc=>{"use strict";var LFr=vc&&vc.__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]}),FFr=vc&&vc.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),HB=vc&&vc.__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)&&LFr(e,t,r);return FFr(e,t),e},RI=vc&&vc.__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(vc,"__esModule",{value:!0});vc.WebFormData=vc.Node16FormData=vc.Node18FormData=vc.newFormData=void 0;var Roe=NB();function aIe(t){return typeof t=="object"&&t!=null&&"name"in t}function kFr(){return RI(this,void 0,void 0,function*(){let t;return Roe.RUNTIME.type==="node"&&Roe.RUNTIME.parsedVersion!=null&&Roe.RUNTIME.parsedVersion>=18?t=new Noe:Roe.RUNTIME.type==="node"?t=new joe:t=new Doe,yield t.setup(),t})}vc.newFormData=kFr;var Noe=class{setup(){return RI(this,void 0,void 0,function*(){this.fd=new(yield Promise.resolve().then(()=>HB(PAt()))).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 RI(this,void 0,void 0,function*(){n==null&&aIe(r)&&(n=r.name),r instanceof(yield Promise.resolve().then
`)),{ok:!0,value:e}):n}}});var sIe=v($oe=>{"use strict";Object.defineProperty($oe,"__esModule",{value:!0});$oe.stringifyValidationError=void 0;function HFr(t){return t.path.length===0?t.message:`${t.path.join(" -> ")}: ${t.message}`}$oe.stringifyValidationError=HFr});var lIe=v(zoe=>{"use strict";Object.defineProperty(zoe,"__esModule",{value:!0});zoe.JsonError=void 0;var VFr=sIe(),uIe=class t extends Error{constructor(e){super(e.map(VFr.stringifyValidationError).join("; ")),this.errors=e,Object.setPrototypeOf(this,t.prototype)}};zoe.JsonError=uIe});var dIe=v(Boe=>{"use strict";Object.defineProperty(Boe,"__esModule",{value:!0});Boe.ParseError=void 0;var WFr=sIe(),cIe=class t extends Error{constructor(e){super(e.map(WFr.stringifyValidationError).join("; ")),this.errors=e,Object.setPrototypeOf(this,t.prototype)}};Boe.ParseError=cIe});var KAt=v(NI=>{"use strict";Object.defineProperty(NI,"__esModule",{value:!0});NI.transform=NI.optional=NI.getSchemaUtils=void 0;var KFr=fd(),GFr=lIe(),JFr=dIe();function fIe(t){return{optional:()=>VAt(t),transform:e=>WAt(t,e),parseOrThrow:(e,r)=>{let n=t.parse(e,r);if(n.ok)return n.value;throw new JFr.ParseError(n.errors)},jsonOrThrow:(e,r)=>{let n=t.json(e,r);if(n.ok)return n.value;throw new GFr.JsonError(n.errors)}}}NI.getSchemaUtils=fIe;function VAt(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:()=>KFr.SchemaType.OPTIONAL};return Object.assign(Object.assign({},e),fIe(e))}NI.optional=VAt;function WAt(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),fIe(r))}NI.transform=WAt});var uh=v(Bg=>{"use strict";Object.defineProperty(Bg,"__esModule",{value:!0});Bg.ParseError=Bg.JsonError=Bg.transform=Bg.optional=Bg.getSchemaUtils=void 0;var pIe=KAt();Object.defineProperty(Bg,"getSchemaUtils",{enumerable:!0,get:function(){return pIe.getSchemaUtils}});Object.defineProperty(Bg,"optional",{enumerable:!0,get:function(){return pIe.optional}});Object.defineProperty(Bg,"transform",{enumerable:!0,get:function(){return pIe.transform}});var ZFr=lIe();Object.defineProperty(Bg,"JsonError",{enumerable:!0,get:function(){return ZFr.JsonError}});var YFr=dIe();Object.defineProperty(Bg,"ParseError",{enumerable:!0,get:function(){return YFr.ParseError}})});var GAt=v(Uoe=>{"use strict";Object.defineProperty(Uoe,"__esModule",{value:!0});Uoe.date=void 0;var XFr=fd(),mIe=am(),QFr=RP(),ekr=uh(),tkr=/^([+-]?\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 rkr(){let t={parse:(e,{breadcrumbsPrefix:r=[]}={})=>typeof e!="string"?{ok:!1,errors:[{path:r,message:(0,mIe.getErrorMessageForIncorrectType)(e,"string")}]}:tkr.test(e)?{ok:!0,value:new Date(e)}:{ok:!1,errors:[{path:r,message:(0,mIe.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,mIe.getErrorMessageForIncorrectType)(e,"Date object")}]},getType:()=>XFr.SchemaType.DATE};return Object.assign(Object.assign({},(0,QFr.maybeSkipValidation)(t)),(0,ekr.getSchemaUtils)(t))}Uoe.date=rkr});var JAt=v(qoe=>{"use strict";Object.defineProperty(qoe,"__esModule",{value:!0});qoe.date=void 0;var nkr=GAt();Object.defineProperty(qoe,"date",{enumerable:!0,get:function(){return nkr.date}})});var NP=v(Hoe=>{"use strict";Object.defineProperty(Hoe,"__esModule",{value:!0});Hoe.createIdentitySchemaCreator=void 0;var okr=uh(),ikr=RP();function akr(t,e){return()=>{let r={parse:e,json:e,getType:()=>t};return Object.assign(Object.assign({},(0,ikr.maybeSkipValidation)(r)),(0,okr.getSchemaUtils)(r))}}Hoe.createIdentitySchemaCreator=akr});var YAt=v(Voe=>{"use stri
`);o.enqueue(s)}catch(i){o.error(i)}})},cancel(){var o;return y5(this,void 0,void 0,function*(){yield(o=r.return)===null||o===void 0?void 0:o.call(r)})}})}};uu.StreamUtils=EIe;function qIt(t,e){return _5(this,arguments,function*(){var n,o;if(!t.body)throw e?.abort(),new QB.CohereError({message:"Attempted to iterate over a response with no body"});let i=new TIe,a=new DI,s=AIe(t.body);try{for(var u=b5(rzr(s)),l;l=yield La(u.next()),!l.done;){let c=l.value;for(let d of a.decode(c)){let f=i.decode(d);f&&(yield yield La(f))}}}catch(c){n={error:c}}finally{try{l&&!l.done&&(o=u.return)&&(yield La(o.call(u)))}finally{if(n)throw n.error}}for(let c of a.flush()){let d=i.decode(c);d&&(yield yield La(d))}})}uu._iterSSEMessages=qIt;function rzr(t){return _5(this,arguments,function*(){var r,n;let o=new Uint8Array;try{for(var i=b5(t),a;a=yield La(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=nzr(o))!==-1;)yield yield La(o.slice(0,c)),o=o.slice(c)}}catch(s){r={error:s}}finally{try{a&&!a.done&&(n=i.return)&&(yield La(n.call(i)))}finally{if(r)throw r.error}}o.length>0&&(yield yield La(o))})}function nzr(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 TIe=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]=izr(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},DI=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 QB.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 QB.CohereError({message:`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`})}throw new QB.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}};uu.LineDecoder=DI;DI.NEWLINE_CHARS=new Set([`
`,"\r"]);DI.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function ozr(t){let e=new DI,r=[];for(let n of t)r.push(...e.decode(n));return r}uu._decodeChunks=ozr;function izr(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}function AIe(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{next(){return y5(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 y5(this,void 0,void 0,function*(){let r=e.cancel();return e.releaseLock(),yield r,{done:!0,value:void 0}})},[Symbol.asyncIterator](){return this}}}uu.readableStreamAsyncIterable=AIe});var IIe=v(qv=>{"use strict";var azr=qv&&qv.__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]}),szr=qv&&qv.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),uzr=qv&&qv.__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)&&azr(e,t,r);return szr(e,t),e};Object.defineProperty(qv,"__esModule",{value:!0});qv.V2ChatStreamRequestCitationMode=void 0;var lzr=uzr(G());qv.V2ChatStreamRequestCitationMode=lzr.serialization.enum_(["FAST","ACCURATE","OFF"])});var MIe=v(Hv=>{"use strict";var czr=Hv&&Hv.__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]}),dzr=Hv&&Hv.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),fzr=Hv&&Hv.__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)&&czr(e,t,r);return dzr(e,t),e};Object.defineProperty(Hv,"__esModule",{value:!0});Hv.V2ChatRequestCitationMode=void 0;var pzr=fzr(G());Hv.V2ChatRequestCitationMode=pzr.serialization.enum_(["FAST","ACCURATE","OFF"])});var eU=v(Vv=>{"use strict";var mzr=Vv&&Vv.__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]}),hzr=Vv&&Vv.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),gzr=Vv&&Vv.__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)&&mzr(e,t,r);return hzr(e,t),e};Object.defineProperty(Vv,"__esModule",{value:!0});Vv.TextContent=void 0;var VIt=gzr(G());Vv.TextContent=VIt.serialization.object({text:VIt.serialization.string()})});var RIe=v(Wv=>{"use strict";var yzr=Wv&&Wv.__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]}),bzr=Wv&&Wv.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),_zr=Wv&&Wv.__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)&&yzr(e,t,r);return bzr(e,t),e};Object.defineProperty(Wv,"__esModule",{value:!0});Wv.Content=void 0;var vzr=_zr(G()),wzr=eU();Wv.Content=vzr.serialization.union("type",{text:wzr.TextContent}).transform({
`)}}}}catch(x){a={error:x}}finally{try{h&&!h.done&&(s=m.return)&&(yield s.call(m))}finally{if(a)throw a.error}}for(let x of g.flush()){let S=(0,pi.parseAWSEvent)(x);if(S){let O=yield(0,pi.mapResponseFromBedrock)(c,u,S);y.push(JSON.stringify(O)+`
`)}}return y.end(),{ok:!0,body:y}}else{let b=yield p.body;return{ok:!0,body:yield(0,pi.mapResponseFromBedrock)(c,u,b)}}}catch(b){throw b}});pi.fetchOverride=vYr});var $P=v(tae=>{"use strict";Object.defineProperty(tae,"__esModule",{value:!0});tae.CohereEnvironment=void 0;tae.CohereEnvironment={Production:"https://api.cohere.com"}});var WI=v((m1t,rae)=>{(function(t,e,r){typeof rae<"u"&&rae.exports?rae.exports=r():typeof define=="function"&&define.amd?define(r):e[t]=r()})("urljoin",m1t,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 z1e=v(cm=>{"use strict";var wYr=cm&&cm.__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]}),xYr=cm&&cm.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),H5=cm&&cm.__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)&&wYr(e,t,r);return xYr(e,t),e},nae=cm&&cm.__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())})},SYr=cm&&cm.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(cm,"__esModule",{value:!0});cm.V2=void 0;var h1t=H5($P()),um=H5(G()),Es=H5(lP()),lm=H5(kP()),g1t=SYr(WI()),zP=H5(Hs()),$1e=class{constructor(e={}){this._options=e}chatStream(e,r){var n,o;return nae(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:um.fetcher)({url:(0,g1t.default)((o=yield um.Supplier.get(this._options.environment))!==null&&o!==void 0?o:h1t.CohereEnvironment.Production,"v2/chat"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield um.Supplier.get(this._options.clientName))!=null?yield um.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":um.RUNTIME.type,"X-Fern-Runtime-Version":um.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},lm.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 um.Stream({stream:i.body,parse:a=>nae(this,void 0,void 0,function*(){return lm.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 Es.BadRequestError(i.error.body);case 401:th
`}});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new Ee.BadRequestError(i.error.body);case 401:throw new Ee.UnauthorizedError(i.error.body);case 403:throw new Ee.ForbiddenError(i.error.body);case 404:throw new Ee.NotFoundError(i.error.body);case 422:throw new Ee.UnprocessableEntityError(dt.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new Ee.TooManyRequestsError(dt.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new Ee.ClientClosedRequestError(dt.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(dt.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(dt.GatewayTimeoutErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));default:throw new Vr.CohereError({statusCode:i.error.statusCode,body:i.error.body})}switch(i.error.reason){case"non-json":throw new Vr.CohereError({statusCode:i.error.statusCode,body:i.error.rawBody});case"timeout":throw new Vr.CohereTimeoutError;case"unknown":throw new Vr.CohereError({message:i.error.errorMessage})}})}chat(e,r){var n,o;return gm(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:xt.fetcher)({url:(0,Tb.default)((o=yield xt.Supplier.get(this._options.environment))!==null&&o!==void 0?o:Eb.CohereEnvironment.Production,"v1/chat"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield xt.Supplier.get(this._options.clientName))!=null?yield xt.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":xt.RUNTIME.type,"X-Fern-Runtime-Version":xt.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},dt.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 dt.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(dt.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new Ee.TooManyRequestsError(dt.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new Ee.ClientClosedRequestError(dt.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{
`}});if(i.error.reason==="status-code")switch(i.error.statusCode){case 400:throw new Ee.BadRequestError(i.error.body);case 401:throw new Ee.UnauthorizedError(i.error.body);case 403:throw new Ee.ForbiddenError(i.error.body);case 404:throw new Ee.NotFoundError(i.error.body);case 422:throw new Ee.UnprocessableEntityError(dt.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new Ee.TooManyRequestsError(dt.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new Ee.ClientClosedRequestError(dt.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(dt.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(dt.GatewayTimeoutErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));default:throw new Vr.CohereError({statusCode:i.error.statusCode,body:i.error.body})}switch(i.error.reason){case"non-json":throw new Vr.CohereError({statusCode:i.error.statusCode,body:i.error.rawBody});case"timeout":throw new Vr.CohereTimeoutError;case"unknown":throw new Vr.CohereError({message:i.error.errorMessage})}})}generate(e,r){var n,o;return gm(this,void 0,void 0,function*(){let i=yield((n=this._options.fetcher)!==null&&n!==void 0?n:xt.fetcher)({url:(0,Tb.default)((o=yield xt.Supplier.get(this._options.environment))!==null&&o!==void 0?o:Eb.CohereEnvironment.Production,"v1/generate"),method:"POST",headers:{Authorization:yield this._getAuthorizationHeader(),"X-Client-Name":(yield xt.Supplier.get(this._options.clientName))!=null?yield xt.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":xt.RUNTIME.type,"X-Fern-Runtime-Version":xt.RUNTIME.version},contentType:"application/json",requestType:"json",body:Object.assign(Object.assign({},dt.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 dt.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(dt.UnprocessableEntityErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 429:throw new Ee.TooManyRequestsError(dt.TooManyRequestsErrorBody.parseOrThrow(i.error.body,{unrecognizedObjectKeys:"passthrough",allowUnrecognizedUnionMembers:!0,allowUnrecognizedEnumValues:!0,skipValidation:!0,breadcrumbsPrefix:["response"]}));case 499:throw new Ee.ClientClosedRequestError(dt.ClientClosedRequestErrorBody.parseOrThrow(i.error.body,{u
`)),A1t=!0),new Ib(!0).update(t).hex())});function nC(t,e){e?(Sc[0]=Sc[16]=Sc[1]=Sc[2]=Sc[3]=Sc[4]=Sc[5]=Sc[6]=Sc[7]=Sc[8]=Sc[9]=Sc[10]=Sc[11]=Sc[12]=Sc[13]=Sc[14]=Sc[15]=0,this.blocks=Sc):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=t}var Ft,fXr,Mb,fae,Sc,M1t=w(()=>{"use strict";Ft="0123456789abcdef".split(""),fXr=[-2147483648,8388608,32768,128],Mb=[24,16,8,0],fae=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],Sc=[];nC.prototype.update=function(t){if(!this.finalized){var e,r=typeof t;if(r!=="string"){if(r==="object"){if(t===null)throw new Error(ERROR);if(ARRAY_BUFFER&&t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(!Array.isArray(t)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(t)))throw new Error(ERROR)}else throw new Error(ERROR);e=!0}for(var n,o=0,i,a=t.length,s=this.blocks;o<a;){if(this.hashed&&(this.hashed=!1,s[0]=this.block,this.block=s[16]=s[1]=s[2]=s[3]=s[4]=s[5]=s[6]=s[7]=s[8]=s[9]=s[10]=s[11]=s[12]=s[13]=s[14]=s[15]=0),e)for(i=this.start;o<a&&i<64;++o)s[i>>>2]|=t[o]<<Mb[i++&3];else for(i=this.start;o<a&&i<64;++o)n=t.charCodeAt(o),n<128?s[i>>>2]|=n<<Mb[i++&3]:n<2048?(s[i>>>2]|=(192|n>>>6)<<Mb[i++&3],s[i>>>2]|=(128|n&63)<<Mb[i++&3]):n<55296||n>=57344?(s[i>>>2]|=(224|n>>>12)<<Mb[i++&3],s[i>>>2]|=(128|n>>>6&63)<<Mb[i++&3],s[i>>>2]|=(128|n&63)<<Mb[i++&3]):(n=65536+((n&1023)<<10|t.charCodeAt(++o)&1023),s[i>>>2]|=(240|n>>>18)<<Mb[i++&3],s[i>>>2]|=(128|n>>>12&63)<<Mb[i++&3],s[i>>>2]|=(128|n>>>6&63)<<Mb[i++&3],s[i>>>2]|=(128|n&63)<<Mb[i++&3]);this.lastByteIndex=i,this.bytes+=i-this.start,i>=64?(this.block=s[16],this.start=i-64,this.hash(),this.hashed=!0):this.start=i}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};nC.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,e=this.lastByteIndex;t[16]=this.block,t[e>>>2]|=fXr[e&3],this.block=t[16],e>=56&&(this.hashed||this.hash(),t[0]=this.block,t[16]=t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=t[7]=t[8]=t[9]=t[10]=t[11]=t[12]=t[13]=t[14]=t[15]=0),t[14]=this.hBytes<<3|this.bytes>>>29,t[15]=this.bytes<<3,this.hash()}};nC.prototype.hash=function(){var t=this.h0,e=this.h1,r=this.h2,n=this.h3,o=this.h4,i=this.h5,a=this.h6,s=this.h7,u=this.blocks,l,c,d,f,p,m,h,b,g,y,x;for(l=16;l<64;++l)p=u[l-15],c=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,p=u[l-2],d=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,u[l]=u[l-16]+c+u[l-7]+d<<0;for(x=e&r,l=0;l<64;l+=4)this.first?(this.is224?(b=300032,p=u[0]-1413257819,s=p-150054599<<0,n=p+24177077<<0):(b=704751109,p=u[0]-210244248,s=p-1521486534<<0,n=p+143694565<<0),this.first=!1):(c=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),b=t&e,f=b^t&r^x,h=o&i^~o&a,p=s+d+h+fae[l]+u[l],m=c+f,s=n+p<<0,n=p+m<<0),c=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),g=n&t,f=g^n&e^b,h=a&s^~a&o,p=i+d+h+fae[l+1]+u[l+1],m=c+f,a=r+p<<0,r=p+m<<0,c=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),y=r&n,f=y^r&t^g,h=i&a^~i&s,p=o+d+h+fae[l+2]+u[l+2],m=c+f,i=e+p
`).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=j1t.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=rNe.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=rNe.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(..._Xr(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)}},mae=rNe;yXr(mae,"specialTokenRegex",t=>new RegExp(t.map(e=>vXr(e)).join("|"),"g"))});var L1t=w(()=>{D1t()});async function F1t(t){return t in hae||(hae[t]=wXr.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>new mae(e)).catch(e=>{throw delete hae[t],e})),await hae[t]}async function k1t(t){return F1t(nNe(t))}var hae,wXr,oNe=w(()=>{L1t();o$();hae={},wXr=new qm({})});function gd(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 xXr,SXr,CU,OU,t9=w(()=>{N1t();VH();YT();o$();oNe();sf();xXr=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;SXr=()=>!1,CU=class extends jn{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??SXr(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}},OU=class extends CU{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=pae.global():this.cache=void 0,this.caller=new qm(n??{})}async getNumTokens(e){let r;typeof e=="string"?r=e:r=e.map(o=>typeof o=="string"?o:o.type==="text"&&"text"in o?o.text:"").join("");let n=Math.ceil(r.length/4);if(!this._encoding)try{this._encoding=await k1t("modelName"in this?xXr(this.modelName):"gpt2")}catch(o){console.warn("Failed to calculate number of tokens, falling back to approximate count",o)}if(this._encoding)try{n=this._encoding.encode(r).length}catch(o){console.warn("Failed to calculate number of tokens, falling back to approximate count",o)}return n}static _convertInputToPromptValue(e){return typeof e=="string"?new h$(e):Array.isArr
`+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&i.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function yNt(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 xae(t){return!!t.finishReason&&HXr.includes(t.finishReason)}function ZI(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];xae(i)&&(o+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(o+=`: ${i.finishMessage}`))}return o}function n9(t){return this instanceof n9?(this.v=t,this):new n9(t)}function VXr(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 n9?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 WXr(t){let e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),r=JXr(e),[n,o]=r.tee();return{stream:GXr(n),response:KXr(o)}}async function KXr(t){let e=[],r=t.getReader();for(;;){let{done:n,value:o}=await r.read();if(n)return hNe(ZXr(e));e.push(o)}}function GXr(t){return VXr(this,arguments,function*(){let r=t.getReader();for(;;){let{value:n,done:o}=yield n9(r.read());if(o)break;yield yield n9(hNe(n))}})}function JXr(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 Pf("Failed to parse stream"));return}n.close();return}o+=a;let u=o.match(bNt),l;for(;u;){try{l=JSON.parse(u[1])}catch{n.error(new Pf(`Error parsing JSON response: "${u[1]}"`));return}n.enqueue(l),o=o.substring(u[0].length),u=o.match(bNt)}return i()})}}})}function ZXr(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 xNt(t,e,r,n){let o=await i9(e,xD.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(r),n);return WXr(o)}async function SNt(t,e,r,n){let i=await(await i9(e,xD.GENERATE_CONTENT,t,!1,JSON.stringify(r),n)).json();return{response:hNe(i)}}function CNt(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 o9(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 YXr(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 sC(t,e){if(!(this instanceof sC))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 Yl(e.headers),this.url=e.url||"",this._initBody(t)}function zNt(t,e){return new Promise(function(r,n){var o=new PD(t,e);if(o.signal&&o.signal.aborted)return n(new OD("Aborted","AbortError"));var i=new XMLHttpRequest;function a(){i.abort()}i.onload=function(){var l={statusText:i.statusText,headers:_Qr(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 sC(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 OD("Aborted","AbortError"))},0)};function s(l){try{return l===""&&bd.location.href?bd.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&&(bp.blob?i.responseType="blob":bp.arrayBuffer&&(i.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof Yl||bd.Headers&&e.headers instanceof bd.Headers)){var u=[];Object.getOwnPropertyNames(e.headers).forEach(function(l){u.push(EU(l)),i.setRequestHeader(l,wNe(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 bd,bp,DNt,FNt,gQr,vQr,OD,BNt=w(()=>{bd=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof window<"u"&&window||{},bp={searchParams:"URLSearchParams"in bd,iterable:"Symbol"in bd&&"iterator"in Symbol,blob:"FileReader"in bd&&"Blob"in bd&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in bd,arrayBuffer:"ArrayBuffer"in bd};bp.arrayBuffer&&(DNt=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],FNt=ArrayBuffer.isView||function(t){return t&&DNt.indexOf(Object.prototype.toString.call(t))>-1});Yl.prototype.append=function(t,e){t=EU(t),e=wNe(e);var r=this.map[t];this.map[t]=r?r+", "+e:e};Yl.prototype.delete=function(t){delete this.map[EU(t)]};Yl.prototype.get=function(t){return t=EU(t),this.has(t)?this.map[t]:null};Yl.prototype.has=function(t){return this.map.hasOwnProperty(EU(t))};Yl.prototype.set=function(t,e){this.map[EU(t)]=wNe(e)};Yl.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)};Yl.prototype.keys=function(){var t=[];return this.forEach(function(e,r){t.push(r)}),xNe(t)};Yl.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),xNe(t)};Yl.prototype.entries=function(){var t=[];return this.forEach(function(e,r){t.push([r,e])}),xNe(t)};bp.iterable&&(Yl.prototype[Symbol.iterator]=Yl.prototype.entries);gQr=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];PD.prototype.clone=function(){return new PD(this,{body:this._bodyInit})};$Nt.call(PD.prototype);$Nt.call(sC.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-08-12 16:40:13 +08:00
`).filter(i=>i!==""))try{yield JSON.parse(o)}catch{console.warn("invalid json: ",o)}},TQr=t=>{if(!t)return HNt;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=qNt);let o=`${r.protocol}//${r.hostname}:${n}${r.pathname}`;return o.endsWith("/")&&(o=o.slice(0,-1)),o},AQr=Object.defineProperty,IQr=(t,e,r)=>e in t?AQr(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,CNe=(t,e,r)=>(IQr(t,typeof e!="symbol"?e+"":e,r),r),AU=class{constructor(e){CNe(this,"config"),CNe(this,"fetch"),CNe(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e?.headers},e?.proxy||(this.config.host=TQr(e?.host??HNt)),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 TU(this.fetch,n,r,{signal:i.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");let s=EQr(a.body),u=new PNe(i,s,()=>{let l=this.ongoingStreamedRequests.indexOf(u);l>-1&&this.ongoingStreamedRequests.splice(l,1)});return this.ongoingStreamedRequests.push(u),u}return await(await TU(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 PQr(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await TU(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await UNt(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await TU(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await TU(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await TU(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await UNt(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}},NBo=new AU});var VNt=w(()=>{L_()});function WNt(t,e=0){return(_d[t[e+0]]+_d[t[e+1]]+_d[t[e+2]]+_d[t[e+3]]+"-"+_d[t[e+4]]+_d[t[e+5]]+"-"+_d[t[e+6]]+_d[t[e+7]]+"-"+_d[t[e+8]]+_d[t[e+9]]+"-"+_d[t[e+10]]+_d[t[e+11]]+_d[t[e+12]]+_d[t[e+13]]+_d[t[e+14]]+_d[t[e+15]]).toLowerCase()}var _d,Iae,KNt=w(()=>{_d=[];for(Iae=0;Iae<256;++Iae)_d.push((Iae+256).toString(16).slice(1))});function ANe(){if(!Mae&&(Mae=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Mae))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Mae(MQr)}var Mae,MQr,GNt=w(()=>{MQr=new Uint8Array(16)});var RQr,INe,JNt=w(()=>{RQr=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),INe={randomUUID:RQr}});function NQr(t,e,r){if(INe.randomUUID&&!e&&!t)return INe.randomUUID();t=t||{};var n=t.random||(t.rng||ANe)();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 WNt(n)}var MNe,ZNt=w(()=>{JNt();GNt();KNt();MNe=NQr});var YNt=w(
`):[]}};vh=new WeakMap,wh=new WeakMap;ED.NEWLINE_CHARS=new Set([`
`,"\r"]);ED.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function d9(){}function Bae(t,e,r){return!e||Uae[t]>Uae[r]?d9:e[t].bind(e)}function Zs(t){let e=t.logger,r=t.logLevel??"off";if(!e)return JQr;let n=Djt.get(e);if(n&&n[0]===r)return n[1];let o={error:Bae("error",e,r),warn:Bae("warn",e,r),info:Bae("info",e,r),debug:Bae("debug",e,r)};return Djt.set(e,[r,o]),o}var Uae,GNe,JQr,Djt,VP,f9=w(()=>{HP();Uae={off:0,error:200,warn:300,info:400,debug:500},GNe=(t,e,r)=>{if(t){if(ljt(Uae,t))return t;Zs(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(Uae))}`)}};JQr={error:d9,warn:d9,info:d9,debug:d9},Djt=new WeakMap;VP=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t)});async function*ZQr(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new gt("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new gt("Attempted to iterate over a response with no body");let r=new JNe,n=new ED,o=zNe(t.body);for await(let i of YQr(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*YQr(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"?UU(r):r,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let i;for(;(i=Njt(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function XQr(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var p9,pC,JNe,ZNe=w(()=>{Kg();cC();c9();jjt();c9();jae();zae();f9();cC();pC=class t{constructor(e,r,n){this.iterator=e,p9.set(this,void 0),this.controller=r,Xt(this,p9,n,"f")}static fromSSEResponse(e,r,n){let o=!1,i=n?Zs(n):console;async function*a(){if(o)throw new gt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let s=!1;try{for await(let u of ZQr(e,r))if(!s){if(u.data.startsWith("[DONE]")){s=!0;continue}if(u.event===null||!u.event.startsWith("thread.")){let l;try{l=JSON.parse(u.data)}catch(c){throw i.error("Could not parse message into JSON:",u.data),i.error("From chunk:",u.raw),c}if(l&&l.error)throw new Xl(void 0,l.error,void 0,e.headers);yield l}else{let l;try{l=JSON.parse(u.data)}catch(c){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),c}if(u.event=="error")throw new Xl(void 0,l.error,l.message,void 0);yield{event:u.event,data:l}}}s=!0}catch(u){if(u9(u))return;throw u}finally{s||r.abort()}}return new t(a,r,n)}static fromReadableStream(e,r,n){let o=!1;async function*i(){let s=new ED,u=zNe(e);for await(let l of u)for(let c of s.decode(l))yield c;for(let l of s.flush())yield l}async function*a(){if(o)throw new gt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let s=!1;try{for await(let u of i())s||u&&(yield JSON.parse(u));s=!0}catch(u){if(u9(u))return;throw u}finally{s||r.abort()}}return new t(a,r,n)}[(p9=new WeakMap,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,ie(this,p9,"f")),new t(()=>o(r),this.controller,ie(this,p9,"f"))]}toReadableStream(){let e=this,r;return $Ne({async start(){r=e[Symbol.asyncIterator]()},async pull(n){try{let{value:o,done:i}=await r.next();if(i)return n.close();let a=UU(JSON.stringify(o)+`
`);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}};JNe=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]=XQr(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}}});async function qae(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:o,startTime:i}=e,a=await(async()=>{if(e.options.stream)return Zs(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller,t):pC.fromSSEResponse(r,e.controller,t);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let u=r.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){let d=await r.json();return YNe(d,r)}return await r.text()})();return Zs(t).debug(`[${n}] response parsed`,VP({retryOfRequestLogID:o,url:r.url,status:r.status,body:a,durationMs:Date.now()-i})),a}function YNe(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})}var XNe=w(()=>{ZNe();f9()});var m9,TD,Hae=w(()=>{Kg();XNe();TD=class t extends Promise{constructor(e,r,n=qae){super(o=>{o(null)}),this.responsePromise=r,this.parseResponse=n,m9.set(this,void 0),Xt(this,m9,e,"f")}_thenUnwrap(e){return new t(ie(this,m9,"f"),this.responsePromise,async(r,n)=>YNe(e(await this.parseResponse(r,n),n),n.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("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(ie(this,m9,"f"),e))),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)}};m9=new WeakMap});var Vae,Wae,h9,mC,hn,$a=w(()=>{Kg();cC();XNe();Hae();HP();Wae=class{constructor(e,r,n,o){Vae.set(this,void 0),Xt(this,Vae,e,"f"),this.options=o,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new gt("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await ie(this,Vae,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Vae=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},h9=class extends TD{constructor(e,r,n){super(e,r,async(o,i)=>new n(o,i.response,await qae(o,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},mC=class extends Wae{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},hn=class extends Wae{constructor(e,r,n,o){super(e,r,n,o),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),r=e[e.length-1]?.id;return r?{...this.options,query:{...sjt(this.options.query),after:r}}:null}}});function qU(t,e,r){return eje(),new File(t,e??"unknown_file",r)}function g9(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}function een(t){let e=typeof t=="function"?t:t.fetch,r=Ljt.get(e);if(r)return r;let n=(async()=>{try{let o="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new o(i).text()}catch{return!0}})();return Ljt.set(e,n),n}var eje,tje,xh,Ljt,ten,ren,QNe,WP=w(()=>{c9();eje=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&pa
${i.map(f=>f.error).join(`
`)}
${a}
${d}`)}return a},je=sen(zjt)});var AD,Kae=w(()=>{Cr();$a();Vi();AD=class extends Be{list(e,r={},n){return this._client.getAPIList(je`/chat/completions/${e}/messages`,hn,{query:r,...n})}}});var Rb=w(()=>{cC()});function b9(t){return t!==void 0&&"function"in t&&t.function!==void 0}function Bjt(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function _9(t){return t?.$brand==="auto-parseable-response-format"}function ID(t){return t?.$brand==="auto-parseable-tool"}function Ujt(t,e){return!e||!oje(e)?{...t,choices:t.choices.map(r=>(Hjt(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:v9(t,e)}function v9(t,e){let r=t.choices.map(n=>{if(n.finish_reason==="length")throw new kU;if(n.finish_reason==="content_filter")throw new $U;return Hjt(n.message.tool_calls),{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(o=>den(e,o))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?cen(e,n.message.content):null}}});return{...t,choices:r}}function cen(t,e){return t.response_format?.type!=="json_schema"?null:t.response_format?.type==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function den(t,e){let r=t.tools?.find(n=>b9(n)&&n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:ID(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function qjt(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(n=>b9(n)&&n.function?.name===e.function.name);return b9(r)&&(ID(r)||r?.function.strict||!1)}function oje(t){return _9(t.response_format)?!0:t.tools?.some(e=>ID(e)||e.type==="function"&&e.function.strict===!0)??!1}function Hjt(t){for(let e of t||[])if(e.type!=="function")throw new gt(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Vjt(t){for(let e of t??[]){if(e.type!=="function")throw new gt(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new gt(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var HU=w(()=>{Rb()});var VU,ije,aje=w(()=>{VU=t=>t?.role==="assistant",ije=t=>t?.role==="tool"});var sje,Gae,Jae,w9,x9,Zae,S9,KP,C9,Yae,Xae,WU,Wjt,QI,Qae=w(()=>{Kg();Rb();QI=class{constructor(){sje.add(this),this.controller=new AbortController,Gae.set(this,void 0),Jae.set(this,()=>{}),w9.set(this,()=>{}),x9.set(this,void 0),Zae.set(this,()=>{}),S9.set(this,()=>{}),KP.set(this,{}),C9.set(this,!1),Yae.set(this,!1),Xae.set(this,!1),WU.set(this,!1),Xt(this,Gae,new Promise((e,r)=>{Xt(this,Jae,e,"f"),Xt(this,w9,r,"f")}),"f"),Xt(this,x9,new Promise((e,r)=>{Xt(this,Zae,e,"f"),Xt(this,S9,r,"f")}),"f"),ie(this,Gae,"f").catch(()=>{}),ie(this,x9,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},ie(this,sje,"m",Wjt).bind(this))},0)}_connected(){this.ended||(ie(this,Jae,"f").call(this),this._emit("connect"))}get ended(){return ie(this,C9,"f")}get errored(){return ie(this,Yae,"f")}get aborted(){return ie(this,Xae,"f")}abort(){this.controller.abort()}on(e,r){return(ie(this,KP,"f")[e]||(ie(this,KP,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=ie(this,KP,"f")[e];if(!n)return this;let o=n.findIndex(i=>i.listener===r);return o>=0&&n.splice(o,1),this}once(e,r){return(ie(this,KP,"f")[e]||(ie(this,KP,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{Xt(this,WU,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){Xt(this,WU,!0,"f"),await ie(this,x9,"f")}_emit(e,...r){if(ie(this,C9,"f"))return;e==="end"&&(Xt(this,C9,!0,"f"),ie(this,Zae,"f").call(this));let n=ie(this,KP,"f")[e];if(n&&(ie(this,KP,"f")[e]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...r))),e==="abort"){let o=r[0];!ie(this,WU,"f")&&!n?.length&&Promise.reject(o),ie(t
\r `.includes(t[n]);)n++};return a()},yje=t=>pen(t,Oc.ALL^Oc.NUM)});var bje=w(()=>{ZNe()});function hen(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 gt(`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 gt(`missing role for choice ${d}`);if(h){let{arguments:x,name:S}=h;if(x==null)throw new gt(`missing function_call.arguments for choice ${d}`);if(!S)throw new gt(`missing function_call.name for choice ${d}`);return{...p,message:{content:m,function_call:{arguments:x,name:S},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((x,S)=>{let{function:O,type:E,id:P,...A}=x,{arguments:I,name:R,...N}=O||{};if(P==null)throw new gt(`missing choices[${d}].tool_calls[${S}].id
${nse(t)}`);if(E==null)throw new gt(`missing choices[${d}].tool_calls[${S}].type
${nse(t)}`);if(R==null)throw new gt(`missing choices[${d}].tool_calls[${S}].function.name
${nse(t)}`);if(I==null)throw new gt(`missing choices[${d}].tool_calls[${S}].function.arguments
${nse(t)}`);return{...A,id:P,type:E,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 Ujt(u,e)}function nse(t){return JSON.stringify(t)}var ec,GP,GU,eM,_je,tse,vje,wje,xje,rse,Sje,Yjt,MD,ose=w(()=>{Kg();Zjt();Rb();HU();bje();pje();MD=class t extends KU{constructor(e){super(),ec.add(this),GP.set(this,void 0),GU.set(this,void 0),eM.set(this,void 0),Xt(this,GP,e,"f"),Xt(this,GU,[],"f")}get currentChatCompletionSnapshot(){return ie(this,eM,"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())),ie(this,ec,"m",_je).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)ie(this,ec,"m",vje).call(this,a);if(i.controller.signal?.aborted)throw new Is;return this._addChatCompletion(ie(this,ec,"m",rse).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),ie(this,ec,"m",_je).call(this),this._connected();let o=pC.fromReadableStream(e,this.controller),i;for await(let a of o)i&&i!==a.id&&this._addChatCompletion(ie(this,ec,"m",rse).call(this)),ie(this,ec,"m",vje).call(this,a),i=a.id;if(o.controller.signal?.aborted)throw new Is;return this._addChatCompletion(ie(this,ec,"m",rse).call(this))}[(GP=new WeakMap,GU=new WeakMap,eM=new WeakMap,ec=new WeakSet,_je=function(){this.ended||Xt(this,eM,void 0,"f")},tse=function(r){let n=ie(this,GU,"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},ie(this,GU,"f")[r.index]=n,n)},vje=function(r){if(this.ended)return;let n=ie(this,ec,"m",Yjt).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=ie(this,ec,"m",tse).call(this,i);i.finish_reason&&(ie(this,ec,"m",xje).call(this,i),a.current_tool_call_index!=null&&ie(this,ec,"m",wje).call(this,i,a.current_tool_call_index));for(let s of o.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(ie(this,ec,"m",xje).call(this,i),a.current_tool_call_index!=null&&ie(this,ec,"m",wje).call(this,i,a.current_tool_call_index)),a.current_tool_call_index=s.index;for(let s of o.delta.tool_calls??[]){let u=i.message.tool_calls?.[s.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:s.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,arguments_delta:s.function?.arguments??""}):(u?.type,void 0))}}},wje=function(r,n){if(ie(this,ec,"m",tse).call(this,r).done_tool_calls.has(n))return;let i=r.message.tool_calls?.[n];if(!i)throw new Error("no tool call snapshot");if(!i.type)throw new Error("tool call snapshot missing `type`");if(i.type==="function"){let a=ie(this,GP,"f")?.tools?.find(s=>b9(s)&&s.funct
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-08-12 16:40:13 +08:00
`);this.baseURL=s.baseURL,this.timeout=s.timeout??wDe.DEFAULT_TIMEOUT,this.logger=s.logger??console;let u="warn";this.logLevel=u,this.logLevel=GNe(s.logLevel,"ClientOptions.logLevel",this)??GNe(Nb("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??yjt(),Xt(this,hse,_jt,"f"),this._options=s,this.apiKey=r,this.organization=n,this.project=o,this.webhookSecret=i}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){}async authHeaders(e){return mt([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return WNe(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${XI}`}defaultIdempotencyKey(){return`stainless-node-retry-${jNe()}`}makeStatusError(e,r,n,o){return Xl.generate(e,r,n,o)}buildURL(e,r,n){let o=!ie(this,vDe,"m",wDt).call(this)&&n||this.baseURL,i=ajt(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return ujt(a)||(r={...a,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(i.search=this.stringifyQuery(r)),i.toString()}async prepareOptions(e){}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(o=>({method:e,path:r,...o})))}request(e,r=null){return new TD(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let o=await e,i=o.maxRetries??this.maxRetries;r==null&&(r=i),await this.prepareOptions(o);let{req:a,url:s,timeout:u}=await this.buildRequest(o,{retryCount:i-r});await this.prepareRequest(a,{url:s,options:o});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),c=n===void 0?"":`, retryOf: ${n}`,d=Date.now();if(Zs(this).debug(`[${l}] sending request`,VP({retryOfRequestLogID:n,method:o.method,url:s,options:o,headers:a.headers})),o.signal?.aborted)throw new Is;let f=new AbortController,p=await this.fetchWithTimeout(s,a,u,f).catch(l9),m=Date.now();if(p instanceof Error){let g=`retrying, ${r} attempts remaining`;if(o.signal?.aborted)throw new Is;let y=u9(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(r)return Zs(this).info(`[${l}] connection ${y?"timed out":"failed"} - ${g}`),Zs(this).debug(`[${l}] connection ${y?"timed out":"failed"} (${g})`,VP({retryOfRequestLogID:n,url:s,durationMs:m-d,message:p.message})),this.retryRequest(o,r,n??l);throw Zs(this).info(`[${l}] connection ${y?"timed out":"failed"} - error; no more retries left`),Zs(this).debug(`[${l}] connection ${y?"timed out":"failed"} (error; no more retries left)`,VP({retryOfRequestLogID:n,url:s,durationMs:m-d,message:p.message})),y?new uC:new YI({cause:p})}let h=[...p.headers.entries()].filter(([g])=>g==="x-request-id").map(([g,y])=>", "+g+": "+JSON.stringify(y)).join(""),b=`[${l}${c}${h}] ${a.method} ${s} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${m-d}ms`;if(!p.ok){let g=await this.shouldRetry(p);if(r&&g){let P=`retrying, ${r} attempts remaining`;return await bjt(p.body),Zs(this).info(`${b} - ${P}`),Zs(this).debug(`[${l}] response error (${P})`,VP({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,durationMs:m-d})),this.retryRequest(o,r,n??l,p.headers)}let y=g?"error; no more retries left":"error; not retryable";Zs(this).info(`${b} - ${y}`);let x=await p.text().catch(P=>l9(P).message),S=djt(x),O=S?void 0:x;throw Zs(this).debug(`[${l}] response error (${y})`,VP({retryOfRequestLogID:n,url:p.url,status:p.status,headers:p.headers,message:O,durationMs:Date.now()-d})),this.makeStatusE
`))}let n={name:t.function.name,args:r,type:"tool_call"};return e?.returnId&&(n.id=t.id),n}function _C(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 _m(t,e){return{name:t.function?.name,args:t.function?.arguments,id:t.id,error:e,type:"invalid_tool_call"}}var xDe,wd,CDt=w(()=>{m$();hve();iA();oN();LO();xDe=class extends pN{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(Di(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=>bm(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}},wd=class extends xDe{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 gKe(this.zodSchema,e);if(r.success)return r.data;throw new Km(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(r.error?.issues)}`,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 ODt=w(()=>{CDt()});var yq=w(()=>{ODt()});var SDe=w(()=>{uN()});function XP(t){let{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:r,azureOpenAIApiKey:n,azureOpenAIBasePath:o,baseURL:i,azureADTokenProvider:a,azureOpenAIEndpoint:s}=t;if((n||a)&&o&&e)return`${o}/${e}`;if((n||a)&&s&&e)return`${s}/openai/deployments/${e}`;if(n||a){if(!r)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${r}.openai.azure.com/openai/deployments/${e}`}return i}var cM=w(()=>{});var EDt,PDt,TDt,yse=w(()=>{EDt=Symbol("Let zodToJsonSchema decide on which parser to use"),PDt={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,emailStr
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-08-12 16:40:13 +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 vse(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===re.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:vr(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:vr(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===re.ZodString&&t.keyType._def.checks?.length){let n=Object.entries(bse(t.keyType._def,e)).reduce((o,[i,a])=>i==="type"?o:{...o,[i]:a},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===re.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}var wse=w(()=>{Qf();pu();_se()});function qDt(t,e){if(e.mapStrategy==="record")return vse(t,e);let r=vr(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=vr(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 BDe=w(()=>{pu();wse()});function HDt(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 UDe=w(()=>{});function VDt(){return{not:{}}}var qDe=w(()=>{});function WDt(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var HDe=w(()=>{});function GDt(t,e){if(e.target==="openApi3")return KDt(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in N9&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=N9[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 KDt(t,e)}var N9,KDt,xse=w(()=>{pu();N9={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};KDt=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>vr(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 JDt(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:N9[t.innerType._def.typeName],nullable:!0}:{type:[N9[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=vr(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=vr(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var VDe=w(()=>{pu();xse()});function ZDt(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",PDe(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?oo(r,"
2025-07-05 20:48:33 +08:00
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
2025-08-12 16:40:13 +08:00
`,t}var lLt=w(()=>{});function fM(t){let e;return t.constructor.name===uC.name?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===Is.name?(e=new Error(t.message),e.name="AbortError"):t.status===400&&t.message.includes("tool_calls")?e=j9(t,"INVALID_TOOL_RESULTS"):t.status===401?e=j9(t,"MODEL_AUTHENTICATION"):t.status===429?e=j9(t,"MODEL_RATE_LIMIT"):t.status===404?e=j9(t,"MODEL_NOT_FOUND"):e=t,e}function oLe(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 utn(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function cLt(t,e,r){if(Vm(t))return sLt(t,e,r);if(Vp(t))return utn({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:FH(t,{cycles:"ref",reused:"ref",override(n){n.jsonSchema.title=e}})}},n=>oY(t,JSON.parse(n)));throw new Error("Unsupported schema response format")}var YD=w(()=>{bC();_h();CD();SDe();aY();uLt();lLt()});function ltn(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function dLt(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(fLt(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
`)}function fLt(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}: ${Sse(o,e)},`):r.push(`${n}?: ${Sse(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
`)}function Sse(t,e){if(ltn(t))return t.anyOf.map(r=>Sse(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["{",fLt(t,e+2),"}"].join(`
`);case"array":return t.items?`${Sse(t.items,e)}[]`:"any[]";default:return""}}var pLt=w(()=>{});function mLt(t,e){let r;return Cc(t)?r=oC(t):r=t,r.type==="function"&&e?.strict!==void 0&&(r.function.strict=e.strict),r}function Cse(t){return"type"in t&&t.type!=="function"&&t.type!=="custom"}function hLt(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function gLt(t){return typeof t=="object"&&t!==null&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null&&"customTool"in t.metadata&&typeof t.metadata.customTool=="object"&&t.metadata.customTool!==null}function iLe(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function yLt(t){if(t.type==="custom_tool_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:t.name,isCustomTool:!0,args:{input:t.input}}}function bLt(t){return t.type==="tool_call"&&"isCustomTool"in t&&t.isCustomTool===!0}function _Lt(t){let e=()=>{if(t.custom.format){if(t.custom.format.type==="grammar")return{type:"grammar",definition:t.custom.format.grammar.definition,syntax:t.custom.format.grammar.syntax};if(t.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:t.custom.name,description:t.custom.description,format:e()}}function vLt(t){let e=()=>{if(t.format){if(t.format.type==="grammar")return{type:"grammar",grammar:{definition:t.format.definition,syntax:t.format.syntax}};if(t.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:t.name,description:t.description,format:e()}}}var wLt=w(()=>{_h();YD()});function Ese(t){return t&&(/^o\d/.test(t)||t.startsWith("gpt-5"))}function ctn(t){return t!==void 0&&typeof t.schema=="object"}function dtn(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 sLe(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(!ks.isInstance(t))throw new Error("Invalid generic chat message");return dtn(t)}default:throw new Error(`Unknown message type: ${e}`)}}function aLe(t,e){return t.flatMap(r=>{let n=sLe(r);n==="system"&&Ese(e)&&(n="developer");let o=typeof r.content=="string"?r.content:r.content.map(a=>Jy(a)?SH(a,xLt):a),i={role:n,content:o};if(r.name!=null&&(i.name=r.name),r.additional_kwargs.function_call!=null&&(i.function_call=r.additional_kwargs.function_call,i.content=""),Di(r)&&r.tool_calls?.length?(i.tool_calls=r.tool_calls.map(_C),i.content=""):(r.additional_kwargs.tool_calls!=null&&(i.tool_calls=r.additional_kwargs.tool_calls),r.tool_call_id!=null&&(i.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio){let a={role:"assistant",audio:{id:r.additional_kwargs.audio.id}};return[i,a]}return i})}var bq,xLt,D9,Ose,Pse,vC,Tse=w(()=>{bC();As();Of();Kn();iC();bh();Jp();eb();yq();CD();SDe();cM();YD();pLt();wLt();bq="__openai_function_call_ids__";xLt={providerName:"ChatOpenAI",fromStandardTextBlock(t){return{type:"text",text:t.text}},fromStandardImageBlock(t){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};if(t.source_type==="base64")return{type:"image_url",image_url:{url:`data:${t.mime_type??""};base64,${t.data}`,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(t){if(t.source_type==="url"){let e=Xk({dataUrl:t.url});if(!e)throw new Error(`URL audio blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);let r=e.mime_type||t.mime_type||"",n;try{n=Qbe(r)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(n.type!=="audio"||n.subtype!=="wav"&&n.subtype!=="mp3")throw new Error(`Audio blocks with sou
Details: ${m.message}`),new nN(h,JSON.stringify(e))}else{let m=da(o,this.schema);if(!m.valid){let h="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(h=`${h}
2025-07-05 20:48:33 +08:00
Details: ${m.errors.map(b=>`${b.keywordLocation}: ${b.error}`).join(`
2025-08-12 16:40:13 +08:00
`)}`),new nN(h,JSON.stringify(e))}i=o}let a=aN(r),u=await ru.configure(a.callbacks,this.callbacks,a.tags||n,this.tags,a.metadata,this.metadata,{verbose:this.verbose})?.handleToolStart(this.toJSON(),typeof e=="string"?e:JSON.stringify(e),a.runId,void 0,void 0,void 0,a.runName);delete a.runId;let l;try{l=await this._call(i,u,a)}catch(m){throw await u?.handleToolError(m),m}let c,d;if(this.responseFormat==="content_and_artifact")if(Array.isArray(l)&&l.length===2)[c,d]=l;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
Result: ${JSON.stringify(l)}`);else c=l;let f;ZT(e)&&(f=e.id),!f&&N9e(a)&&(f=a.toolCall.id);let p=ptn({content:c,artifact:d,toolCallId:f,name:this.name,metadata:this.metadata});return await u?.handleToolEnd(p),p}},QP=class extends Rse{constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:rn.object({input:rn.string().optional()}).transform(r=>r.input)})}call(e,r){let n=typeof e=="string"||e==null?{input:e}:e;return super.call(n,r)}},Nse=class extends QP{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=aN(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)}},cLe=class extends Rse{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=aN(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 eE=w(()=>{ILt()});var dLe,MLt=w(()=>{Kn();bC();eE();dLe=class extends QP{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??ct("OPENAI_API_KEY"),n=e?.organization??ct("OPENAI_ORGANIZATION"),o={apiKey:r,organization:n,dangerouslyAllowBrowser:!0,baseURL:e?.baseUrl};this.client=new _r(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
without CORS Error: `+ci(n)+`
with CORS Error: `+ci(o);throw new Error(i)}}}}});function qLt(t){return t!==void 0&&L9.includes(t)?BLt[t]:void 0}var BLt,ULt,L9,$se=w(()=>{BLt={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"},ULt={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},L9=Object.keys(BLt)});function Ki(t,e){if(e.length<fLe)Array.prototype.push.apply(t,e);else{let r=e.length;for(let n=0;n<r;n+=fLe)Array.prototype.push.apply(t,e.slice(n,n+fLe))}}function GLt(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 btn(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function _tn(){return typeof process<"u"&&process.release&&process.release.name==="node"}function KLt(){return BigInt(Math.floor(performance.now()*1e6))}function QD(t){return typeof t=="number"&&(t=BigInt(t)),t<HLt?`${t}ns`:t<VLt?`${t/HLt}\u03BCs`:t<WLt?`${t/VLt}ms`:`${t/WLt}s`}function kb(){return btn()?KLt():_tn()||typeof process<"u"&&typeof process?.hrtime?.bigint=="function"?process.hrtime.bigint():typeof performance<"u"?KLt():BigInt(0)}function F9(){return`${gtn}-${ytn++}`}function _q(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 JLt(t,e){return e[1]===t[1]?t[0]-e[0]:e[1]-t[1]}function vq(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 zse(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 wq(t,e){return zse(t,[e])[e]}functi
- `),xtn={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-08-12 16:40:13 +08:00
- ${wtn}`,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-08-12 16:40:13 +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 ZLt(t){return{raw:Number(t),formatted:QD(t)}}function YLt(t){if(t.id){if(typeof t.id!="string")throw Gt("DOCUMENT_ID_MUST_BE_STRING",typeof t.id);return t.id}return F9()}function mLe(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(tE(n)){let i=gLe(n);if(!Array.isArray(o)||o.length!==i)throw Gt("INVALID_INPUT_VECTOR",r,i,o.length);continue}if(xq(n)){if(!Array.isArray(o))return r;let i=hLe(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=mLe(o,n);if(i)return r+"."+i;continue}if(typeof o!==n)return r}}}function XLt(t){return t==="geopoint"}function tE(t){return typeof t=="string"&&/^vector\[\d+\]$/.test(t)}function xq(t){return typeof t=="string"&&Stn[t]}function hLe(t){return Ctn[t]}function gLe(t){let e=Number(t.slice(7,-1));switch(!0){case isNaN(e):throw Gt("INVALID_VECTOR_VALUE",t);case e<=0:throw Gt("INVALID_VECTOR_SIZE",t);default:return e}}var Stn,Ctn,k9=w(()=>{Pc();Ys();Ys();Stn={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},Ctn={"string[]":"string","number[]":"number","boolean[]":"boolean","enum[]":"enum"}});function QLt(){return{idToInternalId:new Map,internalIdToId:[],save:Otn,load:Ptn}}function Otn(t){return{internalIdToId:t.internalIdToId}}function Ptn(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 Ii(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?Ii(t,e.toString()):e}function Jg(t,e){if(t.internalIdToId.length<e)throw new Error(`Invalid internalId ${e}`);return t.internalIdToId[e-1]}var Zg=w(()=>{});function Ttn(t,e){return{sharedInternalDocumentStore:e,docs:{},count:0}}function Atn(t,e){let r=Ii(t.sharedInternalDocumentStore,e);return t.docs[r]}function Itn(t,e){let r=e.length,n=Array.from({length:r});for(let o=0;o<r;o++){let i=Ii(t.sharedInternalDocumentStore,e[o]);n[o]=t.docs[i]}return n}function Mtn(t){return t.docs}function Rtn(t,e,r){let n=Ii(t.sharedInternalDocumentStore,e);return typeof t.docs[n]<"u"?!1:(t.docs[n]=r,t.count++,!0)}function Ntn(t,e){let r=Ii(t.sharedInternalDocumentStore,e);return typeof t.docs[r]>"u"?!1:(delete t.docs[r],t.count--,!0)}function jtn(t){return t.count}function Dtn(t,e){let r=e;return{docs:r.docs,count:r.count,sharedInternalDocumentStore:t}}function Ltn(t){return{docs:t.docs,count:t.count}}function eFt(){return{create:Ttn,get:Atn,getMultiple:Itn,getAll:Mtn,store:Rtn,remove:Ntn,count:jtn,load:Dtn,save:Ltn}}var yLe=w(()=>{Zg()});function rFt(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),Gt("PLUGIN_CRASHED")}return r}var tFt,nFt=w(()=>{Pc();tFt=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeLoad","afterLoad","afterCreate"]});function $b(t,e,r,n){if(t.some(hu))return(async()=>{for(let i of t)await i(e,r,n)})();for(let i of t)i(e,r,n)}function eL(t,e,r){if(t.some(hu))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}},Gue=class t extends tFe{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-08-12 16:40:13 +08:00
`," ",""];throw new Error(`Language ${e} is not supported.`)}}});var N$t=w(()=>{R$t()});var j$t=w(()=>{N$t()});var D$t=w(()=>{j$t()});var L$t=w(()=>{D$t()});var F$t,CC,Jue,k$t=w(()=>{Ur();XD();Tn();E$t();er();on();F$t=F(Iq());L$t();CC=require("obsidian");Qg();Jue=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=ae();this.rateLimiter=new J9(o.embeddingRequestsPerMin),this.embeddingBatchSize=o.embeddingBatchSize,this.checkpointInterval=8*this.embeddingBatchSize,Ma(async()=>{let i=ae();this.rateLimiter=new J9(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 CC.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 CC.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(()=>{J("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=mu.getModelName(r),o=Gue.fromLanguage("markdown",{chunkSize:FGe}),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:Bs(new Date(a.stat.ctime)).display,modified:Bs(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-08-12 16:40:13 +08:00
`,appendChunkOverlapHeader:!0})).forEach(d=>{d.pageContent.trim()&&i.push({content:d.pageContent,fileInfo:l})})}return i}getDocHash(e){return(0,F$t.MD5)(e).toString()}async getFilesToIndex(e){let{inclusions:r,exclusions:n}=Tf(),o=this.app.vault.getMarkdownFiles();if(e)return o.filter(c=>gu(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(!gu(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 J([`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 CC.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 CC.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=ae(),o=Xg(n.qaInclusions);o.length>0&&r.push(`Inclusions: ${o.join(", ")}`);let a=[...Uue(this.app),...Xg(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 CC.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 CC.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 CC.Notice("Indexing cancelled");return}e.length>0?new CC.Notice(`Indexing completed with ${e.length} errors. Check console for details.`):new CC.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(),ae().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 $$t={};Qd($$t,{default:()=>wa});var Z9,wa,OC=w(()=>{BA();XD();er();Z9=require("obsidian");Hue();P$t();k$t();wa=class t{constructor(){this.embeddingsManager=mu.getInstance(),this.dbOps=new nE(app),this.indexOps=new Jue(app,this.dbOps,this.embeddingsManager),this.eventHandler=new Vue(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={...ae()};let e=async()=>{let r=ae(),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())}};Ma(()=>{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 Hr&&r.message.includes("Vault adapter not available")&&(e--,e>0)){await new Promise(n=>setTimeout(n,100));continue}new Z9.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(),Z9.Platform.isMobile&&ae().disableIndexOnMobile?(new Z9.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"}};wde.SDKError=Nze});var fG=v(dG=>{"use strict";Object.defineProperty(dG,"__esModule",{value:!0});dG.EventStream=void 0;dG.discardSentinel=efn;var lG=10,cG=13,L4t=new Set([lG,cG]),Xdn=[new Uint8Array([cG,lG,cG,lG]),new Uint8Array([cG,cG]),new Uint8Array([lG,lG])],Dze=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=F4t(r,s);if(u==null)continue;let l=r.slice(n,s);n=s+u.length;let c=Lze(l,this.decoder);c!=null&&(yield c)}n>0&&(r=r.slice(n),n=0)}if(r.length>0){let o=Lze(r,this.decoder);o!=null&&(yield o)}}catch(o){if(o instanceof Error&&o.name==="AbortError")return;throw o}finally{e.releaseLock()}}};dG.EventStream=Dze;function F4t(t,e){let r=t[e],n=t[e+1];if(r==null||n==null||!L4t.has(r)||!L4t.has(n))return null;for(let o of Xdn){let i=Qdn(e,t,o);if(i!=null)return i}return null}function Qdn(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 Lze(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 efn(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=F4t(n,d);if(f==null)continue;let p=o,m=n.slice(p,d);o=d+f.length,Lze(m,tfn)?.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 tfn(t){return t}});var $ze=v(r_=>{"use strict";var rfn=r_&&r_.__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]}),nfn=r_&&r_.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),ofn=r_&&r_.__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)&&rfn(e,t,r);return nfn(e,t),e};Object.defineProperty(r_,"__esModule",{value:!0});r_.SDKValidationError=void 0;r_.formatZodError=kze;var ifn=ofn(Ie()),Fze=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 ifn.ZodError?`${this.rawMessage}
${kze(this.cause)}`:this.toString()}};r_.SDKValidationError=Fze;function kze(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(`${kze(c,e+1)}`)})}}}return t.issues.length&&o("\u2514\u2500*"),n.slice(1)}});var we=v(pG=>{"use strict";Object.defineProperty(pG,"__esModule",{value:!0});pG.parse=sfn;pG.safeParse=ufn;pG.collectExtraKeys=lfn;var afn=Ie(),$4t=$ze(),k4t=dy();function sfn(t,e,r){try{return e(t)}catch(n){throw n instanceof afn.ZodError?new $4t.SDKValidationError(r,n,t):n}}function ufn(t,e,r){try{return(0,k4t.OK)(e(t))}catch(n){return(0,k4t.ERR)(new $4t.SDKValidationError(r,n,t))}}function lfn(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 gi=v(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});Fc.jsonErr=ffn;Fc.json=pfn;Fc.textErr=mfn;Fc.text=hfn;Fc.bytesErr=gfn;Fc.bytes=yfn;Fc.streamErr=bfn;Fc.stream=_fn;Fc.sseErr=vfn;Fc.sse=wfn;Fc.nilErr=xfn;Fc.nil=Sfn;Fc.fail=Cfn;Fc.match=Ofn;Fc.unpackHeaders=xde;Fc.discardResponseBody=H4t;var z4t=jze(),cfn=fG(),B4t=aG(),U4t=Oze(),q4t=we(),dfn={json:"application/json",text:"text/plain",bytes:"application/octet-stream",stream:"application/octet-stream",sse:"text/event-stream",nil:"*",fail:"*"};function ffn(t,e,r){return{...r,err:!0,enc:"json",codes:t,schema:e}}function pfn(t,e,r){return{...r,enc:"json",codes:t,schema:e}}function mfn(t,e,r){return{...r,err:!0,enc:"text",codes:t,schema:e}}function hfn(t,e,r){return{...r,enc:"text",codes:t,schema:e}}function gfn(t,e,r){return{...r,err:!0,enc:"bytes",codes:t,schema:e}}function yfn(t,e,r){return{...r,enc:"bytes",codes:t,schema:e}}function bfn(t,e,r){return{...r,err:!0,enc:"stream",codes:t,schema:e}}function _fn(t,e,r){return{...r,enc:"stream",codes:t,schema:e}}function vfn(t,e,r){return{...r,err:!0,enc:"sse",codes:t,schema:e}}function wfn(t,e,r){return{...r,enc:"sse",codes:t,schema:e}}function xfn(t,e,r){return{...r,err:!0,enc:"nil",codes:t,schema:e}}function Sfn(t,e,r){return{...r,enc:"nil",codes:t,schema:e}}function Cfn(t){return{enc:"fail",codes:t}}function Ofn(...t){return async function(r,n){let o,i;for(let l of t){let{codes:c}=l,d="ctype"in l?l.ctype:dfn[l.enc];if(d&&(0,B4t.matchResponse)(r,c,d)){i=l;break}else if(!d&&(0,B4t.matchStatusCode)(r,c)){i=l;break}}if(!i){let l=await r.text();return[{ok:!1,error:new z4t.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,cfn.discardSentinel)(r.body,i.sseSentinel):r.body;break;case"nil":o=await H4t(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 z4t.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:xde(r.headers)}:null,...(0,U4t.isPlainObject)(o)?o:null}:s?u={...n?.extraFields,...i.hdrs?{Headers:xde(r.headers)}:null,[s]:o}:i.hdrs?u={...n?.extraFields,...i.hdrs?{Headers:xde(r.headers)}:null,...(0,U4t.isPlainObject)(o)?o:null}:u=o,"err"in i){let l=(0,q4t.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-08-12 16:40:13 +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 gpe=v(hpe=>{"use strict";Object.defineProperty(hpe,"__esModule",{value:!0});hpe.parseRecordDef=void 0;var PG=Ie(),CWt=Ml(),JOn=mpe(),ZOn=ape();function YOn(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===PG.ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:(0,CWt.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:(0,CWt.parseDef)(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===PG.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=(0,JOn.parseStringDef)(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===PG.ZodFirstPartyTypeKind.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===PG.ZodFirstPartyTypeKind.ZodBranded&&t.keyType._def.type._def.typeName===PG.ZodFirstPartyTypeKind.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=(0,ZOn.parseBrandedDef)(t.keyType._def,e);return{...r,propertyNames:o}}}return r}hpe.parseRecordDef=YOn});var qBe=v(ype=>{"use strict";Object.defineProperty(ype,"__esModule",{value:!0});ype.parseMapDef=void 0;var OWt=Ml(),XOn=gpe();function QOn(t,e){if(e.mapStrategy==="record")return(0,XOn.parseRecordDef)(t,e);let r=(0,OWt.parseDef)(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=(0,OWt.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}}}ype.parseMapDef=QOn});var HBe=v(bpe=>{"use strict";Object.defineProperty(bpe,"__esModule",{value:!0});bpe.parseNativeEnumDef=void 0;function ePn(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}}bpe.parseNativeEnumDef=ePn});var VBe=v(_pe=>{"use strict";Object.defineProperty(_pe,"__esModule",{value:!0});_pe.parseNeverDef=void 0;function tPn(){return{not:{}}}_pe.parseNeverDef=tPn});var WBe=v(vpe=>{"use strict";Object.defineProperty(vpe,"__esModule",{value:!0});vpe.parseNullDef=void 0;function rPn(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}vpe.parseNullDef=rPn});var wpe=v(TR=>{"use strict";Object.defineProperty(TR,"__esModule",{value:!0});TR.parseUnionDef=TR.primitiveMappings=void 0;var nPn=Ml();TR.primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function oPn(t,e){if(e.target==="openApi3")return PWt(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in TR.primitiveMappings&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=TR.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._
2025-07-05 20:48:33 +08:00
${e.join(`
2025-08-12 16:40:13 +08:00
`)}`)}};Gg();on();var _M=class t{constructor(){this.mentions=new Map,this.brevilabsClient=Wi.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=>!IGe(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 PC.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-08-12 16:40:13 +08:00
${s.processed}`)}),{urlContext:n,imageUrls:o}}getMentions(){return this.mentions}clearMentions(){this.mentions.clear()}};Qg();er();Tn();var Y$t=F(Iq()),Xue=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)||(J("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,Y$t.MD5)(r).toString();return J("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)){J("Cache hit for PDF:",e.path);let o=await app.vault.adapter.read(n);return JSON.parse(o)}return J("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);J("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);J("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)}}};Tn();function sL(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 X$t(t){let r=(t?.message||t?.toString()||"").match(/Try again in ([\d\w\s]+)/);return r?r[1]:"some time"}var tzt=require("obsidian");var Q$t=require("obsidian");var ele,ezt,Que=class{constructor(e){this.vault=e;y6e(this,ele)}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 Q$t.TFile?await this.vault.cachedRead(l):"";return{...u,content:c}}return u.type==="text"?{...u,content:u.text??""}:{...u,content:""}})),a=[...o];b6e(this,ele,ezt).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-08-12 16:40:13 +08:00
`,o}};ele=new WeakSet,ezt=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 cFe=class{constructor(){this.supportedExtensions=["md"]}async parseFile(e,r){return await r.read(e)}},tle=class{constructor(e){this.supportedExtensions=["pdf"];this.brevilabsClient=e,this.pdfCache=Xue.getInstance()}async parseFile(e,r){try{J("Parsing PDF file:",e.path);let n=await this.pdfCache.get(e);if(n)return J("Using cached PDF content for:",e.path),n.response;let o=await r.readBinary(e);J("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(){J("Clearing PDF cache"),await this.pdfCache.clear()}},dFe=class{constructor(){this.supportedExtensions=["canvas"]}async parseFile(e,r){try{J("Parsing Canvas file:",e.path);let n=new Que(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}]`}}},jq=class jq{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=zb.getInstance(),this.currentProject=r}static resetRateLimitNoticeTimer(){jq.lastRateLimitNoticeTime=0}async parseFile(e,r){try{if(J(`[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 J(`[Docs4LLMParser] Project ${this.currentProject.name}: Using cached content for: ${e.path}`),n;J(`[Docs4LLMParser] Project ${this.currentProject.name}: Cache miss for: ${e.path}. Proceeding to API call.`);let o=await r.readBinary(e);J(`[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-08-12 16:40:13 +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),J(`[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),sL(n)&&this.showRateLimitNotice(n),n}}showRateLimitNotice(e){let r=Date.now();if(r-jq.lastRateLimitNoticeTime<6e4)return;jq.lastRateLimitNoticeTime=r;let n=X$t(e);new tzt.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(){J("Cache clearing is now handled at the project level")}};jq.lastRateLimitNoticeTime=0;var Y9=jq,vM=class{constructor(e,r,n=!1,o=null){this.parsers=new Map;this.isProjectMode=n,this.currentProject=o,this.registerParser(new cFe),this.registerParser(new Y9(e,o)),n||this.registerParser(new tle(e)),this.registerParser(new dFe)}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 tle&&await e.clearCache()}};on();var HG=require("obsidian");Gg();Us();td();Ur();Us();on();async function rle(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-08-12 16:40:13 +08:00
`);return await rb(async()=>{let i=await Ec.instance.getCurrentChainManager().chatModelManager.getChatModel().bind({temperature:0}).invoke([{role:"user",content:r.replace("{chat_history}",n).replace("{question}",t)}]);return wN(i.content)})}Ur();Gg();Tn();Gg();XD();Tn();OC();er();on();Kue();sA();QT();sf();j_();var nle=class extends jn{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,_n(r))}async getRelevantDocuments(e,r){let n=_n(aN(r)),i=await(await ru.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}}};H9();Hue();var EC=class extends nle{constructor(r){super();this.options=r;this.lc_namespace=["hybrid_retriever"];this.queryRewritePrompt=Gp.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-08-12 16:40:13 +08:00
Passage:`)}async getRelevantDocuments(r,n){return rb(async()=>{let o=tb(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 ae().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 Wi.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}}))),ae().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-08-12 16:40:13 +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 rb(()=>Ec.instance.getCurrentChainManager().chatModelManager.getChatModel().bind({temperature:0}).invoke(n));return o&&"content"in o?wN(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 wa.getInstance().getDb(),a=await nE.getDocsByPath(i,o.path);if(a){let s=a.map(u=>new oE({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 wa.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&&(ae().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);J("==== Daily note date range: ====",d[0],d[d.length-1]);let f=tb(d.join(", "),app.vault),m=(await this.getExplicitChunks(f)).map(x=>({...x,metadata:{...x.metadata,includeInContext:!0}}));J("==== Modified time range: ====",l,c),s.where={mtime:{between:[l,c]}};let b=(await xd(a,s)).hits.map(x=>new oE({pageContent:x.document.content,metadata:{...x.document.metadata,score:x.score,path:x.document.path,mtime:x.document.mtime,ctime:x.document.ctime,title:x.document.title,id:x.document.id,embeddingModel:x.document.embeddingModel,tags:x.document.tags,extension:x.document.extension,created_at:x.document.created_at,nchars:x.document.nchars}})),g=[...m,...b];return Array.from(new Set(g.map(x=>x.metadata.id))).map(x=>g.find(S=>S.metadata.id===x)).filter(x=>x!==void 0)}ae().debug&&console.log(`==== Orama Search Params: ====
`,s);let u=await xd(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 oE({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 mu.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}}))}};er();var fFe=require("obsidian"),rzt=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""}},Dq=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 fFe.Notice(n.message):new fFe.Notice("An error occurred while executing the tool. Check console for details."),null}}};on();var hUt=require("obsidian");Us();eE();Qf();Qg();function Ann(t){return"children"in t&&"path"in t}function Inn(t){return"path"in t&&!("children"in t)}function Mnn(t){let e=t.split(".");return e.length>1&&e.pop()?.toLowerCase()||""}function pFe(t,e=!0){let r=[],n={},o={},{inclusions:i,exclusions:a}=Tf();for(let u of t.children)if(Inn(u)){if(gu(u,i,a)){e&&r.push(u.name);let l=Mnn(u.name)||"unknown";l&&(n[l]=(n[l]||0)+1)}}else if(Ann(u)){let l=pFe(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 nzt=t=>Ch(async()=>{let e=pFe(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-08-12 16:40:13 +08:00
`,n=JSON.stringify(e);if(n.length>5e5){let o=pFe(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:rn.void()});Ur();BA();Gg();OC();er();eE();Qf();var mFe=Ch(async({timeRange:t,query:e,salientTerms:r})=>{if(await wa.getInstance().isIndexEmpty())throw new Hr(zY);let o=t!==void 0,i=ae().maxSourceChunks<owe?owe:ae().maxSourceChunks;ae().debug&&console.log("returnAll:",o);let u=(await new EC({minSimilarityScore:o?0:.1,maxK:o?1e3:i,salientTerms:r,timeRange:t?{startTime:t.startTime.epoch,endTime:t.endTime.epoch}:void 0,textWeight:kGe,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:rn.object({timeRange:rn.object({startTime:rn.any(),endTime:rn.any()}).optional(),query:rn.string().describe("The search query"),salientTerms:rn.array(rn.string()).describe("List of salient terms extracted from the query")})}),ozt=Ch(async()=>{try{let t=await wa.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"}),hFe=Ch(async({query:t,chatHistory:e})=>{try{let r=await rle(t,e),n=await Wi.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-08-12 16:40:13 +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:rn.object({query:rn.string().describe("The search query"),chatHistory:rn.array(rn.object({role:rn.enum(["user","assistant"]),content:rn.string()})).describe("Previous conversation turns")})});eE();var uzt=F(izt(),1),X9=F(wM(),1);var go;(function(t){t[t.AM=0]="AM",t[t.PM=1]="PM"})(go||(go={}));var yu;(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"})(yu||(yu={}));var Oh;(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"})(Oh||(Oh={}));function azt(t,e){e=e.add(1,"day"),uL(t,e),Lq(t,e)}function Bb(t,e){t.assign("day",e.date()),t.assign("month",e.month()+1),t.assign("year",e.year())}function ole(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",go.AM):t.assign("meridiem",go.PM)}function uL(t,e){t.imply("day",e.date()),t.imply("month",e.month()+1),t.imply("year",e.year())}function Lq(t,e){t.imply("hour",e.hour()),t.imply("minute",e.minute()),t.imply("second",e.second()),t.imply("millisecond",e.millisecond())}var vFe=F(wM(),1);var Rnn={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=>szt(t,Oh.MARCH,yu.SUNDAY,2),dstEnd:t=>szt(t,Oh.OCTOBER,yu.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=>xM(t,Oh.MARCH,yu.SUNDAY,2,2),dstEnd:t=>xM(t,Oh.NOVEMBER,yu.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=>xM(t,Oh.MARCH,yu.SUNDAY,2,2),dstEnd:t=>xM(t,Oh.NOVEMBER,yu.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=>xM(t,Oh.MARCH,yu.SUNDAY,2,2),dstEnd:t=>xM(t,Oh.NOVEMBER,yu.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=>xM(t,Oh.MARCH,yu.SUNDAY,2,2),dstEnd:t=>xM(t,Oh.NOVEMBER,yu.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 xM(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-08-12 16:40:13 +08:00
reference: ${JSON.stringify(this.reference)}]`}dayjs(){return(0,X9.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,X9.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?(ole(o,n),Bb(o,n),e.timezoneOffset!==null&&o.assign("timezoneOffset",-e.instant.getTimezoneOffset())):(Lq(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}},iE=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 yo(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 wFe(t,e,r="\\s{0,5},?\\s{0,5}"){let n=e.replace(/\((?!\?)/g,"(?:");return`${t}${n}(?:${r}${n}){0,10}`}function Nnn(t){let e;return t instanceof Array?e=[...t]:t instanceof Map?e=Array.from(t.keys()):e=Object.keys(t),e}function Sd(t){return`(?:${Nnn(t).sort((r,n)=>n.length-r.length).join("|").replace(/\./g,"\\.")})`}var lzt=F(wM(),1);function ale(t){return t<100&&(t>50?t=t+1900:t=t+2e3),t}function CM(t,e,r){let n=(0,lzt.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 CFe={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},OFe={january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12},ey={...OFe,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},xFe={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12},SFe={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},dzt={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"},Q9={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-08-12 16:40:13 +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}},sK=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:mg,isVisible:!0,timestamp:Bs(new Date),sources:a}),i("")):n.signal.reason==="new-chat"&&i(""),J(`==== Chat Memory ====
`,this.chainManager.memoryManager.getMemory().chatHistory.messages.map(s=>s.content)),J(`==== Final AI Response ====
`,e),e}async handleError(e,r,n){let o=ci(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.
2025-07-05 20:48:33 +08:00
Path: Settings > copilot plugin > Basic Tab > Set Keys.
Or check model config
2025-08-12 16:40:13 +08:00
Error Details: `+s),r({message:s,isErrorMessage:!0,sender:mg,isVisible:!0,timestamp:Bs(new Date)})}else new hUt.Notice(s),fe(i)}},Rle=class extends sK{async run(e,r,n,o,i){let a=new aK(n);try{let l=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),c=vN(l),d=[],f=q_(),p=this.chainManager.chatModelManager.getChatModel();f&&d.push({role:$Y(p),content:f});for(let h of c)d.push({role:h.role,content:h.content});d.push({role:"user",content:e.message}),J(`==== Final Request to AI ====
`,d);let m=await rb(()=>this.chainManager.chatModelManager.getChatModel().stream(d,{signal:r.signal}));for await(let h of m){if(r.signal.aborted){J("Stream iteration aborted",{reason:r.signal.reason});break}a.processChunk(h)}}catch(u){u.name==="AbortError"||r.signal.aborted?J("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)}},Nle=class extends sK{async run(e,r,n,o,i){let a=new aK(n);try{if(await this.chainManager.vectorStoreManager.isIndexEmpty())return this.handleResponse(zY,e,r,o,n);let c=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),d=vN(c),f=e.message;d.length>0&&(f=e.message);let m=await new EC({minSimilarityScore:.01,maxK:ae().maxSourceChunks,salientTerms:[]}).getRelevantDocuments(f);this.chainManager.storeRetrieverDocuments(m);let h=m.map(E=>E.pageContent).join(`
2025-07-05 20:48:33 +08:00
2025-08-12 16:40:13 +08:00
`),b=[],g=q_(),y=`
2025-07-05 20:48:33 +08:00
Answer the question with as detailed as possible based only on the following context:
2025-08-12 16:40:13 +08:00
`+h,x=g+y,S=this.chainManager.chatModelManager.getChatModel();x&&b.push({role:$Y(S),content:x});for(let E of d)b.push({role:E.role,content:E.content});b.push({role:"user",content:e.message}),J(`==== Final Request to AI ====
`,b);let O=await rb(()=>this.chainManager.chatModelManager.getChatModel().stream(b,{signal:r.signal}));for await(let E of O){if(r.signal.aborted){J("VaultQA stream iteration aborted",{reason:r.signal.reason});break}a.processChunk(E)}}catch(u){u.name==="AbortError"||r.signal.aborted?J("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=AGe(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-08-12 16:40:13 +08:00
`+n}return e}},uK=class extends sK{isYoutubeOnlyMessage(e){let r=e.trim(),n=r.includes("@youtube"),o=Qve(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 aL.processUrlBatch(e,r,this.chainManager.app.vault);return aL.showFailedImagesNotice(r),n}async processChatInputImages(e){let r=[],n=await aL.processChatImageBatch(e,r,this.chainManager.app.vault);return aL.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=ae(),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-08-12 16:40:13 +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=vN(a),u=[],l=await this.getSystemPrompt();s.length>0&&(l+=`
2025-07-05 20:48:33 +08:00
2025-08-12 16:40:13 +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:$Y(c),content:`${l}
IMPORTANT: Maintain consistency with previous responses in the conversation. If you've provided information about a person or topic before, use that same information in follow-up questions.`});for(let g of s)u.push({role:g.role,content:g.content});let d=this.chainManager.chatModelManager.getChatModel(),p=this.isMultimodalModel(d)?await this.buildMessageContent(e,r):e;u.push({role:"user",content:p});let m=p instanceof Array?p[0].text:p;J("Enhanced user message: ",m),J(`==== Final Request to AI ====
`,u);let h=new aK(o),b=await rb(()=>this.chainManager.chatModelManager.getChatModel().stream(u,{signal:n.signal}));for await(let g of b){if(n.signal.aborted){J("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 x=Qve(e.message),S="Transcript not available. Only videos with the auto transcript option turned on are supported at the moment.";if(x)try{let O=await Wi.getInstance().youtube4llm(x);return O.response.transcript?this.handleResponse(O.response.transcript,e,r,o,n):this.handleResponse(S,e,r,o,n)}catch(O){return fe("Error processing YouTube video:",O),this.handleResponse(S,e,r,o,n)}}J("==== Step 1: Analyzing intent ====");let d,f=e.originalMessage||e.message;try{d=await hL.analyzeIntent(f)}catch(x){return this.handleResponse(CGe(x),e,r,o,n)}let p=e.message.split(" ").filter(x=>!iK.includes(x.toLowerCase())).join(" ").trim(),m=await this.executeToolCalls(d,a),h=m.find(x=>x.tool==="localSearch"&&x.output&&x.output.length>0),g=await this.chainManager.memoryManager.getMemory().loadMemoryVariables({}),y=vN(g);if(h){J("==== Step 2: Processing local search results ====");let x=JSON.parse(h.output);J("==== Step 3: Condensing Question ====");let S=await rle(p,y);J("Condensed standalone question: ",S),J("==== Step 4: Preparing context ====");let O=this.getTimeExpression(d),E=this.prepareLocalSearchResult(x,O),P=m.filter(R=>R.tool==="getCurrentTime"),A=this.prepareEnhancedUserMessage(S,P);J(E),J("==== Step 5: Invoking QA Chain ====");let I=await this.chainManager.promptManager.getQAPrompt({question:A,context:E,systemMessage:""});s=await this.streamMultimodalResponse(I,e,r,c),u=this.getSources(x)}else{let x=this.prepareEnhancedUserMessage(p,m);J("No local search results. Using standard LLM Chain."),s=await this.streamMultimodalResponse(x,e,r,c)}}catch(d){a?.(K_.DEFAULT),d.name==="AbortError"||r.signal.aborted?J("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)?(dg("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){dg("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){J(`==== Step 2: Calling tool: ${o.tool.name} ====`),o.tool.name==="localSearch"?r?.(K_.READING_FILES):o.tool.name==="webSearch"?r?.(K_.SEARCHING_WEB):o.tool.name==="getFileTree"&&r?.(K_.READING_FILE_TREE);let i=await Dq.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-08-12 16:40:13 +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>iwe){let s=iwe/o;J("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-08-12 16:40:13 +08:00
${a}`}async getSystemPrompt(){return q_()}},jle=class extends uK{async getSystemPrompt(){let e=q_(),r=iu();if(!r)return e;let n=await Ec.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-08-12 16:40:13 +08:00
</project_context>`),e}};Tn();er();on();sA();var hme=require("obsidian");Us();Ur();CN();Tn();er();on();a9();var gL="0.39.0";var gUt=!1,yL,bke,Pan,Ean,Tan,yUt,Aan,Dle,_ke,bUt,vke,Lle,_Ut;function vUt(t,e={auto:!1}){if(gUt)throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${t.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(yL)throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${t.kind}'\` after \`import '@anthropic-ai/sdk/shims/${yL}'\``);gUt=e.auto,yL=t.kind,bke=t.fetch,Pan=t.Request,Ean=t.Response,Tan=t.Headers,yUt=t.FormData,Aan=t.Blob,Dle=t.File,_ke=t.ReadableStream,bUt=t.getMultipartRequestOptions,vke=t.getDefaultAgent,Lle=t.fileFromPath,_Ut=t.isFsReadStream}var Fle=class{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}};function wUt({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 Fle(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}}yL||vUt(wUt(),{auto:!0});var Dr=class extends Error{},Mc=class t extends Dr{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 FM({message:n,cause:kle(r)});let i=r;return e===400?new lK(e,i,n,o):e===401?new cK(e,i,n,o):e===403?new dK(e,i,n,o):e===404?new fK(e,i,n,o):e===409?new pK(e,i,n,o):e===422?new mK(e,i,n,o):e===429?new hK(e,i,n,o):e>=500?new gK(e,i,n,o):new t(e,i,n,o)}},Cd=class extends Mc{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},FM=class extends Mc{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},i2=class extends FM{constructor({message:e}={}){super({message:e??"Request timed out."})}},lK=class extends Mc{},cK=class extends Mc{},dK=class extends Mc{},fK=class extends Mc{},pK=class extends Mc{},mK=class extends Mc{},hK=class extends Mc{},gK=class extends Mc{};var $le=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},bL=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
`):[]}};Th=new WeakMap;dE.NEWLINE_CHARS=new Set([`
`,"\r"]);dE.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ran(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 xUt(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 yK(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 TC=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 Nan(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 Mc.generate(void 0,`SSE Error: ${a.data}`,a.data,xke(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 dE,s=yK(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 _ke({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*Nan(t,e){if(!t.body)throw e.abort(),new Dr("Attempted to iterate over a response with no body");let r=new wke,n=new dE,o=yK(t.body);for await(let i of jan(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*jan(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=xUt(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}var wke=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]=Dan(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}};function Dan(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var Lan=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",Fan=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&bK(t),bK=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 SUt(t,e,r){if(t=await t,Fan(t))return t;if(Lan(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=bK(o)?[await o.arrayBuffer()]:[o];return new Dle(i,e,r)}let n=await kan(t);if(e||(e=zan(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new Dle(n,e,r)}async function kan(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(bK(t))e.push(await t.arrayBuffer());else if(Ban(t))for await(let r of t)e.push(r);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${$an(t)}`);return e}function $an(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function zan(t){return Ske(t.name)||Ske(t.filename)||Ske(t.path)?.split(/[\\/]/).pop()}var Ske=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},Ban=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Cke=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody";var qan=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},Han=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)},zle;async function TUt(t){let{response:e}=t;if(t.options.stream)return a2("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):TC.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 a2("response",e.status,e.url,e.headers,i),AUt(i,e)}let o=await e.text();return a2("response",e.status,e.url,e.headers,o),o}function AUt(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 Ule=class t extends Promise{constructor(e,r=TUt){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=r}_thenUnwrap(e){return new t(this.responsePromise,async r=>AUt(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)}},qle=class{constructor({baseURL:e,maxRetries:r=2,timeout:n=6e5,httpAgent:o,fetch:i}){this.baseURL=e,this.maxRetries=Oke("maxRetries",r),this.timeout=Oke("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 Qle.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}})}};$M.Batches=vL;$M.BetaMessageBatchesPage=l2;var IC=class extends Rc{constructor(){super(...arguments),this.models=new _L(this._client),this.messages=new $M(this._client)}};IC.Models=_L;IC.BetaModelInfosPage=s2;IC.Messages=$M;var wL=class extends Rc{create(e,r){return this._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...r,stream:e.stream??!1})}};var xL=class extends Rc{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 ay(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",f2,{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 Dr(`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)=>u2.fromResponse(i.response,i.controller))}},f2=class extends AC{};xL.MessageBatchesPage=f2;var Mf=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},Mn=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)},uy,zM,OK,ece,PK,EK,tce,TK,pE,AK,rce,nce,p2,oce,ice,Rke,LUt,Nke,jke,Dke,Lke,FUt,kUt="__json_buf",ace=class t{constructor(){uy.add(this),this.messages=[],this.receivedMessages=[],zM.set(this,void 0),this.controller=new AbortController,OK.set(this,void 0),ece.set(this,()=>{}),PK.set(this,()=>{}),EK.set(this,void 0),tce.set(this,()=>{}),TK.set(this,()=>{}),pE.set(this,{}),AK.set(this,!1),rce.set(this,!1),nce.set(this,!1),p2.set(this,!1),oce.set(this,void 0),ice.set(this,void 0),Nke.set(this,e=>{if(Mf(this,rce,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new Cd),e instanceof Cd)return Mf(this,nce,!0,"f"),this._emit("abort",e);if(e instanceof Dr)return this._emit("error",e);if(e instanceof Error){let r=new Dr(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new Dr(String(e)))}),Mf(this,OK,new Promise((e,r)=>{Mf(this,ece,e,"f"),Mf(this,PK,r,"f")}),"f"),Mf(this,EK,new Promise((e,r)=>{Mf(this,tce,e,"f"),Mf(this,TK,r,"f")}),"f"),Mn(this,OK,"f").catch(()=>{}),Mn(this,EK,"f").catch(()=>{})}get response(){return Mn(this,oce,"f")}get request_id(){return Mn(this,ice,"f")}async withResponse(){let e=await Mn(this,OK,"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 ace.createMessage(this,e,r)}countTokens(e,r){return this._client.post("/v1/messages/count_tokens",{body:e,...r})}},$Ut={"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"};mE.Batches=xL;mE.MessageBatchesPage=f2;var BM=class extends Rc{retrieve(e,r){return this._client.get(`/v1/models/${e}`,r)}list(e={},r){return ay(e)?this.list({},e):this._client.getAPIList("/v1/models",SL,{query:e,...r})}},SL=class extends AC{};BM.ModelInfosPage=SL;var zUt,Si=class extends qle{constructor({baseURL:e=Vle("ANTHROPIC_BASE_URL"),apiKey:r=Vle("ANTHROPIC_API_KEY")??null,authToken:n=Vle("ANTHROPIC_AUTH_TOKEN")??null,...o}={}){let i={apiKey:r,authToken:n,...o,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&MUt())throw new Dr(`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-08-12 16:40:13 +08:00
`);super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new wL(this),this.messages=new mE(this),this.models=new BM(this),this.beta=new IC(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&&!_K(r)?r:n!=null&&!_K(n)?n:{}}apiKeyAuth(e){return this.apiKey==null?{}:{"X-Api-Key":this.apiKey}}bearerAuth(e){return this.authToken==null?{}:{Authorization:`Bearer ${this.authToken}`}}};zUt=Si;Si.Anthropic=zUt;Si.HUMAN_PROMPT=`
2025-07-05 20:48:33 +08:00
2025-08-12 16:40:13 +08:00
Human:`;Si.AI_PROMPT=`
2025-07-05 20:48:33 +08:00
2025-08-12 16:40:13 +08:00
Assistant:`;Si.DEFAULT_TIMEOUT=6e5;Si.AnthropicError=Dr;Si.APIError=Mc;Si.APIConnectionError=FM;Si.APIConnectionTimeoutError=i2;Si.APIUserAbortError=Cd;Si.NotFoundError=fK;Si.ConflictError=pK;Si.RateLimitError=hK;Si.BadRequestError=lK;Si.AuthenticationError=cK;Si.InternalServerError=gK;Si.PermissionDeniedError=dK;Si.UnprocessableEntityError=mK;Si.toFile=SUt;Si.fileFromPath=Lle;Si.Completions=wL;Si.Messages=mE;Si.Models=BM;Si.ModelInfosPage=SL;Si.Beta=IC;var{HUMAN_PROMPT:oai,AI_PROMPT:iai}=Si;As();Of();Kn();iC();bh();ug();Jp();CD();_h();eb();var IK=class extends cN{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 Km(`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 Km(`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)?Fke(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 Fke(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 BUt(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:typeof t=="string"?{type:"tool",name:t}:t}As();function UUt(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 qUt(t){let e=Xk({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-08-12 16:40:13 +08:00
`))}function csn(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 $s({content:[{type:"tool_result",content:r.content,tool_use_id:r.tool_call_id}]}))}else e.push(new $s({content:[{type:"tool_result",content:kke(r.content),tool_use_id:r.tool_call_id}]}));else e.push(r);return e}function HUt(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 dsn={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=Xk({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 kke(t){let e=["tool_use","tool_result","input_json_delta"],r=["text","text_delta"];return typeof t=="string"?t:t.map(o=>{if(Jy(o))return SH(o,dsn);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=qUt(o.image_url):a=qUt(o.image_url.url),{type:"image",source:a,...i?{cache_control:i}:{}}}else{if(UUt(o))return o;if(o
2025-07-05 20:48:33 +08:00
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
2025-08-12 16:40:13 +08:00
`,t}function $ke(t){let e;return t.status===400&&t.message.includes("tool")?e=uce(t,"INVALID_TOOL_RESULTS"):t.status===401?e=uce(t,"MODEL_AUTHENTICATION"):t.status===404?e=uce(t,"MODEL_NOT_FOUND"):t.status===429?e=uce(t,"MODEL_RATE_LIMIT"):e=t,e}function psn(t){return!!(t.tools&&t.tools.length>0)}function msn(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 hsn(t){return!!(t.thinking&&t.thinking.type==="enabled")}function gsn(t){return"input_schema"in t}function ysn(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 zke=class extends du{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??ct("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 Si(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
`):[]}};Ih=new WeakMap;EL.NEWLINE_CHARS=new Set([`
`,"\r"]);EL.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Msn(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 rqt(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 Xke(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 NC=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 Rsn(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 bu(void 0,s.error,void 0,e$e(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 bu(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 EL,s=Xke(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 Kke({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*Rsn(t,e){if(!t.body)throw e.abort(),new Bt("Attempted to iterate over a response with no body");let r=new Qke,n=new EL,o=Xke(t.body);for await(let i of Nsn(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*Nsn(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=rqt(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}var Qke=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]=jsn(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}};function jsn(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}var nqt=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",oqt=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&MK(t),MK=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",Dsn=t=>oqt(t)||nqt(t)||Zke(t);async function n$e(t,e,r){if(t=await t,oqt(t))return t;if(nqt(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=MK(o)?[await o.arrayBuffer()]:[o];return new fce(i,e,r)}let n=await Lsn(t);if(e||(e=ksn(t)??"unknown_file"),!r?.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new fce(n,e,r)}async function Lsn(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(MK(t))e.push(await t.arrayBuffer());else if($sn(t))for await(let r of t)e.push(r);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${Fsn(t)}`);return e}function Fsn(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function ksn(t){return t$e(t.name)||t$e(t.filename)||t$e(t.path)?.split(/[\\/]/).pop()}var t$e=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},$sn=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",o$e=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody";var ly=async t=>{let e=await iqt(t.body);return Gke(e,t)},iqt=async t=>{let e=new Wke;return await Promise.all(Object.entries(t||{}).map(([r,n])=>r$e(e,r,n))),e};var r$e=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(Dsn(r)){let n=await n$e(r);t.append(e,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>r$e(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>r$e(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 Bsn=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},Usn=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)},yce;Yke();async function dqt(t){let{response:e}=t;if(t.options.stream)return gE("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):NC.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 gE("response",e.status,e.url,e.headers,a),fqt(a,e)}let i=await e.text();return gE("response",e.status,e.url,e.headers,i),i}function fqt(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})}var _ce=class t extends Promise{constructor(e,r=dqt){supe
\r `.includes(t[n]);)n++};return a()},_$e=t=>aun(t,Nc.ALL^Nc.NUM);var M2=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},Fi=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)},nc,vE,R2,GM,v$e,Tce,w$e,x$e,S$e,Ace,C$e,Oqt,N2=class t extends I2{constructor(e){super(),nc.add(this),vE.set(this,void 0),R2.set(this,void 0),GM.set(this,void 0),M2(this,vE,e,"f"),M2(this,R2,[],"f")}get currentChatCompletionSnapshot(){return Fi(this,GM,"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())),Fi(this,nc,"m",v$e).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)Fi(this,nc,"m",w$e).call(this,a);if(i.controller.signal?.aborted)throw new xa;return this._addChatCompletion(Fi(this,nc,"m",Ace).call(this))}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),Fi(this,nc,"m",v$e).call(this),this._connected();let o=NC.fromReadableStream(e,this.controller),i;for await(let a of o)i&&i!==a.id&&this._addChatCompletion(Fi(this,nc,"m",Ace).call(this)),Fi(this,nc,"m",w$e).call(this,a),i=a.id;if(o.controller.signal?.aborted)throw new xa;return this._addChatCompletion(Fi(this,nc,"m",Ace).call(this))}[(vE=new WeakMap,R2=new WeakMap,GM=new WeakMap,nc=new WeakSet,v$e=function(){this.ended||M2(this,GM,void 0,"f")},Tce=function(r){let n=Fi(this,R2,"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},Fi(this,R2,"f")[r.index]=n,n)},w$e=function(r){if(this.ended)return;let n=Fi(this,nc,"m",Oqt).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=Fi(this,nc,"m",Tce).call(this,i);i.finish_reason&&(Fi(this,nc,"m",S$e).call(this,i),a.current_tool_call_index!=null&&Fi(this,nc,"m",x$e).call(this,i,a.current_tool_call_index));for(let s of o.delta.tool_calls??[])a.current_tool_call_index!==s.index&&(Fi(this,nc,"m",S$e).call(this,i),a.current_tool_call_index!=null&&Fi(this,nc,"m",x$e).call(this,i,a.current_tool_call_index)),a.current_tool_call_index=s.index;for(let s of o.delta.tool_calls??[]){let u=i.message.tool_calls?.[s.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:s.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arg
${Ice(t)}`);if(E==null)throw new Bt(`missing choices[${d}].tool_calls[${S}].type
${Ice(t)}`);if(R==null)throw new Bt(`missing choices[${d}].tool_calls[${S}].function.name
${Ice(t)}`);if(I==null)throw new Bt(`missing choices[${d}].tool_calls[${S}].function.arguments
${Ice(t)}`);return{...A,id:P,type:E,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 vqt(u,e)}function Ice(t){return JSON.stringify(t)}var UK=class t extends N2{static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static runFunctions(e,r,n){let o=new t(null),i={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return o._run(()=>o._runFunctions(e,r,i)),o}static runTools(e,r,n){let o=new t(r),i={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(e,r,i)),o}};var qK=class extends it{parse(e,r){return xqt(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap(n=>zK(n,e))}runFunctions(e,r){return e.stream?UK.runFunctions(this._client,e,r):BK.runFunctions(this._client,e,r)}runTools(e,r){return e.stream?UK.runTools(this._client,e,r):BK.runTools(this._client,e,r)}stream(e,r){return N2.createChatCompletion(this._client,e,r)}};var j2=class extends it{constructor(){super(...arguments),this.completions=new qK(this._client)}};(function(t){t.Completions=qK})(j2||(j2={}));var D2=class extends it{create(e,r){return this._client.post("/realtime/sessions",{body:e,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}};var L2=class extends it{create(e,r){return this._client.post("/realtime/transcription_sessions",{body:e,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}};var JM=class extends it{constructor(){super(...arguments),this.sessions=new D2(this._client),this.transcriptionSessions=new L2(this._client)}};JM.Sessions=D2;JM.TranscriptionSessions=L2;var tr=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)},Mh=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},Od,O$e,LC,Mce,Jb,RL,F2,ML,jce,Rh,Rce,Nce,WK,HK,VK,Pqt,Eqt,Tqt,Aqt,Iqt,Mqt,Rqt,FC=class t extends KM{constructor(){super(...arguments),Od.add(this),O$e.set(this,[]),LC.set(this,{}),Mce.set(this,{}),Jb.set(this,void 0),RL.set(this,void 0),F2.set(this,void 0),ML.set(this,void 0),jce.set(this,void 0),Rh.set(this,void 0),Rce.set(this,void 0),Nce.set(this,void 0),WK.set(this,void 0)}[(O$e=new WeakMap,LC=new WeakMap,Mce=new WeakMap,Jb=new WeakMap,RL=new WeakMap,F2=new WeakMap,ML=new WeakMap,jce=new WeakMap,Rh=new WeakMap,Rce=new WeakMap,Nce=new WeakMap,WK=new WeakMap,Od=new WeakSet,Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",o=>{let i=r.shift();i?i.resolve(o):e.push(o)}),this.on("end",()=>{n=!0;for(let o of r)o.resolve(void 0);r.length=0}),this.on("abort",o=>{n=!0;for(let i of r)i.reject(o);r.length=0}),this.on("error",o=>{n=!0;for(let i of r)i.reject(o);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((i,a)=>r.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let r=new t;return r._run(()=>r._fromReadableStream(e)),r}async _fromReadableStream(e,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();let o=NC.fromReadableStream(e,this.controller);for await(let i of o)tr(this,Od,"m",HK).call(this,i);if(o.controller.signal?.aborted)throw new xa;return this._addRun(tr(this,Od,"m",VK).call(this))}
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-08-12 16:40:13 +08:00
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
`);super({baseURL:a.baseURL,timeout:a.timeout??6e5,httpAgent:a.httpAgent,maxRetries:a.maxRetries,fetch:a.fetch}),this.completions=new DL(this),this.chat=new bE(this),this.embeddings=new LL(this),this.files=new ZM(this),this.images=new UL(this),this.audio=new DC(this),this.moderations=new HL(this),this.models=new XM(this),this.fineTuning=new Yb(this),this.vectorStores=new Nh(this),this.beta=new Zb(this),this.batches=new VM(this),this.uploads=new rR(this),this.responses=new tR(this),this.evals=new $C(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 Hke(e,{arrayFormat:"brackets"})}};$qt=wr;wr.OpenAI=$qt;wr.DEFAULT_TIMEOUT=6e5;wr.OpenAIError=Bt;wr.APIError=bu;wr.APIConnectionError=hE;wr.APIConnectionTimeoutError=Ah;wr.APIUserAbortError=xa;wr.NotFoundError=y2;wr.ConflictError=b2;wr.RateLimitError=v2;wr.BadRequestError=m2;wr.AuthenticationError=h2;wr.InternalServerError=w2;wr.PermissionDeniedError=g2;wr.UnprocessableEntityError=_2;wr.toFile=n$e;wr.fileFromPath=pce;wr.Completions=DL;wr.Chat=bE;wr.ChatCompletionsPage=HM;wr.Embeddings=LL;wr.Files=ZM;wr.FileObjectsPage=$L;wr.Images=UL;wr.Audio=DC;wr.Moderations=HL;wr.Models=XM;wr.ModelsPage=qL;wr.FineTuning=Yb;wr.VectorStores=Nh;wr.VectorStoresPage=VL;wr.VectorStoreSearchResponsesPage=WL;wr.Beta=Zb;wr.Batches=VM;wr.BatchesPage=TL;wr.Uploads=rR;wr.Responses=tR;wr.Evals=$C;wr.EvalListResponsesPage=kL;As();Of();Kn();iC();bh();Jp();eb();yq();ug();var Bqt=Symbol("Let zodToJsonSchema decide on which parser to use"),zqt={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"},Uqt=t=>typeof t=="string"?{...zqt,basePath:["#"],definitions:{},name:t}:{...zqt,basePath:["#"],definitions:{},...t};var KK=t=>"_def"in t?t._def:t;function qqt(t){if(!t)return!0;for(let e in t)return!1;return!0}var Hqt=t=>{let e=Uqt(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])=>[KK(o),{def:KK(o),path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function T$e(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function io(t,e,r,n,o){t[e]=r,T$e(t,e,n,o)}Qf();function Vqt(){return{}}Qf();function Wqt(t,e){let r={type:"array"};return t.type?._def?.typeName!==re.ZodAny&&(r.items=xr(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&io(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&io(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(io(r,"minItems",t.exactLength.value,t.exactLength.message,e),io(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Kqt(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?io(r,"minimum",n.value,n.message,e):io(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),io(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?io(r,"maximum",n.value,n.message,e):io(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),io(r,"maximum",n.value,n.message,e));break;case"multipleOf":io(r,"multipleOf",n.value,n.message,e);break}return r}function Gqt(){return{type:"boolean"}}function Jqt(t,e){return xr(t.type._def,e)}var Zqt=(t,e)=>xr(t.innerType._def,e);function A$e(t,e,r){let n=r??e.dateStrate
]))`;continue}else if(o[l]==="$"){i+=`($|(?=[\r
]))`;continue}}if(n.s&&o[l]==="."){i+=s?`${o[l]}\r
`:`[${o[l]}\r
]`;continue}i+=o[l],o[l]==="\\"?a=!0:s&&o[l]==="]"?s=!1:!s&&o[l]==="["&&(s=!0)}try{let l=new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return i};function zce(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===re.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:xr(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:xr(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===re.ZodString&&t.keyType._def.checks?.length){let n=Object.entries($ce(t.keyType._def,e)).reduce((o,[i,a])=>i==="type"?o:{...o,[i]:a},{});return{...r,propertyNames:n}}else if(t.keyType?._def.typeName===re.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function n2t(t,e){if(e.mapStrategy==="record")return zce(t,e);let r=xr(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},n=xr(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}}}function o2t(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}}function i2t(){return{not:{}}}function a2t(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var GK={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function u2t(t,e){if(e.target==="openApi3")return s2t(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in GK&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let a=GK[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 s2t(t,e)}var s2t=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>xr(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 l2t(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:GK[t.innerType._def.typeName],nullable:!0}:{type:[GK[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=xr(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=xr(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function c2t(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",T$e(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?io(r,"minimum",n.value,n.message,e):io(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),io(r,"minimum",n.value,n.message,e));break;case"max":
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:kun(t,e)};return r.required.length||delete r.required,r}var f2t=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return xr(t.innerType._def,e);let r=xr(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}};var p2t=(t,e)=>{if(e.pipeStrategy==="input")return xr(t.in._def,e);if(e.pipeStrategy==="output")return xr(t.out._def,e);let r=xr(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=xr(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function m2t(t,e){return xr(t.type._def,e)}function h2t(t,e){let n={type:"array",uniqueItems:!0,items:xr(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&io(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&io(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function g2t(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>xr(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:xr(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>xr(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function y2t(){return{not:{}}}function b2t(){return{}}var _2t=(t,e)=>xr(t.innerType._def,e);function xr(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==Bqt)return a}if(n&&!r){let a=$un(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=Uun(t,t.typeName,e,r);return i&&qun(t,e,i),o.jsonSchema=i,i}var $un=(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:zun(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}},zun=(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("/")},Uun=(t,e,r,n)=>{switch(e){case re.ZodString:return $ce(t,r);case re.ZodNumber:return c2t(t,r);case re.ZodObject:return d2t(t,r);case re.ZodBigInt:return Kqt(t,r);case re.ZodBoolean:return Gqt();case re.ZodDate:return A$e(t,r);case re.ZodUndefined:return y2t();case re.ZodNull:return a2t(r);case re.ZodArray:return Wqt(t,r);case re.ZodUnion:case re.ZodDiscriminatedUnion:return u2t(t,r);case re.ZodIntersection:return e2t(t,r);case re.ZodTuple:return g2t(t,r);case re.ZodRecord:return zce(t,r);case re.ZodLiteral:return t2t(t,r);case re.ZodEnum:return Qqt(t);case re.ZodNativeEnum:return o2t(t);case re.ZodNullable:return l2t(t,r);case re.ZodOptional:return f2t(t,r);case re.ZodMap:return n2t(t,r);case re.ZodSet:return h2t(t,r);case re.ZodLazy:return xr(t.getter()._def,r);case re.ZodPromise:return m2t(t,r);case re.ZodNaN:case re.ZodNever:return i2t();case re.ZodEffects:return Xqt(t,r,n);case re.ZodAny:return Vqt();case re.ZodUnknown:return b2t();case re.ZodDefault:return Yqt(t,r);case re.ZodBranded:return Jqt(t,r);case re.ZodReadonly:return _2t(t,r);case re.ZodCatch:return Zqt(t,r);case re.ZodPipeline:return p2t(t,r);case re.ZodFunction:case re.ZodVoid:case re.ZodSymbol:return;default:return(o=>{})(e)}},qun=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var v2t=(t,e)=>{let r=Hqt(e),n=typeof e=="string"?e:e?.nam
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
`,t}function JL(t){let e;return t.constructor.name===Ah.name?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===xa.name?(e=new Error(t.message),e.name="AbortError"):t.status===400&&t.message.includes("tool_calls")?e=JK(t,"INVALID_TOOL_RESULTS"):t.status===401?e=JK(t,"MODEL_AUTHENTICATION"):t.status===429?e=JK(t,"MODEL_RATE_LIMIT"):t.status===404?e=JK(t,"MODEL_NOT_FOUND"):e=t,e}function M$e(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 Hun(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function x2t(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(S2t(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
`)}function S2t(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}: ${qce(o,e)},`):r.push(`${n}?: ${qce(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
`)}function qce(t,e){if(Hun(t))return t.anyOf.map(r=>qce(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["{",S2t(t,e+2),"}"].join(`
`);case"array":return t.items?`${qce(t.items,e)}[]`:"any[]";default:return""}}_h();function C2t(t,e){let r;if(Cc(t)){let n=Uce({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:GI(t,e)}}else r=t;return e?.strict!==void 0&&(r.function.strict=e.strict),r}function Vun(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 j$e(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(!ks.isInstance(t))throw new Error("Invalid generic chat message");return Vun(t)}default:throw new Error(`Unknown message type: ${e}`)}}function N$e(t,e){return t.flatMap(r=>{let n=j$e(r);n==="system"&&D$e(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=""),Di(r)&&r.tool_calls?.length?(o.tool_calls=r.tool_calls.map(_C),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 Q2="__openai_function_call_ids__";function O2t(t,e){return t.flatMap(r=>{let n=j$e(r);if(n==="system"&&D$e(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[Q2];if(Di(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==="in
`);o.enqueue(s)}catch(i){o.error(i)}},async cancel(){await r.return?.()}})}},H$e=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]=eln(e,":");return o.startsWith(" ")&&(o=o.substring(1)),r==="event"?this.event=o:r==="data"&&this.data.push(o),null}},u4=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 jc(`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 jc(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new jc("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}};u4.NEWLINE_CHARS=new Set([`
`,"\r","\v","\f","","","","\x85","\u2028","\u2029"]);u4.NEWLINE_REGEXP=/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g;function eln(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}function M2t(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 R2t=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",N2t=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Yce(t),Yce=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",tln=t=>N2t(t)||R2t(t)||U$e(t);async function K$e(t,e,r){if(t=await t,r??(r=N2t(t)?{lastModified:t.lastModified,type:t.type}:{}),R2t(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file"),new Wce([o],e,r)}let n=await rln(t);if(e||(e=oln(t)??"unknown_file"),!r.type){let o=n[0]?.type;typeof o=="string"&&(r={...r,type:o})}return new Wce(n,e,r)}async function rln(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Yce(t))e.push(await t.arrayBuffer());else if(iln(t))for await(let r of t)e.push(r);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${nln(t)}`);return e}function nln(t){return`[${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}function oln(t){return V$e(t.name)||V$e(t.filename)||V$e(t.path)?.split(/[\\/]/).pop()}var V$e=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},iln=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",G$e=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody";var YK=async t=>{let e=await j2t(t.body);return z$e(e,t)},j2t=async t=>{let e=new k$e;return await Promise.all(Object.entries(t||{}).map(([r,n])=>W$e(e,r,n))),e};var W$e=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(tln(r)){let n=await K$e(r);t.append(e,n)}else if(Array.isArray(r))await Promise.all(r.map(n=>W$e(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,o])=>W$e(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 sln=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},uln=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)},Xce;async function z2t(t){let{response:e}=t;if(t.options.stream)return l4("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):Zce.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 l4("response",e.status,e.url,e.headers,i),i}let o=await e.text();return l4("response",e.status,e.url,e.headers,o),o}var Qce=class t extends Promise{constructor(e
This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
new Groq({ apiKey, dangerouslyAllowBrowser: true })`);super({baseURL:o.baseURL,timeout:o.timeout??6e4,httpAgent:o.httpAgent,maxRetries:o.maxRetries,fetch:o.fetch}),this.completions=new uR(this),this.chat=new sR(this),this.embeddings=new lR(this),this.audio=new aR(this),this.models=new cR(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}`}}};U2t=Rs;Rs.Groq=U2t;Rs.GroqError=jc;Rs.APIError=oc;Rs.APIConnectionError=SE;Rs.APIConnectionTimeoutError=XL;Rs.APIUserAbortError=iR;Rs.NotFoundError=n4;Rs.ConflictError=o4;Rs.RateLimitError=a4;Rs.BadRequestError=e4;Rs.AuthenticationError=t4;Rs.InternalServerError=s4;Rs.PermissionDeniedError=r4;Rs.UnprocessableEntityError=i4;Rs.toFile=K$e;Rs.fileFromPath=Kce;var{GroqError:Fhi,APIError:khi,APIConnectionError:$hi,APIConnectionTimeoutError:zhi,APIUserAbortError:Bhi,NotFoundError:Uhi,ConflictError:qhi,RateLimitError:Hhi,BadRequestError:Vhi,AuthenticationError:Whi,InternalServerError:Khi,PermissionDeniedError:Ghi,UnprocessableEntityError:Jhi}=q$e;(function(t){t.Completions=uR,t.Chat=sR,t.Embeddings=lR,t.Audio=aR,t.Models=cR})(Rs||(Rs={}));var q2t=Rs;Jp();eb();yq();_h();function Oln(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 H2t(t){return t.map(e=>{if(typeof e.content!="string")throw new Error("Non string message content not supported");let r={role:Oln(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 Di(e)&&e.tool_calls?.length?r.tool_calls=e.tool_calls.map(_C):(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 Pln(t,e){let r=t.tool_calls;switch(t.role){case"assistant":{let n=[],o=[];for(let i of r??[])try{n.push(bm(i,{returnId:!0}))}catch(a){o.push(_m(i,a.message))}return new En({content:t.content||"",additional_kwargs:{tool_calls:r},tool_calls:n,invalid_tool_calls:o,usage_metadata:e})}default:return new ks(t.content||"",t.role??"unknown")}}function Eln(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 Tln(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 Yf({content:o})};if(n==="assistant"){let u=Eln(t.tool_calls,e);return{message:new yr({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 of({content:o})}:{message:new Zf({content:o,role:n})}}var tde=class extends du{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-08-12 16:40:13 +08:00
Received: ${JSON.stringify(o,null,2)}`)},n=o=>{if(Di(o)&&o.tool_calls?.length)return o.tool_calls.map(i=>({...i,id:kUe(i.id??"")})).map(_C)};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:kUe(o.tool_call_id)}:Di(o)?i===void 0?{role:e(o.getType()),content:a}:{role:e(o.getType()),toolCalls:i}:{role:e(o.getType()),content:a}})}function DMn(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=$Ue(r.content);switch(r.role){case"assistant":{let i=[],a=[];for(let s of n)try{let u=bm(s,{returnId:!0});i.push({...u,id:u.id??ode().replace(/-/g,"")})}catch(u){a.push(_m(s,u.message))}return new En({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 $s({content:o})}}function LMn(t,e){if(!t.content&&!t.toolCalls)return e?new yr({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??ode().replace(/-/g,""),type:"function"})):void 0,n="assistant";t.role&&(n=t.role);let o=$Ue(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 Yf({content:o}):n==="assistant"?new yr({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 sg({content:o,additional_kwargs:i,tool_call_id:r?.[0].id??""}):n==="function"?new Um({content:o,additional_kwargs:i}):new Zf({content:o,role:n})}function XKt(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:Ga(e.schema)}}})}var lme=class extends du{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-08-12 16:40:13 +08:00
`,t}function jF(t){let e;return t.constructor.name===Ah.name?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===xa.name?(e=new Error(t.message),e.name="AbortError"):t.status===400&&t.message.includes("tool_calls")?e=FG(t,"INVALID_TOOL_RESULTS"):t.status===401?e=FG(t,"MODEL_AUTHENTICATION"):t.status===429?e=FG(t,"MODEL_RATE_LIMIT"):t.status===404?e=FG(t,"MODEL_NOT_FOUND"):e=t,e}function zUe(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 FMn(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function rGt(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(nGt(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
`)}function nGt(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}: ${cme(o,e)},`):r.push(`${n}?: ${cme(o,e)},`);return r.map(n=>" ".repeat(e)+n).join(`
`)}function cme(t,e){if(FMn(t))return t.anyOf.map(r=>cme(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["{",nGt(t,e+2),"}"].join(`
`);case"array":return t.items?`${cme(t.items,e)}[]`:"any[]";default:return""}}_h();function oGt(t,e){let r;if(Cc(t)){let n=Uce({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:GI(t,e)}}else r=t;return e?.strict!==void 0&&(r.function.strict=e.strict),r}function kMn(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 qUe(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(!ks.isInstance(t))throw new Error("Invalid generic chat message");return kMn(t)}default:throw new Error(`Unknown message type: ${e}`)}}function UUe(t,e){return t.flatMap(r=>{let n=qUe(r);n==="system"&&HUe(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=""),Di(r)&&r.tool_calls?.length?(o.tool_calls=r.tool_calls.map(_C),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 F4="__openai_function_call_ids__";function iGt(t,e){return t.flatMap(r=>{let n=qUe(r);if(n==="system"&&HUe(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[F4];if(Di(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==="in
without CORS Error: `+ci(n)+`
with CORS Error: `+ci(o);throw new Error(i)}}}findModelByName(e){return ae().activeModels.find(n=>n.name===e)}};Bc.REASONING_MODEL_TEMPERATURE=1;var DF=Bc;er();As();var k4=class{},uGt=(t,e)=>{if(e!==void 0)return t[e];let r=Object.keys(t);if(r.length===1)return t[r[0]]},mme=(t,e)=>{let r=uGt(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},WUe=(t,e)=>{let r=uGt(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};Q1();lN();var KUe=class extends kp{addUserMessage(e){return this.addMessage(new $s(e))}addAIChatMessage(e){return this.addMessage(new En(e))}addAIMessage(e){return this.addMessage(new En(e))}async addMessages(e){for(let r of e)await this.addMessage(r)}clear(){throw new Error("Not implemented.")}},$4=class extends KUe{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 s_=class extends k4{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 $4,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(mme(e,this.inputKey)),await this.chatHistory.addAIChatMessage(WUe(r,this.outputKey))}async clear(){await this.chatHistory.clear()}};var $G=class extends s_{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]:Xf(r,this.humanPrefix,this.aiPrefix)}}};As();As();GUe();sA();As();var zG=class extends s_{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]:Xf(r.slice(-this.k*2),this.humanPrefix,this.aiPrefix)}}};Kue();Mve();As();Q1();GUe();As();As();var BG=class t{constructor(){this.initMemory(),Ma(()=>{let e=this.memory?.chatHistory;this.initMemory(e)})}static g
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-08-12 16:40:13 +08:00
`;this.qaPrompt=Gp.fromMessages([aA.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 qG=class{constructor(e,r){this.retrievedDocuments=[];this.app=e,this.vectorStoreManager=r,this.memoryManager=BG.getInstance(),this.chatModelManager=DF.getInstance(),this.promptManager=UG.getInstance(),this.initialize(),Ma(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 hme.Notice(e),new Error(e)}}validateChainInitialization(){(!this.chain||!PGe(this.chain))&&(console.error("Chain is not initialized properly, re-initializing chain: ",bg()),this.createChainWithNewModel({},!1))}storeRetrieverDocuments(e){this.retrievedDocuments=e}async createChainWithNewModel(e={},r=!0){let n=bg(),o=iu();if(n==="project"&&!o)return;let i=n==="project"?o?.projectModelKey:ZY();if(!i)throw new hme.Notice("No model key found"),new Error("No model key found");try{if(r){let a=LY(i,ae().activeModels);if(a||(console.error("Resetting default model. No model configuration found for: ",i),a=H_[0],i=a.name+"|"+a.provider),n==="project"&&!a.projectEnabled){let u=ae().activeModels.find(l=>l.enabled&&l.projectEnabled);if(u)a=u,i=u.name+"|"+u.provider,new hme.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),J(`Setting model to ${i}`)}catch(a){fe(`createChainWithNewModel failed: ${a}`),J(`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=c6.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),ON("llm_chain");break}case"vault_qa":{await this.initializeQAChain(r);let a=new EC({minSimilarityScore:.01,maxK:ae().maxSourceChunks,salientTerms:[]});this.retrievalChain=c6.createConversationalRetrievalChain({llm:n,retriever:a,systemMessage:q_()},this.storeRetrieverDocuments.bind(this),ae().debug),ON("vault_qa"),ae().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=c6.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),ON("copilot_plus");break}case"project":{await this.initializeQAChain(r),this.chain=c6.createNewLLMChain({llm:n,memory:o,prompt:r.prompt||i,abortController:r.abortController}),ON("project");break}default:this.validateChainType(e);break}}getChainRunner(){let e=bg();switch(e){case"llm_chain":return new Rle(this);case"vault_qa":return new Nle(this);case"copilot_plus":return new uK(this);case"project":return new jle(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||l6(u)){let c=Gp.fromMessages([new B_("history"),U_.fromTemplate("{input}")]);l6(u)&&(c=Gp.fromMessages([[Ei,q_()||""],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===Ei&&await this.memoryManager.getMemory().saveContext({input:n.message},{output:o.message})}}};var Ec=class t{constructor(e,r,n){this.app=e,this.plugin=n,this.currentProjectId=null,this.chainMangerInstance=new qG(e,r),this.projectContextCache=zb.getInstance(),this.fileParserManager=new vM(Wi.getInstance(),this.app.vault,!0,null),pJe(async()=>{await this.getCurrentChainManager().createChainWithNewModel()}),mJe(async()=>{EN()||await this.getCurrentChainManager().createChainWithNewModel({refreshIndex:ae().indexVaultToVectorStore==="ON MODE SWITCH"&&(bg()==="vault_qa"||bg()==="copilot_plus")})}),L$(async o=>{await this.switchProject(o)}),this.setupProjectListChangeMonitor()}setupProjectListChangeMonitor(){Ma(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}getCurrentProjectId(){return this.currentProjectId}async switchProject(e){try{if(mA(!0),J("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 vM(Wi.getInstance(),this.app.vault,!0,e),await this.loadProjectContext(e),this.refreshChatView(),J(`Switched to project: ${e.name}`)}catch(r){throw fe(`Failed to switch project: ${r}`),r}finally{mA(!1)}}async saveCurrentProjectMessage(){await this.plugin.autosaveCurrentChat()}async loadNextProjectMessage(){await this.plugin.chatUIState.handleProjectSwitch()}async loadProjectContext(e){try{if(!e.contextSource)return dg(`[loadProjectContext] Project ${e.name}: No contextSource. Aborting.`),null;J(`[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?J(`[loadProjectContext] Project ${e.name}: Existing cache found. MarkdownNeedsReload: ${n.markdownNeedsReload}`):J(`[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(J(`[loadProjectContext] Project ${e.name}: Checking ${i} fileContexts for non-markdown processing.`),i>0){this.fileParserManager=new vM(Wi.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 HG.TFile&&u.extension!=="md"&&this.fileParserManager.supportsExtension(u.extension))try{await this.projectContextCache.getFileContext(e,s)||(J(`[loadProjectContext] Project ${e.name}: Parsing/caching new/updated file: ${s}`),await this.fileParserManager.parseFile(u,this.app.vault),a++)}catch(l){if(fe(`[loadProjectContext] Project ${e.name}: Error parsing file ${s}:`,l),sL(l))throw l}}a>0&&J(`[loadProjectContext] Project ${e.name}: Processed and cached ${a} non-markdown files.`)}}return o.timestamp=Date.now(),await this.projectContextCache.set(e,o),J(
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(`
2025-08-12 16:40:13 +08:00
`).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(xs)[0]?.view;e&&e.updateView()}async getProjectContext(e){let r=ae().projectList.find(o=>o.id===e);if(!r)return dg(`[getProjectContext] Project not found for ID: ${e}`),null;J(`[getProjectContext] Getting context for project: ${r.name} (ID: ${e})`);let n=this.projectContextCache.getSync(r);if(!n||n.markdownNeedsReload){n?J(`[getProjectContext] Project ${r.name}: Markdown needs reload. Triggering full load.`):J(`[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 J(`[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
2025-07-05 20:48:33 +08:00
${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>
2025-08-12 16:40:13 +08:00
`}async processMarkdownFiles(e,r){J(`[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&&J(`[processMarkdownFiles] Project ${e.name}: Added ${o-n} new file references via updateProjectFilesFromPatterns.`),r.markdownNeedsReload||!r.markdownContext||!r.markdownContext.trim()){J(`[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,J(`[processMarkdownFiles] Project ${e.name}: Markdown content updated.`)}else J(`[processMarkdownFiles] Project ${e.name}: Markdown content already up-to-date.`)}return J(`[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}=Tf({inclusions:e,exclusions:r,isProject:!0}),a=this.app.vault.getFiles().filter(u=>u.extension==="md"&&gu(u,o,i));J(`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}]]
2025-07-05 20:48:33 +08:00
path: ${u.path}
type: ${u.extension}
created: ${d?new Date(d.ctime).toISOString():"unknown"}
2025-08-12 16:40:13 +08:00
modified: ${d?new Date(d.mtime).toISOString():"unknown"}`,l=await this.app.vault.read(u),J(`Completed processing markdown file: ${u.path}`)}catch(d){fe(`Error processing file ${u.path}: ${d}`),l=`[Error: ${ci(d)}]`}return`${c}
2025-07-05 20:48:33 +08:00
2025-08-12 16:40:13 +08:00
${l}`}));return J("All markdown files processed for project context"),s.join(`
2025-07-05 20:48:33 +08:00
2025-08-12 16:40:13 +08:00
`)}async processWebUrls(e,r){J(`[processWebUrls] Starting for project: ${e.name}`);let n=e.contextSource?.webUrls?.trim()||"";if(!n)return Object.keys(r.webContexts).length>0&&(J(`[processWebUrls] Project ${e.name}: Clearing all Web contexts as none are configured.`),r.webContexts={}),r;let o=n.split(`
`).filter(c=>c.trim());J(`[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&&J(`[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){J(`[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&&J(`[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&&dg(`[processWebUrls] Project ${e.name}: Fetched empty content for Web URL: ${c.url}`)}),J(`[processWebUrls] Completed for project: ${e.name}. Total Web contexts: ${Object.keys(r.webContexts).length}`),r}async processYoutubeUrls(e,r){J(`[processYoutubeUrls] Starting for project: ${e.name}`);let n=e.contextSource?.youtubeUrls?.trim()||"";if(!n)return Object.keys(r.youtubeContexts).length>0&&(J(`[processYoutubeUrls] Project ${e.name}: Clearing all YouTube contexts as none are configured.`),r.youtubeContexts={}),r;let o=n.split(`
`).filter(c=>c.trim());J(`[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&&J(`[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){J(`[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&&J(`[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&&dg(`[processYoutubeUrls] Project ${e.name}: Fetched empty transcript for YouTube URL: ${c.url}`)}),J(`[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=_M.getInstance(),{urlContext:n}=await r.processUrls(e);return n||""}catch(r){return fe(`Failed to process web URLs: ${r}`),new HG.Notice(`Failed to process web URLs: ${ci(r)}`),""}}async processYoutubeUrlsContext(e){if(!e?.trim())return"";let n=e.split(`
`).filter(i=>i.trim()).map(async i=>{try{let a=await Wi.getInstance().youtube4llm(i);return a.response.transcript?`
2025-07-05 20:48:33 +08:00
YouTube transcript from ${i}:
2025-08-12 16:40:13 +08:00
${a.response.transcript}`:""}catch(a){return fe(`Failed to process YouTube URL ${i}: ${a}`),new HG.Notice(`Failed to process YouTube URL ${i}: ${ci(a)}`),""}});return(await Promise.all(n)).join("")}onunload(){this.projectContextCache.cleanup()}};Us();Ur();Tn();er();JUe();Ur();Gg();Tn();er();var Py=require("@codemirror/view"),cT=require("@codemirror/state");function pGt(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 WMn=Object.defineProperty,KMn=(t,e,r)=>e in t?WMn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,z4=(t,e,r)=>(KMn(t,typeof e!="symbol"?e+"":e,r),r),gme=cT.StateField.define({create(){return{suggestion:null}},update(t,e){let r=e.effects.find(n=>n.is(eqe));return e.state.doc&&r&&(r.value.doc==null||e.state.doc==r.value.doc)?{suggestion:r.value.suggestion}:{suggestion:null}}}),eqe=cT.StateEffect.define();function GMn(t,e){let r=t.state.selection.main.head,n=[],o=Py.Decoration.widget({widget:new ZUe(e),side:1});return n.push(o.range(r)),Py.Decoration.set(n)}var ZUe=class extends Py.WidgetType{constructor(e){super(),z4(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}},YUe=t=>{let e=0;return Py.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:eqe.of({suggestion:i,doc:n})})}}})},XUe=class{constructor(){z4(this,"decorations"),this.decorations=Py.Decoration.none}update(e){var r;let n=(r=e.state.field(gme))==null?void 0:r.suggestion;if(!n){this.decorations=Py.Decoration.none;return}this.decorations=GMn(e.view,n.display_suggestion)}},mGt=Py.ViewPlugin.fromClass(XUe,{decorations:t=>t.decorations}),QUe=class{constructor(e,r){z4(this,"suggestFn"),z4(this,"keymap"),z4(this,"completionId"),z4(this,"run",n=>{var o,i;let a=(o=n.state.field(gme))==null?void 0:o.suggestion;return a?(n.dispatch({...JMn(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:eqe.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=cT.Prec.highest(Py.keymap.of([{key:r,run:n=>this.run(n)}])),this.completionId=0}};function JMn(t,e,r,n){return{...t.changeByRange(o=>{if(o==t.selection.main)return{changes:{from:r,to:n,insert:e},range:cT.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:cT.EditorSelection.cursor(o.from-i+e.length)}}),userEvent:"input.complete"}}function hGt(t){return typeof t=="string"?{complete_suggestion:t,display_suggestion:t}:t}function ZMn(t){return async function*(e){let r=await t(e);if(typeof r=="string"||"complete_suggestion"in r){yield hGt(r);return}for await(let n of r)yield hGt(n)}}function yme(t){let{delay:e=500,accept_shortcut:r="Tab"}=t,n=ZMn(t.fetchFn),{debounced:o,force:i}=pGt(n,e);return{extension:r?[gme,YUe(o),mGt,new QUe(t.continue_suggesting?n:null,r).keymap]:[gme,YUe(o),mGt],force_fetch:i}}var iqe=require("obsidian");var tqe=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-08-12 16:40:13 +08:00
`)&&(a=a.substring(1)),a}},nqe=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}},bme=class{constructor(){this.processors=[];this.processors.push(new nqe),this.processors.push(new tqe),this.processors.push(new rqe)}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}};d6();var gGt=require("obsidian");function yGt(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 bGt(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 gGt.TFile&&(r.push(i),r.length>=e))break}return r}Hue();er();var oqe=require("obsidian"),YMn=.4,XMn=20,_Gt=.7,_me=.3;async function QMn(t,e){let r=ae().debug,n=await nE.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 eRn(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 tRn(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 rRn({db:t,filePath:e}){let r=ae().debug,n=await QMn(e,t),o=eRn(n);if(o.length===0)return r&&console.log("No embeddings found for note:",e),new Map;let i=await nE.getDocsByEmbedding(t,o,{limit:XMn,similarity:YMn});return tRn(i,e)}function nRn(t){let e=new Map,n=yGt(t).map(a=>a.path);for(let a of n)e.set(a,{links:!0,backlinks:!1});let i=bGt(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 oRn(t,e){let r=new Map,n=_Gt+_me;for(let[o,i]of t)r.set(o,i*_Gt/n);for(let[o,i]of e){let a=0;i.links&&i.backlinks?a=_me:(i.links||i.backlinks)&&(a=_me*.8),r.set(o,(r.get(o)??0)+a)}return r}async function wme({db:t,filePath:e}){let r=app.vault.getAbstractFileByPath(e);if(!(r instanceof oqe.TFile))return[];let n=await rRn({db:t,filePath:e}),o=nRn(r),i=oRn(n,o);return Array.from(i.entries()).sort((s,u)=>{let l=s[0],c=u[0],d=vme(n.get(l)??0),f=vme(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 oqe.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 vme(t){return t>.7?3:t>.55?2:1}OC();var vGt=require("obsidian"),iRn={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 aRn(t,e){let r=t.codePointAt(0);return r?e.some(([n,o])=>r>=n&&r<=o):!1}function wGt(t){let e=t.replace(/[\p{Emoji}\p{Symbol}\p{Punctuation}]/gu,"");if(!e)return!1;for(let r of e)if(Object.values(iRn).some(n=>aRn(r,n)))return!0;return!1}function xGt(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-08-12 16:40:13 +08:00
`;return{prefix:r,noteContext:n}}var IR=class IR{constructor(){this.currentNotePath=null;this.cachedNotes=null;this.cachedNoteTitles=[]}static getInstance(){return IR.instance||(IR.instance=new IR),IR.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 wa.getInstance().getDb(),o=(await wme({db:r,filePath:e.path})).slice(0,IR.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 vGt.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-08-12 16:40:13 +08:00
`),this.cachedNotes}clearCache(){this.currentNotePath=null,this.cachedNotes=null,this.cachedNoteTitles=[]}};IR.MAX_RELEVANT_NOTES=3;var xme=IR;var LF=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 WG=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-08-12 16:40:13 +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 wGt(s)?!0:e.endsWith(" ")}async*handleUnifiedCompletion(){if(!this.isActive)return;let e=app.workspace.getActiveViewOfType(iqe.MarkdownView);if(!e)return;await new Promise(c=>setTimeout(c,10));let r=e.editor,n=r.getCursor(),{prefix:o,noteContext:i}=xGt(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=ae();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(P=>P.word),g=o.slice(-1e3),y=a.slice(0,500),x,S,O;if(this.cacheEnabled&&(S=this.cache.generateWordKey(g,y,b),O=this.cache.get(S)),O)x=O;else{let P=this.client.wordcomplete(g,y,b);this.activeRequests.set(d,P),this.lastRequestTime=s,x=await P,this.cacheEnabled&&S&&this.cache.set(S,x),this.activeRequests.delete(d)}let E=x.response.selected_word;if(E&&E!==c){let P=this.generateCaseMatchedCompletion(E,c);P&&(yield{display_suggestion:P,complete_suggestion:P})}}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 xme.getInstance().getRelevantNotes(e.file));let m=e.file?.basename||"",h=m?`[[${m}]]:
2025-07-05 20:48:33 +08:00
2025-08-12 16:40:13 +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 x=b.response.completion,S=this.detectContext(o);x=this.postProcessor.process(c,a,x,S),yield{display_suggestion:x,complete_suggestion:x}}catch(f){this.activeRequests.delete(d),fe("[Copilot Autocomplete] Error fetching autocomplete suggestions:",f)}}}shouldUseWordCompletion(e,r){if(!r.enableWordCompletion||e.endsWith("[[")||/\[\[[^\]]*$/.test(e))return!1;let o=e.trim(),i=o[o.length-1];if(i&&/[a-zA-Z']/.test(i)){let a=this.getCurrentWordFromPrefix(e);if(a&&a.length>=2){let s=this.wordCompletionManager.getSuggestions(a);if(s.length===0)return!1;let u=s.some(c=>c.word===a),l=s.some(c=>c.word.length-a.length>=2);return!(u&&!l)}}return!1}getCurrentWordFromPrefix(e){let r=e.length;for(let o=e.length-1;o>=0;o--){let i=e[o];if(!/[a-zA-Z']/.test(i)){r=o+1;break}o===0&&(r=0)}let n=e.substring(r);return n.length>=2?n:null}generateCaseMatchedCompletion(e,r){if(e.length<=r.length)return"";let n=e.substring(r.length),o=r===r.toUpperCase(),i=r===r.toLowerCase(),a=r.length>0&&r[0]===r[0].toUpperCase()&&r.slice(1)===r.slice(1).toLowerCase();return o?n.toUpperCase():i||a?n.toLowerCase():n}detectContext(e){let r=e.split(`
`).pop()||"";if(/^\s*[-*+]\s/.test(r))return"UnorderedList";if(/^\s*\d+\.\s/.test(r))return"NumberedList";if(/^\s*[-*+]\s\[[ x]\]\s/.test(r))return"TaskList";if(e.includes("```")&&(e.split("```").length-1)%2===1)return"CodeBlock"}triggerCompletion(){this.isActive&&(this.clearActiveRequests(),this.forceFetch())}clearActiveRequests(){this.activeRequests.size>0&&this.activeRequests.clear()}getWordCompletionManager(){return this.wordCompletionManager}setCacheEnabled(e){this.cacheEnabled=e,e||this.cache.clear()}getCacheEnabled(){return this.cacheEnabled}};var Cme=class t{constructor(e){this.plugin=e;let r=ae();this.cmIntegration=Sme.getInstance({delay:hg.DELAY_MS,minTriggerLength:hg.MIN_TRIGGER_LENGTH,maxContextLength:hg.MAX_CONTEXT_LENGTH}),this.unsubscribeSettings=Ma((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()}};Ur();on();I1();function CGt(t){let e=t.split(`
`),r=[],n="",o="",i="";for(let a of e)a.startsWith("**user**:")||a.startsWith("**ai**:")?(n&&o&&r.push({id:Rp(),sender:n===Ei?Ei:mg,message:o.trim(),isVisible:!0,timestamp:i?Zve(i):null}),n=a.startsWith("**user**:")?Ei:mg,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({id:Rp(),sender:n===Ei?Ei:mg,message:o.trim(),isVisible:!0,timestamp:i?Zve(i):null}),r}async function OGt(t,e){await e.clearChatMemory();for(let r=0;r<t.length-1;r++){let n=t[r];if(n.sender===Ei){let o=t[r+1];o?.sender===mg&&await e.getMemory().saveContext({input:n.message},{output:o.message})}}}Us();td();var PGt=require("obsidian"),Ome=class extends PGt.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()}};H9();var MR=require("obsidian"),Pme=class extends MR.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 MR.Notice("Database not found");return}let s=await xd(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 MR.TFile?await this.app.vault.modify(c,u):await this.app.vault.create(l,u);let d=this.app.vault.getAbstractFileByPath(l);d instanceof MR.TFile&&(await this.app.workspace.getLeaf().openFile(d),this.close())}catch(i){console.error("Error in debug search:",i),new MR.Notice("Error executing search. Check console for details.")}})}onClose(){let{contentEl:e}=this;e.empty()}};on();var GG=require("obsidian"),Eme=class extends GG.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-08-12 16:40:13 +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=tb(o,this.app.vault).map(a=>a.path);if(i.length===0){new GG.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 GG.Notice("Error searching database. Check console for details.")}})}onClose(){let{contentEl:e}=this;e.empty()}};var JG=require("obsidian"),Tme=class extends JG.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 JG.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 JG.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-08-12 16:40:13 +08:00
`})}onClose(){let{contentEl:r}=this;r.empty()}};Qg();er();var oa=require("obsidian");I1();Ur();var oJt=require("obsidian");di();var Ame=F(ee());$n();var si=Ame.forwardRef(({className:t,type:e,...r},n)=>Ame.createElement("input",{type:e,className:ve("!tw-h-9 !tw-min-w-[50px] !tw-rounded-md !tw-border tw-border-solid tw-border-border !tw-bg-transparent !tw-px-3 !tw-py-1 !tw-text-sm !tw-transition-colors md:!tw-text-base","focus-visible:!tw-shadow-sm focus-visible:!tw-outline-none focus-visible:!tw-ring-1 focus-visible:!tw-ring-ring","placeholder:tw-text-sm","tw-flex tw-w-full tw-shadow-sm placeholder:tw-text-muted disabled:tw-cursor-not-allowed disabled:tw-opacity-50",t),ref:n,...r}));si.displayName="Input";var Ime=F(ee());var RGt=F(ee(),1);var TGt=F(ee(),1),AGt=F(Cs(),1);var Rd=F(ee(),1);var EGt=F(ee(),1);function uRn(t,e){typeof t=="function"?t(e):t!=null&&(t.current=e)}function kF(...t){return e=>t.forEach(r=>uRn(r,e))}function zi(...t){return EGt.useCallback(kF(...t),t)}var B4=F(bt(),1),sqe=Rd.forwardRef((t,e)=>{let{children:r,...n}=t,o=Rd.Children.toArray(r),i=o.find(cRn);if(i){let a=i.props.children,s=o.map(u=>u===i?Rd.Children.count(a)>1?Rd.Children.only(null):Rd.isValidElement(a)?a.props.children:null:u);return(0,B4.jsx)(aqe,{...n,ref:e,children:Rd.isValidElement(a)?Rd.cloneElement(a,void 0,s):null})}return(0,B4.jsx)(aqe,{...n,ref:e,children:r})});sqe.displayName="Slot";var aqe=Rd.forwardRef((t,e)=>{let{children:r,...n}=t;if(Rd.isValidElement(r)){let o=fRn(r);return Rd.cloneElement(r,{...dRn(n,r.props),ref:e?kF(e,o):o})}return Rd.Children.count(r)>1?Rd.Children.only(null):null});aqe.displayName="SlotClone";var lRn=({children:t})=>(0,B4.jsx)(B4.Fragment,{children:t});function cRn(t){return Rd.isValidElement(t)&&t.type===lRn}function dRn(t,e){let r={...e};for(let n in e){let o=t[n],i=e[n];/^on[A-Z]/.test(n)?o&&i?r[n]=(...s)=>{i(...s),o(...s)}:o&&(r[n]=o):n==="style"?r[n]={...o,...i}:n==="className"&&(r[n]=[o,i].filter(Boolean).join(" "))}return{...t,...r}}function fRn(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,r=e&&"isReactWarning"in e&&e.isReactWarning;return r?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,r=e&&"isReactWarning"in e&&e.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}var IGt=F(bt(),1),pRn=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Po=pRn.reduce((t,e)=>{let r=TGt.forwardRef((n,o)=>{let{asChild:i,...a}=n,s=i?sqe:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,IGt.jsx)(s,{...a,ref:o})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});function MGt(t,e){t&&AGt.flushSync(()=>t.dispatchEvent(e))}var NGt=F(bt(),1),mRn="Label",jGt=RGt.forwardRef((t,e)=>(0,NGt.jsx)(Po.label,{...t,ref:e,onMouseDown:r=>{r.target.closest("button, input, select, textarea")||(t.onMouseDown?.(r),!r.defaultPrevented&&r.detail>1&&r.preventDefault())}}));jGt.displayName=mRn;var uqe=jGt;bQ();$n();var gRn=pz("tw-text-sm tw-font-medium tw-leading-none peer-disabled:tw-cursor-not-allowed peer-disabled:tw-opacity-70"),Sp=Ime.forwardRef(({className:t,...e},r)=>Ime.createElement(uqe,{ref:r,className:ve(gRn(),t),...e}));Sp.displayName=uqe.displayName;var V4=F(ee());var $h=F(ee(),1);var LGt=F(ee(),1);function DGt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function lqe(...t){return e=>{let r=!1,n=t.map(o=>{let i=DGt(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():DGt(t[o],null)}}}}function FGt(...t){return LGt.useCallback(lqe(...t),t)}var Ey=F(ee(),1),cqe=F(bt(),1);function kGt(t,e){let r=Ey.createContext(e),n=i=>{let{children:a,...s}=i,u=Ey.useMemo(()=>s,Object.values(s));return(0,cqe.jsx)(r.Provider,{value:u,children:a})};n.displayName=t+"Provider";function o(i){let a=Ey.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 na(t,e=[]){let r=[];function n(i,a){let s=Ey.createContext(a),u=r.length;r=[...r,a];let l=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.
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-08-12 16:40:13 +08:00
Return only the formatted thread.`,showInContextMenu:!1,showInSlashMenu:!1,order:1120,modelKey:"",lastUsedMs:0}];var W4=require("obsidian");er();a6();a6();var $F=S$(),zF=cg([]),vqe=new Set;function BF(t){vqe.add(t)}function UF(t){vqe.delete(t)}function YG(t){return vqe.has(t)}function XG(t){let e=$F.get(zF);$F.set(zF,e.filter(r=>r.title!==t))}function qF(t,e){let r=$F.get(zF),n;(e?r.findIndex(i=>i.title===e):-1)!==-1?n=r.map(i=>i.title===e?t:i):n=[...r,t],$F.set(zF,n)}function jme(t){$F.set(zF,t)}function eJt(){return o6(zF,{store:$F})}function Mm(){return $F.get(zF)}d6();on();Ur();function Dme(t,e,r){let n=t.trim();return r&&n===r?null:n?/[#<>:"/\\|?*[\]^\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:"Command name cannot be empty"}function K4(t){return encodeURIComponent(t.toLowerCase())}function DR(){return(0,W4.normalizePath)(ae().customPromptsFolder)}function G4(t){return`${DR()}/${t}.md`}function J4(t){if(!(t instanceof W4.TFile)||t.extension!=="md")return!1;let e=DR();return!(!t.path.startsWith(e+"/")||t.path.slice(e.length+1).includes("/"))}function jRn(t){if(t.startsWith("---")){let e=t.indexOf("---",3);if(e!==-1)return t.slice(e+3).trimStart()}return t}function tJt(t){return app.metadataCache.getFileCache(t)?.frontmatter?.[rO]!=null}async function QG(t){let e=await app.vault.read(t),r=jRn(e),n=app.metadataCache.getFileCache(t),o=n?.frontmatter?.[fT]??tO.showInContextMenu,i=n?.frontmatter?.[pT]??tO.showInSlashMenu,a=n?.frontmatter?.[hT]??tO.lastUsedMs,s=n?.frontmatter?.[rO]??tO.order,u=n?.frontmatter?.[mT]??tO.modelKey;return{title:t.basename,modelKey:u,content:r,showInContextMenu:o,showInSlashMenu:i,order:s,lastUsedMs:a}}async function Lme(){let t=app.vault.getFiles().filter(r=>J4(r)),e=await Promise.all(t.map(QG));return jme(e),e}function eJ(t){return[...t].sort((e,r)=>e.order===r.order?e.title.localeCompare(r.title):e.order-r.order)}function DRn(t){return[...t].sort((e,r)=>e.lastUsedMs===r.lastUsedMs?e.title.localeCompare(r.title):r.lastUsedMs-e.lastUsedMs)}function LRn(t){return[...t].sort((e,r)=>e.title.localeCompare(r.title))}function rJt(t){switch(ae().promptSortStrategy){case"timestamp":return DRn(t);case"alphabetical":return LRn(t);case"manual":return eJ(t);default:return t}}async function wqe(t,e,r=!1){let o=(await tJ(t,e,app.vault,app.workspace.getActiveFile())).processedPrompt;if(o.includes("{selectedText}")||r)return o;let i=o.indexOf(_qe);return i===-1&&e.trim()?o+`
2025-07-05 20:48:33 +08:00
2025-08-12 16:40:13 +08:00
<selectedText>`+e+"</selectedText>":o.slice(0,i)+e+o.slice(i+_qe.length)}var FRn=/\{(?!copilot-selection\})([^}]+)\}/g;async function kRn(t,e,r){let n=new Map,o=new Set,i;for(;(i=FRn.exec(t))!==null;){let a=i[1].trim(),s={content:"",files:[]};if(a.toLowerCase()==="activenote")if(r){let u=await E$(r,e);u&&(s.content=`## ${DY(r)}
2025-07-05 20:48:33 +08:00
2025-08-12 16:40:13 +08:00
${u}`,s.files.push(r))}else new W4.Notice("No active note found.");else if(a.startsWith("#")){let u=a.slice(1).split(",").map(d=>d.trim()),l=await OGe(e,u),c=[];for(let d of l){let f=await E$(d,e);f&&(c.push(`## ${DY(d)}
2025-07-05 20:48:33 +08:00
${f}`),s.files.push(d))}s.content=c.join(`
2025-08-12 16:40:13 +08:00
`)}else{let u=TGe(a),l=await Jve(e,u),c=[];for(let d of l){let f=await E$(d,e);f&&(c.push(`## ${DY(d)}
2025-07-05 20:48:33 +08:00
${f}`),s.files.push(d))}s.content=c.join(`
2025-08-12 16:40:13 +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 tJ(t,e,r,n){let o=ae(),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-08-12 16:40:13 +08:00
`,includedFiles:Array.from(i)};let{variablesMap:a,includedFiles:s}=await kRn(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-08-12 16:40:13 +08:00
${e}`:n?(c=await E$(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-08-12 16:40:13 +08:00
${p}`);let d=tb(u,r);for(let f of d)if(!i.has(f)){let p=await E$(f,r);if(p){let m=`<${f6}>
2025-07-05 20:48:33 +08:00
Title: [[${f.basename}]]
Path: ${f.path}
${p}
2025-08-12 16:40:13 +08:00
</${f6}>`;l&&(l+=`
2025-07-05 20:48:33 +08:00
`),l+=`${m}`,i.add(f)}}return{processedPrompt:l?`${u}
${l}`:`${u}
2025-08-12 16:40:13 +08:00
`,includedFiles:Array.from(i)}}function nJt(t,e){let n=`${t} (copy)`,o=1;for(;e.some(i=>i.title.toLowerCase()===n.toLowerCase());)o++,n=`${t} (copy ${o})`;return n}function Fme(){let e=Mm().reduce((r,n)=>r>n.order?r:n.order,0);return e===Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:e+10}async function xqe(t,e){try{BF(t.path),await app.fileManager.processFrontMatter(t,r=>{r[fT]==null&&(r[fT]=e.showInContextMenu),r[pT]==null&&(r[pT]=e.showInSlashMenu),r[rO]==null&&(r[rO]=e.order),r[mT]==null&&(r[mT]=e.modelKey),r[hT]==null&&(r[hT]=e.lastUsedMs)})}finally{UF(t.path)}}function $Rn({commands:t,command:e,onConfirm:r,onCancel:n}){let i=Hn().activeModels.filter(f=>f.enabled).map(f=>({label:Nme(f),value:Yr(f)})),[a,s]=(0,ui.useState)(e),[u,l]=(0,ui.useState)({}),c=(f,p)=>{s(m=>({...m,[f]:p})),l(m=>({...m,[f]:void 0}))},d=()=>{let f={},p=Dme(a.title,t,e.title);if(p&&(f.title=p),a.content.trim()||(f.content="Prompt is required"),Object.keys(f).length>0){l(f);return}r(a)};return ui.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4 tw-p-4"},ui.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},ui.default.createElement(Sp,{htmlFor:"title"},"Name"),ui.default.createElement(si,{id:"title",value:a.title,onChange:f=>c("title",f.target.value),placeholder:"Enter command name"}),u.title&&ui.default.createElement("div",{className:"tw-text-sm tw-text-error"},u.title)),ui.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},ui.default.createElement(Sp,{htmlFor:"content"},"Prompt"),ui.default.createElement(XGt,null),ui.default.createElement(dT,{id:"content",value:a.content,onChange:f=>c("content",f.target.value),placeholder:"Enter command prompt",className:"tw-min-h-[200px]"}),u.content&&ui.default.createElement("div",{className:"tw-text-sm tw-text-error"},u.content)),ui.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},ui.default.createElement(Sp,{htmlFor:"modelKey"},"Model (Optional)"),ui.default.createElement("div",{className:"tw-group tw-relative tw-w-full"},ui.default.createElement("select",{value:a.modelKey,onChange:f=>{let p=f.target.value;if(!p){c("modelKey","");return}if(!i.find(h=>h.value===p)){fe(`Model ${p} not found`),c("modelKey","");return}c("modelKey",f.target.value)},className:ve("tw-w-full tw-appearance-none","tw-flex tw-h-9 tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-dropdown tw-px-3 tw-py-1 tw-pr-8","tw-text-sm !tw-shadow tw-transition-colors","focus:tw-outline-none focus:tw-ring-1 focus:tw-ring-ring","disabled:tw-cursor-not-allowed disabled:tw-opacity-50","hover:tw-bg-interactive-hover hover:tw-text-normal")},ui.default.createElement("option",{value:""},"Inherit from chat model"),i.map(f=>ui.default.createElement("option",{key:f.value,value:f.value.toString()},f.label))),ui.default.createElement("div",{className:ve("tw-pointer-events-none tw-absolute tw-inset-y-0 tw-right-0 tw-flex tw-items-center tw-pr-2","tw-transition-colors group-hover:[&>svg]:tw-text-normal")},ui.default.createElement(Xi,{className:"tw-size-4"})))),ui.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},ui.default.createElement(Ld,{id:"showInContextMenu",checked:a.showInContextMenu,onCheckedChange:f=>c("showInContextMenu",f)}),ui.default.createElement(Sp,{htmlFor:"showInContextMenu"},"Show in context menu")),ui.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},ui.default.createElement(Ld,{id:"showInSlashMenu",checked:a.showInSlashMenu,onCheckedChange:f=>c("showInSlashMenu",f)}),ui.default.createElement(Sp,{htmlFor:"showInSlashMenu"},"Show in slash menu")),ui.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},ui.default.createElement(be,{variant:"secondary",onClick:n},"Cancel"),ui.default.createElement(be,{variant:"default",onClick:d},"Save")))}var HF=class extends oJt.Modal{constructor(r,n,o,i){super(r);this.commands=n;this.command=o;this.onUpdate=i;this.setTitle("Edit Command")}onOpen(){let{contentEl:r}=this;this.root=(0,iJt.createRoot)(r);let n=o=>{this.onUpdate(o),this.close()};this
`),f=`${`Copilot-Indexed-Files-${new Date().toLocaleDateString().replace(/\//g,"-")}.md`}`,p=t.app.vault.getAbstractFileByPath(f);p instanceof oa.TFile?await t.app.vault.modify(p,c):await t.app.vault.create(f,c);let m=t.app.vault.getAbstractFileByPath(f);m instanceof oa.TFile&&(await t.app.workspace.getLeaf().openFile(m),new oa.Notice(`Listed ${n.length} indexed files`))}catch(n){console.error("Error listing indexed files:",n),new oa.Notice("Failed to list indexed files.")}}),r.debug&&(kd(t,qr.INSPECT_COPILOT_INDEX_BY_NOTE_PATHS,()=>{new Eme(t.app,t).open()}),kd(t,qr.SEARCH_ORAMA_DB,()=>{new Pme(t.app,t).open()}),kd(t,qr.REMOVE_FILES_FROM_COPILOT_INDEX,async()=>{new Tme(t.app,async n=>{let o=await t.vectorStoreManager.getDbOps();try{for(let i of n)await o.removeDocs(i);await o.saveDB(),new oa.Notice(`Successfully removed ${n.length} files from the index.`)}catch(i){console.error("Error removing files from index:",i),new oa.Notice("An error occurred while removing files from the index.")}}).open()})),kd(t,qr.CLEAR_COPILOT_CACHE,async()=>{try{await t.fileParserManager.clearPDFCache(),await zb.getInstance().clearAllCache(),await Nq.getInstance().clear();let{AutocompleteCache:o}=await Promise.resolve().then(()=>(JUe(),fGt));o.getInstance().clear(),new oa.Notice("All Copilot caches cleared successfully")}catch(n){console.error("Error clearing Copilot caches:",n),new oa.Notice("Failed to clear Copilot caches")}}),kd(t,qr.TOGGLE_AUTOCOMPLETE,()=>{let o=!ae().enableAutocomplete;ht("enableAutocomplete",o),new oa.Notice(`Copilot autocomplete ${o?"enabled":"disabled"}`)}),aJt(t,qr.ADD_SELECTION_TO_CHAT_CONTEXT,async n=>{let o=bg();if(o!=="copilot_plus"&&o!=="project"){new oa.Notice("Selected text context is only available in Copilot Plus and Project modes");return}let i=n.getSelection();if(!i){new oa.Notice("No text selected");return}let a=t.app.workspace.getActiveFile();if(!a){new oa.Notice("No active file");return}let s=n.listSelections()[0];if(!s){new oa.Notice("Could not determine selection range");return}let u=s.anchor.line+1,l=s.head.line+1,c={id:Rp(),content:i,noteTitle:a.basename,notePath:a.path,startLine:Math.min(u,l),endLine:Math.max(u,l)};gJe(c),t.activateView()}),kd(t,qr.ADD_CUSTOM_COMMAND,async()=>{let n=Mm(),o={...tO};new HF(t.app,n,o,async a=>{await Fd.getInstance().createCommand(a)}).open()})}Us();td();Us();td();di();var sJt=require("obsidian"),VF=F(ee()),uJt=F(id());function zRn({content:t,onConfirm:e,onCancel:r,confirmButtonText:n,cancelButtonText:o}){return VF.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-5"},VF.default.createElement("div",{className:"tw-whitespace-pre-wrap"},t),VF.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},o&&VF.default.createElement(be,{variant:"secondary",onClick:r},o),n&&VF.default.createElement(be,{variant:"default",onClick:e},n)))}var $d=class extends sJt.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,uJt.createRoot)(r);let n=()=>{this.onConfirm(),this.close()},o=()=>{this.close()};this.root.render(VF.default.createElement(zRn,{content:this.content,onConfirm:n,onCancel:o,confirmButtonText:this.confirmButtonText,cancelButtonText:this.cancelButtonText}))}onClose(){this.root.unmount()}};di();var Gi=F(ee());var ac=F(ee(),1);function nJ(t,e,{checkForDefaultPrevented:r=!0}={}){return function(o){if(t?.(o),r===!1||!o.defaultPrevented)return e?.(o)}}var BRn=F(ee(),1);function lJt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function kme(...t){return e=>{let r=!1,n=t.map(o=>{let i=lJt(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():lJt(t[o],null)}}}}var cJt=F(ee(),1),WRn=F(Cs(),1);var zd=F(ee(),1);var Z4=F(bt(),1),Oqe=zd.forwardRef((t,e)=>{let{children:r,...n}=t,o=zd.Children.toArray(r),i=o.find(qRn);if(i){let a=i.props.children,s=o.map(u=>u===i?zd.Children.count(a)>1?zd.Children.only(null):zd.isVa
.`.concat(e2e,` {
2025-07-05 20:48:33 +08:00
overflow: hidden `).concat(n,`;
padding-right: `).concat(s,"px ").concat(n,`;
}
2025-08-12 16:40:13 +08:00
body[`).concat(i3,`] {
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(""),`
}
2025-08-12 16:40:13 +08:00
.`).concat(f_,` {
2025-07-05 20:48:33 +08:00
right: `).concat(s,"px ").concat(n,`;
}
2025-08-12 16:40:13 +08:00
.`).concat(p_,` {
2025-07-05 20:48:33 +08:00
margin-right: `).concat(s,"px ").concat(n,`;
}
2025-08-12 16:40:13 +08:00
.`).concat(f_," .").concat(f_,` {
2025-07-05 20:48:33 +08:00
right: 0 `).concat(n,`;
}
2025-08-12 16:40:13 +08:00
.`).concat(p_," .").concat(p_,` {
2025-07-05 20:48:33 +08:00
margin-right: 0 `).concat(n,`;
}
2025-08-12 16:40:13 +08:00
body[`).concat(i3,`] {
`).concat(t2e,": ").concat(s,`px;
2025-07-05 20:48:33 +08:00
}
2025-08-12 16:40:13 +08:00
`)},Q7t=function(){var t=parseInt(document.body.getAttribute(i3)||"0",10);return isFinite(t)?t:0},SNn=function(){a3.useEffect(function(){return document.body.setAttribute(i3,(Q7t()+1).toString()),function(){var t=Q7t()-1;t<=0?document.body.removeAttribute(i3):document.body.setAttribute(i3,t.toString())}},[])},rk=function(t){var e=t.noRelative,r=t.noImportant,n=t.gapMode,o=n===void 0?"margin":n;SNn();var i=a3.useMemo(function(){return a2e(o)},[o]);return a3.createElement(wNn,{styles:xNn(i,!e,o,r?"":"!important")})};var s2e=!1;if(typeof window<"u")try{fJ=Object.defineProperty({},"passive",{get:function(){return s2e=!0,!0}}),window.addEventListener("test",fJ,fJ),window.removeEventListener("test",fJ,fJ)}catch{s2e=!1}var fJ,nk=s2e?{passive:!1}:!1;var CNn=function(t){return t.tagName==="TEXTAREA"},eZt=function(t,e){if(!(t instanceof Element))return!1;var r=window.getComputedStyle(t);return r[e]!=="hidden"&&!(r.overflowY===r.overflowX&&!CNn(t)&&r[e]==="visible")},ONn=function(t){return eZt(t,"overflowY")},PNn=function(t){return eZt(t,"overflowX")},u2e=function(t,e){var r=e.ownerDocument,n=e;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var o=tZt(t,n);if(o){var i=rZt(t,n),a=i[1],s=i[2];if(a>s)return!0}n=n.parentNode}while(n&&n!==r.body);return!1},ENn=function(t){var e=t.scrollTop,r=t.scrollHeight,n=t.clientHeight;return[e,r,n]},TNn=function(t){var e=t.scrollLeft,r=t.scrollWidth,n=t.clientWidth;return[e,r,n]},tZt=function(t,e){return t==="v"?ONn(e):PNn(e)},rZt=function(t,e){return t==="v"?ENn(e):TNn(e)},ANn=function(t,e){return t==="h"&&e==="rtl"?-1:1},nZt=function(t,e,r,n,o){var i=ANn(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=rZt(t,s),m=p[0],h=p[1],b=p[2],g=h-b-i*m;(m||g)&&tZt(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 lhe=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},oZt=function(t){return[t.deltaX,t.deltaY]},iZt=function(t){return t&&"current"in t?t.current:t},INn=function(t,e){return t[0]===e[0]&&t[1]===e[1]},MNn=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-08-12 16:40:13 +08:00
`)},RNn=0,s3=[];function aZt(t){var e=Oa.useRef([]),r=Oa.useRef([0,0]),n=Oa.useRef(),o=Oa.useState(RNn++)[0],i=Oa.useState(_T)[0],a=Oa.useRef(t);Oa.useEffect(function(){a.current=t},[t]),Oa.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var h=o3([t.lockRef.current],(t.shards||[]).map(iZt),!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=Oa.useCallback(function(h,b){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!a.current.allowPinchZoom;var g=lhe(h),y=r.current,x="deltaX"in h?h.deltaX:y[0]-g[0],S="deltaY"in h?h.deltaY:y[1]-g[1],O,E=h.target,P=Math.abs(x)>Math.abs(S)?"h":"v";if("touches"in h&&P==="h"&&E.type==="range")return!1;var A=u2e(P,E);if(!A)return!0;if(A?O=P:(O=P==="v"?"h":"v",A=u2e(P,E)),!A)return!1;if(!n.current&&"changedTouches"in h&&(x||S)&&(n.current=O),!O)return!0;var I=n.current||O;return nZt(I,b,h,I==="h"?x:S,!0)},[]),u=Oa.useCallback(function(h){var b=h;if(!(!s3.length||s3[s3.length-1]!==i)){var g="deltaY"in b?oZt(b):lhe(b),y=e.current.filter(function(O){return O.name===b.type&&(O.target===b.target||b.target===O.shadowParent)&&INn(O.delta,g)})[0];if(y&&y.should){b.cancelable&&b.preventDefault();return}if(!y){var x=(a.current.shards||[]).map(iZt).filter(Boolean).filter(function(O){return O.contains(b.target)}),S=x.length>0?s(b,x[0]):!a.current.noIsolation;S&&b.cancelable&&b.preventDefault()}}},[]),l=Oa.useCallback(function(h,b,g,y){var x={name:h,delta:b,target:g,should:y,shadowParent:NNn(g)};e.current.push(x),setTimeout(function(){e.current=e.current.filter(function(S){return S!==x})},1)},[]),c=Oa.useCallback(function(h){r.current=lhe(h),n.current=void 0},[]),d=Oa.useCallback(function(h){l(h.type,oZt(h),h.target,s(h,t.lockRef.current))},[]),f=Oa.useCallback(function(h){l(h.type,lhe(h),h.target,s(h,t.lockRef.current))},[]);Oa.useEffect(function(){return s3.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,nk),document.addEventListener("touchmove",u,nk),document.addEventListener("touchstart",c,nk),function(){s3=s3.filter(function(h){return h!==i}),document.removeEventListener("wheel",u,nk),document.removeEventListener("touchmove",u,nk),document.removeEventListener("touchstart",c,nk)}},[]);var p=t.removeScrollBar,m=t.inert;return Oa.createElement(Oa.Fragment,null,m?Oa.createElement(i,{styles:MNn(o)}):null,p?Oa.createElement(rk,{gapMode:t.gapMode}):null)}function NNn(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var sZt=tk(uhe,aZt);var uZt=che.forwardRef(function(t,e){return che.createElement(dJ,Oi({},t,{ref:e,sideCar:sZt}))});uZt.classNames=dJ.classNames;var l2e=uZt;var Br=F(bt(),1),c2e=["Enter"," "],jNn=["ArrowDown","PageUp","Home"],cZt=["ArrowUp","PageDown","End"],DNn=[...jNn,...cZt],LNn={ltr:[...c2e,"ArrowRight"],rtl:[...c2e,"ArrowLeft"]},FNn={ltr:["ArrowLeft"],rtl:["ArrowRight"]},gJ="Menu",[mJ,kNn,$Nn]=hJt(gJ),[ok,d2e]=na(gJ,[$Nn,qqe,Xqe]),yJ=qqe(),dZt=Xqe(),[fZt,t1]=ok(gJ),[zNn,bJ]=ok(gJ),pZt=t=>{let{__scopeMenu:e,open:r=!1,children:n,dir:o,onOpenChange:i,modal:a=!0}=t,s=yJ(e),[u,l]=Zt.useState(null),c=Zt.useRef(!1),d=Qr(i),f=kR(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,Br.jsx)(Vqe,{...s,children:(0,Br.jsx)(fZt,{scope:e,open:r,onOpenChange:d,content:u,onContentChange:l,children:(0,Br.jsx)(zNn,{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-08-12 16:40:13 +08:00
`)}}return e}async processContextNotes(e,r,n,o,i,a,s){let u="",l=async(d,f=f6)=>{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-08-12 16:40:13 +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=TN();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-08-12 16:40:13 +08:00
</selected_text>`}return r}};er();on();An();var i1=require("obsidian"),ut=F(ee());var Rn=F(ee()),Bi=F(SXt());function o1(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 NDn=new Map([["1km","application/vnd.1000minds.decision-model+xml"],["3dml","text/vnd.in3d.3dml"],["3ds","image/x-3ds"],["3g2","video/3gpp2"],["3gp","video/3gp"],["3gpp","video/3gpp"],["3mf","model/3mf"],["7z","application/x-7z-compressed"],["7zip","application/x-7z-compressed"],["123","application/vnd.lotus-1-2-3"],["aab","application/x-authorware-bin"],["aac","audio/x-acc"],["aam","application/x-authorware-map"],["aas","application/x-authorware-seg"],["abw","application/x-abiword"],["ac","application/vnd.nokia.n-gage.ac+xml"],["ac3","audio/ac3"],["acc","application/vnd.americandynamics.acc"],["ace","application/x-ace-compressed"],["acu","application/vnd.acucobol"],["acutc","application/vnd.acucorp"],["adp","audio/adpcm"],["aep","application/vnd.audiograph"],["afm","application/x-font-type1"],["afp","application/vnd.ibm.modcap"],["ahead","application/vnd.ahead.space"],["ai","application/pdf"],["aif","audio/x-aiff"],["aifc","audio/x-aiff"],["aiff","audio/x-aiff"],["air","application/vnd.adobe.air-application-installer-package+zip"],["ait","application/vnd.dvb.ait"],["ami","application/vnd.amiga.ami"],["amr","audio/amr"],["apk","application/vnd.android.package-archive"],["apng","image/apng"],["appcache","text/cache-manifest"],["application","application/x-ms-application"],["apr","application/vnd.lotus-approach"],["arc","application/x-freearc"],["arj","application/x-arj"],["asc","application/pgp-signature"],["asf","video/x-ms-asf"],["asm","text/x-asm"],["aso","application/vnd.accpac.simply.aso"],["asx","video/x-ms-asf"],["atc","application/vnd.acucorp"],["atom","application/atom+xml"],["atomcat","application/atomcat+xml"],["atomdeleted","application/atomdeleted+xml"],["atomsvc","application/atomsvc+xml"],["atx","application/vnd.antix.game-component"],["au","audio/x-au"],["avi","video/x-msvideo"],["avif","image/avif"],["aw","application/applixware"],["azf","application/vnd.airzip.filesecure.azf"],["azs","application/vnd.airzip.filesecure.azs"],["azv","image/vnd.airzip.accelerator.azv"],["azw","application/vnd.amazon.ebook"],["b16","image/vnd.pco.b16"],["bat","application/x-msdownload"],["bcpio","application/x-bcpio"],["bdf","application/x-font-bdf"],["bdm","application/vnd.syncml.dm+wbxml"],["bdoc","application/x-bdoc"],["bed","application/vnd.realvnc.bed"],["bh2","application/vnd.fujitsu.oasysprs"],["bin","application/octet-stream"],["blb","application/x-blorb"],["blorb","application/x-blorb"],["bmi","application/vnd.bmi"],["bmml","application/vnd.balsamiq.bmml+xml"],["bmp","image/bmp"],["book","application/vnd.framemaker"],["box","application/vnd.previewsystems.box"],["boz","application/x-bzip2"],["bpk","application/octet-stream"],["bpmn","application/octet-stream"],["bsp","model/vnd.valve.source.compiled-map"],["btif","image/prs.btif"],["buffer","application/octet-stream"],["bz","application/x-bzip"],["bz2","application/x-bzip2"],["c","text/x-c"],["c4d","application/vnd.clonk.c4group"],["c4f","application/vnd.clonk.c4group"],["c4g","application/vnd.clonk.c4group"],["c4p","application/vnd.clonk.c4group"],["c4u","application/vnd.clonk.c4group"],["c11amc","application/vnd.cluetrust.cartomobile-config"],["c11amz","application/vnd.cluetrust.cartomobile-config-pkg"],["cab","application/vnd.ms-cab-compressed"],["caf","audio/x-caf"],["cap","application/vnd.tcpdump.pcap"],["car","application/vnd.curl.car"],["cat","application/vnd.ms-pki.seccat"],["cb7","application/x-cbr"],["cba","application/x-cbr"],["cbr","application/x-cbr"],["cbt","application/x-cbr"],["cbz","application/x-cbr"],["cc","text/x-c"],["cco","application/x-cocoa"],["cct","application/x-director"],["ccxml","application/ccxml+xml"],["cdbcmsg","application/
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function VDn(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function WDn(t){if(Array.isArray(t))return K2e(t)}function MXt(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 RXt(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?MXt(Object(r),!0).forEach(function(n){DXt(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):MXt(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}function DXt(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function PJ(t,e){return JDn(t)||GDn(t,e)||LXt(t,e)||KDn()}function KDn(){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 LXt(t,e){if(t){if(typeof t=="string")return K2e(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 K2e(t,e)}}function K2e(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 GDn(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 JDn(t){if(Array.isArray(t))return t}var ZDn=typeof Phe.default=="function"?Phe.default:Phe.default.default,YDn="file-invalid-type",XDn="file-too-large",QDn="file-too-small",eLn="too-many-files";var tLn=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:YDn,message:"File type must be ".concat(n)}},NXt=function(e){return{code:XDn,message:"File is larger than ".concat(e," ").concat(e===1?"byte":"bytes")}},jXt=function(e){return{code:QDn,message:"File is smaller than ".concat(e," ").concat(e===1?"byte":"bytes")}},FXt={code:eLn,message:"Too many files"};function G2e(t,e){var r=t.type==="application/x-moz-file"||ZDn(t,e);return[r,r?null:tLn(e)]}function J2e(t,e,r){if(lk(t.size))if(lk(e)&&lk(r)){if(t.size>r)return[!1,NXt(r)];if(t.size<e)return[!1,jXt(e)]}else{if(lk(e)&&t.size<e)return[!1,jXt(e)];if(lk(r)&&t.size>r)return[!1,NXt(r)]}return[!0,null]}function lk(t){return t!=null}function kXt(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=G2e(u,r),c=PJ(l,1),d=c[0],f=J2e(u,n,o),p=PJ(f,1),m=p[0],h=s?s(u):null;return d&&m&&!h})}function EJ(t){return typeof t.isPropagationStopped=="function"?t.isPropagationStopped():typeof t.cancelBubble<"u"?t.cancelBubble:!1}function TJ(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 Z2e(t){t.preventDefault()}function rLn(t){return t.indexOf("MSIE")!==-1||t.indexOf("Trident/")!==-1}function nLn(t){return t.indexOf("Edge/")!==-1}function $Xt(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.navigator.userAgent;return rLn(t)||nLn(t)}function y_(){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!EJ(n)&&s&&s.apply(void 0,[n].concat(i)),EJ(n)})}}function zXt(){return"showOpenFilePicker"in window}function BXt(t){if(lk(t)){var e=Object.entries(t).filter(function(r){var n=PJ(r,2),o=n[0],i=n[1],a=!0;return VXt(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(WXt))&&(console.warn('Skipped "'.concat(o,'" because an invalid file extension was provided.')),a=!1),a}).reduce(function(r,n){var o=PJ(n,2),i=o[0],a=o[1];return RXt(RXt({},r),{},DXt({},i,a))},{});return[{description:"Files",accept:e}]}return t}function UXt(t){if(lk(t))return Object.entries(t).reduce(function(e,r){var n=PJ(r,2),o=n[0],i=n[1];return[].concat(IXt(e),[o],IXt(i))},[]).filter(function(e){return VXt(e)||WXt(e)}).join(",")}function qXt(t){return t instanceof DOMException&&(t.name==="AbortError"||t.code===t.ABORT_ERR)}function HXt(t){return t instanceof DOMException&&(t.name==="SecurityError"||t.code===t.SECURITY_ERR)}function VXt(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 cLn(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function dLn(t){if(Array.isArray(t))return X2e(t)}function Y2e(t,e){return mLn(t)||pLn(t,e)||JXt(t,e)||fLn()}function fLn(){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 JXt(t,e){if(t){if(typeof t=="string")return X2e(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 X2e(t,e)}}function X2e(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 pLn(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 mLn(t){if(Array.isArray(t))return t}function KXt(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 ps(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?KXt(Object(r),!0).forEach(function(n){Q2e(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):KXt(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}function Q2e(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Ehe(t,e){if(t==null)return{};var r=hLn(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 hLn(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 t4e=(0,Rn.forwardRef)(function(t,e){var r=t.children,n=Ehe(t,oLn),o=r4e(n),i=o.open,a=Ehe(o,iLn);return(0,Rn.useImperativeHandle)(e,function(){return{open:i}},[i]),Rn.default.createElement(Rn.Fragment,null,r(ps(ps({},a),{},{open:i})))});t4e.displayName="Dropzone";var ZXt={disabled:!1,getFilesFromEvent:V2e,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};t4e.defaultProps=ZXt;t4e.propTypes={children:Bi.default.func,accept:Bi.default.objectOf(Bi.default.arrayOf(Bi.default.string)),multiple:Bi.default.bool,preventDropOnDocument:Bi.default.bool,noClick:Bi.default.bool,noKeyboard:Bi.default.bool,noDrag:Bi.default.bool,noDragEventsBubbling:Bi.default.bool,minSize:Bi.default.number,maxSize:Bi.default.number,maxFiles:Bi.default.number,disabled:Bi.default.bool,getFilesFromEvent:Bi.default.func,onFileDialogCancel:Bi.default.func,onFileDialogOpen:Bi.default.func,useFsAccessApi:Bi.default.bool,autoFocus:Bi.default.bool,onDragEnter:Bi.default.func,onDragLeave:Bi.default.func,onDragOver:Bi.default.func,onDrop:Bi.default.func,onDropAccepted:Bi.default.func,onDropRejected:Bi.default.func,onError:Bi.default.func,validator:Bi.default.func};var e4e={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function r4e(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=ps(ps({},ZXt),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,x=e.preventDropOnDocument,S=e.noClick,O=e.noKeyboard,E=e.noDrag,P=e.noDragEventsBubbling,A=e.onError,I=e.validator,R=(0,Rn.useMemo)(function(){return UXt(r)},[r]),N=(0,Rn.useMemo)(function(){return BXt(r)},[r]),j=(0,Rn.useMemo)(function(){return typeof b=="function"?b:GXt},[b]),$=(0,Rn.useMemo)(function(){return typeof h=="function"?h:GXt},[h]),k=(0,Rn.useRef)(null),H=(0,Rn.useRef)(null),V=(0,Rn
`));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};Rhe.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-08-12 16:40:13 +08:00
`)&&(e=e.slice(0,-1))),b_.prototype.equals.call(this,t,e,r)};function pQt(t,e,r){var n=CLn(r,{ignoreWhitespace:!0});return Rhe.diff(t,e,n)}var OLn=new b_;OLn.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var PLn=new b_;PLn.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function i4e(t){"@babel/helpers - typeof";return i4e=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},i4e(t)}var IJ=new b_;IJ.useLongestToken=!0;IJ.tokenize=Rhe.tokenize;IJ.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(a4e(t,null,null,o),o," ")};IJ.equals=function(t,e,r){return b_.prototype.equals.call(IJ,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"),r)};function a4e(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]=a4e(t[i],e,r,n,o);return e.pop(),r.pop(),a}if(t&&t.toJSON&&(t=t.toJSON()),i4e(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]=a4e(t[u],e,r,n,u);e.pop(),r.pop()}else a=t;return a}var s4e=new b_;s4e.tokenize=function(t){return t.slice()};s4e.join=s4e.removeEmpty=function(t){return t};var Mr=F(ee()),_Qt=F(id());var __=F(ee());di();An();$n();Tn();An();var wT=require("obsidian"),Ir=F(ee()),mQt=F(id());di();var hQt=F(ee());function ELn(t){return t.trim().split(`
2025-07-05 20:48:33 +08:00
`).map(r=>"- "+r).join(`
2025-08-12 16:40:13 +08:00
`)}function u4e(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?ELn(a.value):"").join(`
2025-07-05 20:48:33 +08:00
`):r.map(s=>s.value).join(`
`).trim().length>0&&(i="..."),i}).join(`
2025-08-12 16:40:13 +08:00
`)}function RJ(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 NJ="obsidian-copilot-apply-view",Nhe=class extends wT.ItemView{constructor(r){super(r);this.root=null;this.state=null}getViewType(){return NJ}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,mQt.createRoot)(n)),this.root.render(Ir.default.createElement(TLn,{app:this.app,state:this.state,close:()=>this.leaf.detach()}))}},gQt=(0,Ir.memo)(({oldLine:t,newLine:e})=>{let r=dQt(t,e);return Ir.default.createElement(Ir.default.Fragment,null,r.map((n,o)=>n.added?Ir.default.createElement("span",{key:o,className:"tw-text-success"},n.value):n.removed?Ir.default.createElement("span",{key:o,className:"tw-text-error tw-line-through"},n.value):Ir.default.createElement("span",{key:o},n.value)))});gQt.displayName="WordDiff";var TLn=({app:t,state:e,close:r})=>{let[n,o]=(0,hQt.useState)(()=>e.changes.map(p=>({...p,accepted:null}))),i=RJ(n),a=(0,Ir.useRef)([]);if(!e||!e.changes)return fe("Invalid state:",e),Ir.default.createElement("div",{className:"tw-flex tw-h-full tw-flex-col tw-items-center tw-justify-center"},Ir.default.createElement("div",{className:"tw-text-error"},"Error: Invalid state - missing changes"),Ir.default.createElement(be,{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 wT.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 wT.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 wT.TFile)){new wT.Notice("File not found:"+e.path),r();return}await t.vault.modify(h,m),new wT.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(x=>x.added||x.removed),y=b.some(x=>(x.added||x.removed)&&x.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(x=>x===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(x=>x===g);y!==-1&&(h[y]={...h[y],accepted:!1})}),h}),setTimeout(()=>c(p),0)};return Ir.default.createElement("div",{className:"tw-relative tw-flex tw-h-full tw-flex-col"},Ir.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"},Ir.default.createElement(be,{variant:"destructive",size:"sm",onClick:u},Ir.default.createElement(Qi,{className:"tw-size-4"}),"Reject"),Ir.default.createElement(be,{variant:"success",size:"sm",onClick:s},Ir.default.createElement(gc,{className:"tw-size-4"}),"Accept")),Ir.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),Ir.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 Ir.default.createElement("div",{key:m,ref:g=>a.current[m]=g,className:ve("tw-mb-4 tw-overflow-hidden tw-rounded-md")},b==="accepted"?Ir.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>
2025-08-12 16:40:13 +08:00
<div class="tw-text-muted" style="${Y}">${de.trim()}</div>
2025-07-05 20:48:33 +08:00
</details>
2025-08-12 16:40:13 +08:00
`),te=te.replace(/<think>([\s\S]*)$/,(Te,de)=>`<div style="${U}">
2025-07-05 20:48:33 +08:00
<div style="${W}">Thinking...</div>
2025-08-12 16:40:13 +08:00
<div class="tw-text-muted" style="${Y}">${de.trim()}</div>
</div>`),te;let se=/<think>([\s\S]*?)<\/think>/g;return te.replace(se,(Te,de)=>`<details style="${U}">
2025-07-05 20:48:33 +08:00
<summary style="${W}">Thought for a second</summary>
2025-08-12 16:40:13 +08:00
<div class="tw-text-muted" style="${Y}">${de.trim()}</div>
2025-07-05 20:48:33 +08:00
</details>
2025-08-12 16:40:13 +08:00
`)},V=te=>{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(te))!==null;){let se=Y[1],Te=Y.index,de=se.match(/"path"\s*:\s*"([^"]+)"/),Ue=de?de[1].trim():"...";te=te.substring(0,Te)+U(Ue);break}}return te},Q=(te,U,W)=>te.split(/(```[\s\S]*?```|`[^`]*`)/g).map((se,Te)=>Te%2===0?se.replace(U,(de,Ue)=>{let Ke=e.metadataCache.getFirstLinkpathDest(Ue,k);return Ke?W(Ke):de}):se).join(""),Z=j.replace(/\\\[\s*/g,"$$").replace(/\s*\\\]/g,"$$").replace(/\\\(\s*/g,"$").replace(/\s*\\\)/g,"$"),D=V(Z),z=Q(D,/!\[\[(.*?)]]/g,te=>`![](${e.vault.getResourcePath(te)})`),B=H(z),K=y(B);return Q(K,/(?<!!)\[\[([^\]]+)]]/g,te=>`<a href="obsidian://open?file=${encodeURIComponent(te.path)}">${te.basename}</a>`)},[e,r]),y=j=>{let $=j.split(`
2025-07-05 20:48:33 +08:00
#### Sources:
2025-08-12 16:40:13 +08:00
`);if($.length!==2)return j;let[k,H]=$,V=H.split(`
`).map(Q=>{let Z=Q.match(/- \[\[(.*?)\]\]/);return Z?`<li>[[${Z[1]}]]</li>`:Q}).join(`
2025-07-05 20:48:33 +08:00
`);return k+`
<br/>
<details><summary>Sources</summary>
<ul>
`+V+`
</ul>
2025-08-12 16:40:13 +08:00
</details>`};(0,Mr.useEffect)(()=>{let j=[],$=!1;if(p.current&&t.sender!==Ei){p.current.innerHTML="",m.current||(m.current=new ST.Component);let k=g(t.message);if(!$&&(ST.MarkdownRenderer.renderMarkdown(k,p.current,"",m.current),!r)){let H=p.current.querySelectorAll("pre");H.length>0&&H.forEach(V=>{if($)return;let Q=V.querySelector("code");if(!Q)return;let Z=Q.textContent||"";try{if(Z.trim().startsWith("{")&&Z.trim().endsWith("}")){let D=JSON.parse(Z);if(D.type==="composer"&&D.path&&(typeof D.content=="string"||typeof D.canvas_json=="object")){let z;typeof D.content=="string"?z=D.content:z=JSON.stringify(D.canvas_json);let B=D.path.trim();B.startsWith("/")&&(B=B.slice(1));let K=document.createElement("div");V.parentNode?.replaceChild(K,V);let q=(0,_Qt.createRoot)(K);j.push(q);let te=e.vault.getAbstractFileByPath(B),U=[];(async()=>{if(te instanceof ST.TFile){let W=await e.vault.read(te);U=pQt(W,z,{newlineIsToken:!0})}else{let W=B.split("/").pop()?.split(".")[0],Y=z.split(`
2025-07-05 20:48:33 +08:00
`);(Y[0]===`# ${W}
2025-08-12 16:40:13 +08:00
`||Y[0]===`## ${W}`)&&Y.shift(),z=Y.join(`
`)}$||q.render(Mr.default.createElement(bQt,{note_path:B,note_content:z,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,Mr.useEffect)(()=>{l&&h.current&&x(h.current)},[l]),(0,Mr.useEffect)(()=>{f(t.message)},[t.message]);let x=j=>{j.style.height="auto",j.style.height=`${j.scrollHeight}px`},S=j=>{f(j.target.value),x(j.target)},O=j=>{j.nativeEvent.isComposing||(j.key==="Enter"&&!j.shiftKey?(j.preventDefault(),A()):j.key==="Escape"&&(j.preventDefault(),E()))},E=()=>{c(!1),f(t.message)},P=()=>{c(!0)},A=()=>{c(!1),o&&o(d)},I=()=>{t.sources&&t.sources.length>0&&new Ahe(e,t.sources).open()},R=()=>{let j=e.workspace.getMostRecentLeaf();if((!j||!(j.view instanceof ST.MarkdownView))&&(j=e.workspace.getLeaf(!1),!j||!(j.view instanceof ST.MarkdownView)))return;let k=j.view.editor.getSelection().length>0;u6(t.message,k)},N=()=>t.content?Mr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-3"},t.content.map((j,$)=>j.type==="text"?Mr.default.createElement("div",{key:$},t.sender===Ei&&l?Mr.default.createElement("textarea",{ref:h,value:d,onChange:S,onKeyDown:O,autoFocus:!0,className:"edit-textarea"}):t.sender===Ei?Mr.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-break-words tw-text-[calc(var(--font-text-size)_-_2px)] tw-font-normal"},t.message):Mr.default.createElement("div",{ref:p,className:t.isErrorMessage?"tw-text-error":""})):j.type==="image_url"?Mr.default.createElement("div",{key:$,className:"message-image-content"},Mr.default.createElement("img",{src:j.image_url.url,alt:"User uploaded image",className:"chat-message-image"})):null)):t.sender===Ei&&l?Mr.default.createElement("textarea",{ref:h,value:d,onChange:S,onKeyDown:O,autoFocus:!0,className:"edit-textarea"}):t.sender===Ei?Mr.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-break-words tw-text-[calc(var(--font-text-size)_-_2px)] tw-font-normal"},t.message):Mr.default.createElement("div",{ref:p,className:t.isErrorMessage?"tw-text-error":""});return Mr.default.createElement("div",{className:"tw-my-1 tw-flex tw-w-full tw-flex-col"},Mr.default.createElement("div",{className:ve("tw-group tw-mx-2 tw-flex tw-gap-2 tw-rounded-md tw-p-2",t.sender===Ei&&"tw-border tw-border-solid tw-border-border")},Mr.default.createElement("div",{className:"tw-w-6 tw-shrink-0"},t.sender===Ei?Mr.default.createElement(M8,null):Mr.default.createElement(VN,null)),Mr.default.createElement("div",{className:"tw-flex tw-max-w-full tw-grow tw-flex-col tw-gap-2 tw-overflow-hidden"},!l&&Mr.default.createElement(ALn,{context:t.context}),Mr.default.createElement("div",{className:"message-content"},N()),!r&&Mr.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between"},Mr.default.createElement("div",{className:"tw-text-xs tw-text-faint"},t.timestamp?.display),Mr.default.createElement(oQt,{message:t,onCopy:b,isCopied:s,onInsertIntoEditor:R,onRegenerate:n,onEdit:P,onDelete:i,onShowSources:I,hasSources:!!(t.sources&&t.sources.length>0)})))))},l4e=ILn;di();var Vd=F(ee(),1);function vQt(t,e,{checkForDefaultPrevented:r=!0}={}){return function(o){if(t?.(o),r===!1||!o.defaultPrevented)return e?.(o)}}var xQt=F(ee(),1);function wQt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function c4e(...t){return e=>{let r=!1,n=t.map(o=>{let i=wQt(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():wQt(t[o],null)}}}}function SQt(...t){return xQt.useCallback(c4e(...t),t)}var CQt=F(ee(),1),DLn=F(Cs(),1);var Hd=F(ee(),1);var p3=F(bt(),1),f4e=Hd.forwardRef((t,e)=>{let{children:r,...n}=t,o=Hd.Children.toArray(r),i=o.find(RLn);if(i){let a=i.props.children,s=o.map(u=>u===i?Hd.Children.count(a)>1?Hd.Children.only(null):Hd.isValidElement(a)?a.props.children:null:u);return(0,p3.jsx)(d4e,{...n,ref:e,children:Hd.isValidElement(a)?Hd.cloneElement(a,void 0,s):null})}return(0,p3.jsx)(d4e,{...n,ref:e,childr
2025-07-05 20:48:33 +08:00
.block-interactivity-`.concat(t,` {pointer-events: none;}
.allow-interactivity-`).concat(t,` {pointer-events: all;}
2025-08-12 16:40:13 +08:00
`)},CFn=0,h3=[];function mer(t){var e=Pa.useRef([]),r=Pa.useRef([0,0]),n=Pa.useRef(),o=Pa.useState(CFn++)[0],i=Pa.useState(_T)[0],a=Pa.useRef(t);Pa.useEffect(function(){a.current=t},[t]),Pa.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var h=o3([t.lockRef.current],(t.shards||[]).map(per),!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=Pa.useCallback(function(h,b){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!a.current.allowPinchZoom;var g=Fhe(h),y=r.current,x="deltaX"in h?h.deltaX:y[0]-g[0],S="deltaY"in h?h.deltaY:y[1]-g[1],O,E=h.target,P=Math.abs(x)>Math.abs(S)?"h":"v";if("touches"in h&&P==="h"&&E.type==="range")return!1;var A=D4e(P,E);if(!A)return!0;if(A?O=P:(O=P==="v"?"h":"v",A=D4e(P,E)),!A)return!1;if(!n.current&&"changedTouches"in h&&(x||S)&&(n.current=O),!O)return!0;var I=n.current||O;return der(I,b,h,I==="h"?x:S,!0)},[]),u=Pa.useCallback(function(h){var b=h;if(!(!h3.length||h3[h3.length-1]!==i)){var g="deltaY"in b?fer(b):Fhe(b),y=e.current.filter(function(O){return O.name===b.type&&(O.target===b.target||b.target===O.shadowParent)&&xFn(O.delta,g)})[0];if(y&&y.should){b.cancelable&&b.preventDefault();return}if(!y){var x=(a.current.shards||[]).map(per).filter(Boolean).filter(function(O){return O.contains(b.target)}),S=x.length>0?s(b,x[0]):!a.current.noIsolation;S&&b.cancelable&&b.preventDefault()}}},[]),l=Pa.useCallback(function(h,b,g,y){var x={name:h,delta:b,target:g,should:y,shadowParent:OFn(g)};e.current.push(x),setTimeout(function(){e.current=e.current.filter(function(S){return S!==x})},1)},[]),c=Pa.useCallback(function(h){r.current=Fhe(h),n.current=void 0},[]),d=Pa.useCallback(function(h){l(h.type,fer(h),h.target,s(h,t.lockRef.current))},[]),f=Pa.useCallback(function(h){l(h.type,Fhe(h),h.target,s(h,t.lockRef.current))},[]);Pa.useEffect(function(){return h3.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,fk),document.addEventListener("touchmove",u,fk),document.addEventListener("touchstart",c,fk),function(){h3=h3.filter(function(h){return h!==i}),document.removeEventListener("wheel",u,fk),document.removeEventListener("touchmove",u,fk),document.removeEventListener("touchstart",c,fk)}},[]);var p=t.removeScrollBar,m=t.inert;return Pa.createElement(Pa.Fragment,null,m?Pa.createElement(i,{styles:SFn(o)}):null,p?Pa.createElement(rk,{gapMode:t.gapMode}):null)}function OFn(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var her=tk(Lhe,mer);var ger=khe.forwardRef(function(t,e){return khe.createElement(DJ,Oi({},t,{ref:e,sideCar:her}))});ger.classNames=DJ.classNames;var L4e=ger;var Dl=F(bt(),1),F4e="Popover",[yer,lDi]=na(F4e,[A4e]),FJ=A4e(),[PFn,u1]=yer(F4e),ber=t=>{let{__scopePopover:e,children:r,open:n,defaultOpen:o,onOpenChange:i,modal:a=!1}=t,s=FJ(e),u=Ha.useRef(null),[l,c]=Ha.useState(!1),[d=!1,f]=Nd({prop:n,defaultProp:o,onChange:i});return(0,Dl.jsx)(ner,{...s,children:(0,Dl.jsx)(PFn,{scope:e,contentId:Rl(),triggerRef:u,open:d,onOpenChange:f,onOpenToggle:Ha.useCallback(()=>f(p=>!p),[f]),hasCustomAnchor:l,onCustomAnchorAdd:Ha.useCallback(()=>c(!0),[]),onCustomAnchorRemove:Ha.useCallback(()=>c(!1),[]),modal:a,children:r})})};ber.displayName=F4e;var _er="PopoverAnchor",EFn=Ha.forwardRef((t,e)=>{let{__scopePopover:r,...n}=t,o=u1(_er,r),i=FJ(r),{onCustomAnchorAdd:a,onCustomAnchorRemove:s}=o;return Ha.useEffect(()=>(a(),()=>s()),[a,s]),(0,Dl.jsx)(M4e,{...i,...n,ref:e})});EFn.displayName=_er;var ver="PopoverTrigger",wer=Ha.forwardRef((t,e)=>{let{__scopePopover:r,...n}=t,o=u1(ver,r),i=FJ(r),a=v_(e,o.triggerRef),s=(0,Dl.jsx)(Pp.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Per(o.open),...n,ref:a,onClick:aO(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(`
2025-08-12 16:40:13 +08:00
`))},placeholder:"Enter web URLs, one per line",className:"tw-min-h-20 tw-w-full"})),Qt.default.createElement(Bn,{label:"YouTube URLs"},Qt.default.createElement(dT,{value:u.contextSource?.youtubeUrls,onChange:h=>{let g=h.target.value.split(`
`).map(y=>{if(!y.trim())return y;try{let x=new URL(y.trim());return x.hostname.includes("youtube.com")||x.hostname.includes("youtu.be"),y}catch{return y}});p("contextSource.youtubeUrls",g.join(`
`))},placeholder:"Enter YouTube URLs, one per line",className:"tw-min-h-20 tw-w-full"})))),Qt.default.createElement("div",{className:"tw-mt-4 tw-flex tw-items-center tw-justify-end tw-gap-2"},Qt.default.createElement(be,{variant:"ghost",onClick:r,disabled:o},"Cancel"),Qt.default.createElement(be,{onClick:m,disabled:o||!f()},o?"Saving...":"Save")))}var YJ=class extends D3.Modal{constructor(r,n,o){super(r);this.onSave=n;this.initialProject=o}onOpen(){let{contentEl:r}=this;this.root=(0,prr.createRoot)(r);let n=async i=>{await this.onSave(i),this.close()},o=()=>{this.close()};this.root.render(Qt.default.createElement(x$n,{initialProject:this.initialProject,onSave:n,onCancel:o}))}onClose(){this.root.unmount()}};di();var Ui=F(ee());var pt=F(ee(),1),U3e=F(Cs(),1);var hs=F(ee(),1);var w3e=F(bt(),1),S$n="DismissableLayer",v3e="dismissableLayer.update",C$n="dismissableLayer.pointerDownOutside",O$n="dismissableLayer.focusOutside",mrr,grr=hs.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),x3e=hs.forwardRef((t,e)=>{let{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:n,onPointerDownOutside:o,onFocusOutside:i,onInteractOutside:a,onDismiss:s,...u}=t,l=hs.useContext(grr),[c,d]=hs.useState(null),f=c?.ownerDocument??globalThis?.document,[,p]=hs.useState({}),m=zi(e,P=>d(P)),h=Array.from(l.layers),[b]=[...l.layersWithOutsidePointerEventsDisabled].slice(-1),g=h.indexOf(b),y=c?h.indexOf(c):-1,x=l.layersWithOutsidePointerEventsDisabled.size>0,S=y>=g,O=T$n(P=>{let A=P.target,I=[...l.branches].some(R=>R.contains(A));!S||I||(o?.(P),a?.(P),P.defaultPrevented||s?.())},f),E=A$n(P=>{let A=P.target;[...l.branches].some(R=>R.contains(A))||(i?.(P),a?.(P),P.defaultPrevented||s?.())},f);return $R(P=>{y===l.layers.size-1&&(n?.(P),!P.defaultPrevented&&s&&(P.preventDefault(),s()))},f),hs.useEffect(()=>{if(c)return r&&(l.layersWithOutsidePointerEventsDisabled.size===0&&(mrr=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),l.layersWithOutsidePointerEventsDisabled.add(c)),l.layers.add(c),hrr(),()=>{r&&l.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=mrr)}},[c,f,r,l]),hs.useEffect(()=>()=>{c&&(l.layers.delete(c),l.layersWithOutsidePointerEventsDisabled.delete(c),hrr())},[c,l]),hs.useEffect(()=>{let P=()=>p({});return document.addEventListener(v3e,P),()=>document.removeEventListener(v3e,P)},[]),(0,w3e.jsx)(Po.div,{...u,ref:m,style:{pointerEvents:x?S?"auto":"none":void 0,...t.style},onFocusCapture:Ni(t.onFocusCapture,E.onFocusCapture),onBlurCapture:Ni(t.onBlurCapture,E.onBlurCapture),onPointerDownCapture:Ni(t.onPointerDownCapture,O.onPointerDownCapture)})});x3e.displayName=S$n;var P$n="DismissableLayerBranch",E$n=hs.forwardRef((t,e)=>{let r=hs.useContext(grr),n=hs.useRef(null),o=zi(e,n);return hs.useEffect(()=>{let i=n.current;if(i)return r.branches.add(i),()=>{r.branches.delete(i)}},[r.branches]),(0,w3e.jsx)(Po.div,{...t,ref:o})});E$n.displayName=P$n;function T$n(t,e=globalThis?.document){let r=Qr(t),n=hs.useRef(!1),o=hs.useRef(()=>{});return hs.useEffect(()=>{let i=s=>{if(s.target&&!n.current){let l=function(){yrr(C$n,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 A$n(t,e=globalThis?.document){let r=Qr(t),n=hs.useRef(!1);return hs.useEffect(()=>{let o=i=>{i.target&&!n.current&&yrr(O$n,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 hrr(){let t=new CustomEvent(v3e);document.dispatchEvent(t)}function yrr(t,e,r,{discrete:n}){let o=r.originalEvent.target,i=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail
2025-07-05 20:48:33 +08:00
.block-interactivity-`.concat(t,` {pointer-events: none;}
.allow-interactivity-`).concat(t,` {pointer-events: all;}
2025-08-12 16:40:13 +08:00
`)},szn=0,F3=[];function Xrr(t){var e=Ea.useRef([]),r=Ea.useRef([0,0]),n=Ea.useRef(),o=Ea.useState(szn++)[0],i=Ea.useState(_T)[0],a=Ea.useRef(t);Ea.useEffect(function(){a.current=t},[t]),Ea.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var h=o3([t.lockRef.current],(t.shards||[]).map(Yrr),!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=Ea.useCallback(function(h,b){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!a.current.allowPinchZoom;var g=yge(h),y=r.current,x="deltaX"in h?h.deltaX:y[0]-g[0],S="deltaY"in h?h.deltaY:y[1]-g[1],O,E=h.target,P=Math.abs(x)>Math.abs(S)?"h":"v";if("touches"in h&&P==="h"&&E.type==="range")return!1;var A=L3e(P,E);if(!A)return!0;if(A?O=P:(O=P==="v"?"h":"v",A=L3e(P,E)),!A)return!1;if(!n.current&&"changedTouches"in h&&(x||S)&&(n.current=O),!O)return!0;var I=n.current||O;return Jrr(I,b,h,I==="h"?x:S,!0)},[]),u=Ea.useCallback(function(h){var b=h;if(!(!F3.length||F3[F3.length-1]!==i)){var g="deltaY"in b?Zrr(b):yge(b),y=e.current.filter(function(O){return O.name===b.type&&(O.target===b.target||b.target===O.shadowParent)&&izn(O.delta,g)})[0];if(y&&y.should){b.cancelable&&b.preventDefault();return}if(!y){var x=(a.current.shards||[]).map(Yrr).filter(Boolean).filter(function(O){return O.contains(b.target)}),S=x.length>0?s(b,x[0]):!a.current.noIsolation;S&&b.cancelable&&b.preventDefault()}}},[]),l=Ea.useCallback(function(h,b,g,y){var x={name:h,delta:b,target:g,should:y,shadowParent:uzn(g)};e.current.push(x),setTimeout(function(){e.current=e.current.filter(function(S){return S!==x})},1)},[]),c=Ea.useCallback(function(h){r.current=yge(h),n.current=void 0},[]),d=Ea.useCallback(function(h){l(h.type,Zrr(h),h.target,s(h,t.lockRef.current))},[]),f=Ea.useCallback(function(h){l(h.type,yge(h),h.target,s(h,t.lockRef.current))},[]);Ea.useEffect(function(){return F3.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",u,bk),document.addEventListener("touchmove",u,bk),document.addEventListener("touchstart",c,bk),function(){F3=F3.filter(function(h){return h!==i}),document.removeEventListener("wheel",u,bk),document.removeEventListener("touchmove",u,bk),document.removeEventListener("touchstart",c,bk)}},[]);var p=t.removeScrollBar,m=t.inert;return Ea.createElement(Ea.Fragment,null,m?Ea.createElement(i,{styles:azn(o)}):null,p?Ea.createElement(rk,{gapMode:t.gapMode}):null)}function uzn(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var Qrr=tk(gge,Xrr);var enr=bge.forwardRef(function(t,e){return bge.createElement(XJ,Oi({},t,{ref:e,sideCar:Qrr}))});enr.classNames=XJ.classNames;var e7=enr;var mr=F(bt(),1),lzn=[" ","Enter","ArrowUp","ArrowDown"],czn=[" ","Enter"],r7="Select",[vge,wge,dzn]=pge(r7),[k3,T$i]=na(r7,[dzn,T3e]),xge=T3e(),[fzn,y1]=k3(r7),[pzn,mzn]=k3(r7),tnr=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=xge(e),[b,g]=pt.useState(null),[y,x]=pt.useState(null),[S,O]=pt.useState(!1),E=kR(l),[P=!1,A]=Nd({prop:n,defaultProp:o,onChange:i}),[I,R]=Nd({prop:a,defaultProp:s,onChange:u}),N=pt.useRef(null),j=b?m||!!b.closest("form"):!0,[$,k]=pt.useState(new Set),H=Array.from($).map(V=>V.props.value).join(";");return(0,mr.jsx)(krr,{...h,children:(0,mr.jsxs)(fzn,{required:p,scope:e,trigger:b,onTriggerChange:g,valueNode:y,onValueNodeChange:x,valueNodeHasChildren:S,onValueNodeHasChildrenChange:O,contentId:Rl(),value:I,onValueChange:R,open:P,onOpenChange:A,dir:E,triggerPointerDownPosRef:N,disabled:f,children:[(0,mr.jsx)(vge.Provider,{scope:e,children:(0,mr.jsx)(pzn,{scope:t.__scopeSelect,onNativeOptionAdd:pt.useCallback(V=>{k(Q=>new Set(Q).add(V))},[]),onNativeOption
2025-07-05 20:48:33 +08:00
<output_format>
2025-08-12 16:40:13 +08:00
`+pe+`
</output_format>`),Oe&&(ue+=" "+Oe.join(`
`));let Pe={notes:Ne,urls:$e||[],selectedTextContexts:k};h(""),N([]),x(!0),O(K_.DEFAULT);let Ae=await i.sendMessage(ue,Pe,d,A);m&&r(m),a.autosaveChat&&U();let ot=i.getLLMMessage(Ae);ot&&await Sge(ot,t,l,p,g,{debug:a.debug,updateLoadingMessage:O}),a.autosaveChat&&U()}catch(qt){console.error("Error sending message:",qt),new uc.Notice("Failed to send message. Please try again.")}finally{x(!1),O(K_.DEFAULT)}},U=(0,Rr.useCallback)(async()=>{if(!q){console.error("App instance is not available.");return}try{await i.saveChat(c)}catch(Oe){console.error("Error saving chat as note:",ci(Oe)),new uc.Notice("Failed to save chat as note. Check console for details.")}},[q,i,c]),W=(0,Rr.useCallback)(Oe=>{b&&(a.debug&&console.log(`stopping generation..., reason: ${Oe}`),b.abort(Oe),x(!1),O(K_.DEFAULT))},[b,a.debug]),Y=(0,Rr.useCallback)(async Oe=>{if(Oe<=0){new uc.Notice("Cannot regenerate the first message.");return}let $e=u[Oe];if(!$e){new uc.Notice("Message not found.");return}x(!0);try{await i.regenerateMessage($e.id,p,l)?a.debug&&console.log("Message regenerated successfully"):new uc.Notice("Failed to regenerate message. Please try again."),a.autosaveChat&&U()}catch(ce){console.error("Error regenerating message:",ce),new uc.Notice("Failed to regenerate message. Please try again.")}finally{x(!1)}},[u,i,a.debug,a.autosaveChat,U,l]),se=(0,Rr.useCallback)(async(Oe,$e)=>{let ce=u[Oe];if(!(!ce||ce.message===$e))try{if(!await i.editMessage(ce.id,$e,d,A)){new uc.Notice("Failed to edit message. Please try again.");return}if(ce.sender===Ei){let Ze=Oe<u.length-1;if(await i.truncateAfterMessageId(ce.id),Ze){x(!0);try{let Ne=i.getLLMMessage(ce.id);Ne&&await Sge(Ne,t,l,p,g,{debug:a.debug,updateLoadingMessage:O})}catch(Ne){console.error("Error regenerating AI response:",Ne),new uc.Notice("Failed to regenerate AI response. Please try again.")}finally{x(!1)}}}a.autosaveChat&&U()}catch(qt){console.error("Error editing message:",qt),new uc.Notice("Failed to edit message. Please try again.")}},[u,i,d,A,l,t,a.debug,a.autosaveChat,U]);(0,Rr.useEffect)(((Oe,$e)=>()=>{let ce=ae().debug,qt=async Ze=>{let Ne=await $e(Ze.detail.selectedText,Ze.detail.eventSubtype);try{let ue=await i.sendMessage(Ne,{notes:[],urls:[],selectedTextContexts:[]},d,A),pe=i.getLLMMessage(ue);pe&&(x(!0),await Sge(pe,t,l,p,g,{debug:ce,ignoreSystemMessage:!0}),x(!1))}catch(ue){console.error("Error processing adhoc prompt:",ue),x(!1)}};return s?.addEventListener(Oe,qt),()=>{s?.removeEventListener(Oe,qt)}})(qr.APPLY_ADHOC_PROMPT,async(Oe,$e)=>$e?(await tJ($e,Oe,q.vault,q.workspace.getActiveFile())).processedPrompt:Oe),[]),(0,Rr.useEffect)(()=>{e&&e(U)},[e,U]);let de=(0,Rr.useCallback)(Oe=>{let $e=a.projectList||[];if($e.findIndex(Ne=>Ne.name===Oe.name)>=0)throw new Error(`Project "${Oe.name}" already exists, please use a different name`);let qt=[...$e,Oe];return ht("projectList",qt),iu()?.id===Oe.id?xhe().then(()=>{new uc.Notice(`${Oe.name} added and context loaded`)}).catch(Ne=>{console.error("Error loading project context:",Ne),new uc.Notice(`${Oe.name} added but context loading failed`)}):new uc.Notice(`${Oe.name} added successfully`),!0},[a.projectList]),Ue=(0,Rr.useCallback)((Oe,$e)=>{let ce=a.projectList||[];if(!ce.find(ue=>ue.name===Oe.name))throw new Error(`Project "${Oe.name}" does not exist`);let Ze=ce.map(ue=>ue.name===Oe.name?$e:ue);return ht("projectList",Ze),iu()?.id===Oe.id?(PN($e),xhe().then(()=>{new uc.Notice(`${Oe.name} updated and context reloaded`)}).catch(ue=>{console.error("Error reloading project context:",ue),new uc.Notice(`${Oe.name} updated but context reload failed`)})):new uc.Notice(`${Oe.name} updated successfully`),!0},[a.projectList]),Ke=(0,Rr.useCallback)(Oe=>{h($e=>`${$e} ${Oe} `)},[]),at=(0,Rr.useCallback)(Oe=>{yJe(Oe)},[]),hr=(0,Rr.useCallback)(async Oe=>{let $e=u[Oe];if(!$e){new uc.Notice("Message not found.");return}try{await i.deleteMessage($e.id)||new uc.Notice("Failed to delete message. Please try again.")}catch(ce){console.error("Error deleting message:",ce),new uc.Notice("Failed to delete message. Please try again.")}},[u,i]),Nn=(0,Rr.useCallback)
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-08-12 16:40:13 +08:00
`},Uzn={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 qzn(t){let{announcements:e=Uzn,container:r,hiddenTextDescribedById:n,screenReaderInstructions:o=Bzn}=t,{announce:i,announcement:a}=oor(),s=xk("DndLiveRegion"),[u,l]=(0,Me.useState)(!1);if((0,Me.useEffect)(()=>{l(!0)},[]),$zn((0,Me.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=Me.default.createElement(Me.default.Fragment,null,Me.default.createElement(ror,{id:n,value:o.draggable}),Me.default.createElement(nor,{id:s,announcement:a}));return r?(0,Pk.createPortal)(c,r):c}var cc;(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"})(cc||(cc={}));function Rge(){}function q3(t,e){return(0,Me.useMemo)(()=>({sensor:t,options:e??{}}),[t,e])}function jge(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return(0,Me.useMemo)(()=>[...e].filter(n=>n!=null),[...e])}var C_=Object.freeze({x:0,y:0});function _or(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}function vor(t,e){let{data:{value:r}}=t,{data:{value:n}}=e;return r-n}function Hzn(t,e){let{data:{value:r}}=t,{data:{value:n}}=e;return n-r}function ior(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 uHe(t,e){if(!t||t.length===0)return null;let[r]=t;return e?r[e]:r}function aor(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 m7=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=aor(e,e.left,e.top),i=[];for(let a of n){let{id:s}=a,u=r.get(s);if(u){let l=_or(aor(u),o);i.push({id:s,data:{droppableContainer:a,value:l}})}}return i.sort(vor)},wor=t=>{let{collisionRect:e,droppableRects:r,droppableContainers:n}=t,o=ior(e),i=[];for(let a of n){let{id:s}=a,u=r.get(s);if(u){let l=ior(u),c=o.reduce((f,p,m)=>f+_or(l[m],p),0),d=Number((c/4).toFixed(4));i.push({id:s,data:{droppableContainer:a,value:d}})}}return i.sort(vor)};function Vzn(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 Wzn=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=Vzn(s,e);u>0&&o.push({id:a,data:{droppableContainer:i,value:u}})}}return o.sort(Hzn)};function Kzn(t,e,r){return{...t,scaleX:e&&r?e.width/r.width:1,scaleY:e&&r?e.height/r.height:1}}function xor(t,e){return t&&e?{x:t.left-e.left,y:t.top-e.top}:C_}function Gzn(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 Jzn=Gzn(1);function Zzn(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-08-12 16:40:13 +08:00
For more information, see https://radix-ui.com/primitives/docs/components/${e.docsSlug}`;return sa.useEffect(()=>{t&&(document.getElementById(t)||console.error(r))},[r,t]),null},IUn="DialogDescriptionWarning",MUn=({contentRef:t,descriptionId:e})=>{let n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${wir(IUn).contentName}}.`;return sa.useEffect(()=>{let o=t.current?.getAttribute("aria-describedby");e&&o&&(document.getElementById(e)||console.warn(n))},[n,t,e]),null},xir=sir,Sir=lir,Cir=dir,xHe=fir,SHe=pir,CHe=hir,OHe=yir,Oir=_ir;An();$n();var Hge=xir,Pir=Sir,NUn=Cir;var Eir=Zd.forwardRef(({className:t,...e},r)=>Zd.createElement(xHe,{ref:r,className:ve("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}));Eir.displayName=xHe.displayName;var w7=Zd.forwardRef(({className:t,children:e,container:r,...n},o)=>Zd.createElement(NUn,{container:r},Zd.createElement(Eir,null),Zd.createElement(SHe,{ref:o,className:ve("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,Zd.createElement(Oir,{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"},Zd.createElement(Qi,{className:"tw-size-4"}),Zd.createElement("span",{className:"tw-sr-only"},"Close")))));w7.displayName=SHe.displayName;var x7=({className:t,...e})=>Zd.createElement("div",{className:ve("tw-flex tw-flex-col tw-space-y-0.5 tw-text-center sm:tw-text-left",t),...e});x7.displayName="DialogHeader";var jUn=({className:t,...e})=>Zd.createElement("div",{className:ve("tw-flex tw-flex-col-reverse sm:tw-flex-row sm:tw-justify-end sm:tw-space-x-2",t),...e});jUn.displayName="DialogFooter";var S7=Zd.forwardRef(({className:t,...e},r)=>Zd.createElement(CHe,{ref:r,className:ve("tw-mt-0 tw-text-lg tw-font-semibold tw-leading-none tw-tracking-tight",t),...e}));S7.displayName=CHe.displayName;var C7=Zd.forwardRef(({className:t,...e},r)=>Zd.createElement(OHe,{ref:r,className:ve("tw-text-sm tw-text-muted",t),...e}));C7.displayName=OHe.displayName;on();function Pn(t){let{title:e,description:r,className:n,disabled:o}=t,{modalContainer:i}=$3(),a="onChange"in t?t.onChange:void 0,s=(0,Ta.useMemo)(()=>{if(a)return FY(l=>{a(l)},1e3)},[a]),u=()=>{switch(t.type){case"text":case"number":return Ta.default.createElement(si,{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 Ta.default.createElement(fO,{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 Ta.default.createElement(dT,{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 Ta.default.createElement(u3,{checked:t.checked,onCheckedChange:t.onCheckedChange,disabled:o});case"select":return Ta.default.createElement("div",{className:"tw-group tw-relative tw-w-full sm:tw-w-[200px]"},Ta.default.createElement("select",{value:t.value?.toString(),onChange:l=>t.onChange?.(l.target.value),disabled:o,className:ve("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-08-12 16:40:13 +08:00
${a.content}`}):e.push(a)}await Fd.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 ${DR()}.`;r.length>0&&(await DUn(r),i+=`
2025-07-05 20:48:33 +08:00
2025-08-12 16:40:13 +08:00
We found ${r.length} unsupported commands. They are saved in ${DR()}/unsupported. To fix them, please resolve the errors and move the note file out of the unsupported folder.`),ht("inlineEditCommands",[]),new $d(app,()=>{},i,"\u{1F680} New Copilot Custom Commands","OK","").open()}async function PHe(){let t=Mm(),e=QGt.filter(n=>!t.some(o=>o.title===n.title)),r=[...t,...e];Fd.getInstance().updateCommands(r)}async function Air(){if(ae().suggestedDefaultCommands)return;Mm().length===0&&(new $d(app,()=>{PHe()},"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(),ht("suggestedDefaultCommands",!0))}var LUn=({command:t,commands:e,onUpdate:r,onRemove:n,onCopy:o})=>{let{attributes:i,listeners:a,setNodeRef:s,transform:u,transition:l,isDragging:c}=_7({id:t.title}),d={transform:S_.Transform.toString(u),transition:l},f=()=>{n(t)};return Dt.default.createElement(w1,{ref:s,style:d,className:ve("tw-transition-colors",c&&"tw-relative tw-z-[100] tw-cursor-grabbing tw-shadow-lg tw-backdrop-blur-sm tw-border-accent/50")},Dt.default.createElement(Bf,{className:"tw-w-10"},Dt.default.createElement("div",{...i,...a,className:"tw-flex tw-cursor-grab tw-items-center tw-justify-center"},Dt.default.createElement(nv,{className:"tw-size-4"}))),Dt.default.createElement(Bf,null,t.title),Dt.default.createElement(Bf,{className:"tw-text-center"},Dt.default.createElement(Ld,{checked:t.showInContextMenu,onCheckedChange:p=>{r({...t,showInContextMenu:p===!0},t.title)},className:"tw-mx-auto"})),Dt.default.createElement(Bf,{className:"tw-text-center"},Dt.default.createElement(Ld,{checked:t.showInSlashMenu,onCheckedChange:p=>r({...t,showInSlashMenu:p===!0},t.title),className:"tw-mx-auto"})),Dt.default.createElement(Bf,{className:"tw-text-center"},Dt.default.createElement("div",{className:"tw-flex tw-justify-center tw-space-x-1"},Dt.default.createElement(be,{variant:"ghost",size:"icon",onClick:()=>{new HF(app,e,t,async m=>{await r(m,t.title)}).open()}},Dt.default.createElement(iv,{className:"tw-size-4"})),Dt.default.createElement(be,{variant:"ghost",size:"icon",onClick:()=>o(t),title:"Copy command"},Dt.default.createElement(th,{className:"tw-size-4"})),Dt.default.createElement(be,{variant:"ghost",size:"icon",onClick:()=>{new $d(app,f,`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()}},Dt.default.createElement(oh,{className:"tw-size-4"})))))},Iir=()=>{let t=eJt(),e=(0,Dt.useMemo)(()=>eJ([...t]),[t]),r=Hn(),n=jge(q3(C1,{activationConstraint:{distance:8}}),q3(S1,{coordinateGetter:Bge})),o=async(l,c)=>{await Fd.getInstance().updateCommand(l,c)},i=async l=>{await Fd.getInstance().createCommand(l)},a=async l=>{try{await Fd.getInstance().deleteCommand(l),new Vge.Notice(`Command "${l.title}" deleted successfully!`)}catch(c){throw console.error("Failed to delete command:",c),new Vge.Notice("Failed to delete command. Please try again."),c}},s=async l=>{try{let c=nJt(l.title,e),d={...l,title:c};await Fd.getInstance().createCommand(d,{autoOrder:!1})}catch(c){console.error("Failed to copy command:",c),new Vge.Notice("Failed to copy command. Please try again.")}},u=async l=>{let{active:c,over:d}=l;if(!d||c.id===d.id)return;let f=e.findIndex(b=>b.title===c.id),p=e.findIndex(b=>b.title===d.id);if(f===-1||p===-1)return;let m=[...e],[h]=m.splice(f,1);m.splice(p,0,h),await Fd.getInstance().reorderCommands(m)};return Dt.default.createElement("div",{className:"tw-space-y-4"},Dt.default.createElement("section",null,Dt.default.createElement("div",{className:"tw-mb-4 tw-flex tw-flex-col tw-gap-2"},Dt.default.createElement("div",{className:"tw-text-xl tw-font-bold"},"Custom Commands"),Dt.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 ",
detail: `+B)}return z}finally{clearTimeout(D)}},k;try{k=await $(!1)}catch(Q){console.log("First fetch attempt failed, trying with safeFetch...");try{k=await $(!0)}catch(Z){let D=`
without CORS Error: `+ci(Q)+`
with CORS Error: `+ci(Z);throw new Error(D)}}let H=await k.json(),V=Dir(I,H);l(Q=>({...Q,[I]:V})),d(null)}catch(N){console.error(`Error fetching models for ${I}:`,N),p(I),d(null),new P_.Notice(`Failed to load models for ${op(I)}: ${ci(N)}`,5e3)}},A=async()=>{if(!m){new P_.Notice("Please select a model first");return}g(!0);try{let I=x(m.provider),R={name:m.name,provider:m.provider,apiKey:I,enabled:!0};if(await Ec.instance.getCurrentChainManager().chatModelManager.ping(R),e.activeModels.find(j=>j.name===m.name&&j.provider===m.provider))new P_.Notice(`Model ${m.name} verified successfully! It already exists in your models list.`);else{let j=[...e.activeModels,R];ht("activeModels",j),new P_.Notice(`Model ${m.name} verified successfully and added to your models list!`)}}catch(I){console.error("Model verification failed:",I),new P_.Notice("Model verification failed: "+ci(I),1e4)}finally{g(!1)}};return Yt.default.createElement("div",{className:"tw-max-h-[600px] tw-overflow-y-auto tw-p-4 sm:tw-max-w-[500px]"},Yt.default.createElement("div",{className:"tw-mb-4"},Yt.default.createElement("h2",{className:"tw-text-xl tw-font-bold"},"AI Provider Settings"),Yt.default.createElement("p",{className:"tw-text-sm tw-text-muted"},"Configure your AI providers by adding their API keys.")),Yt.default.createElement("div",{className:"tw-space-y-6 tw-py-4"},Yt.default.createElement("div",{className:"tw-space-y-4"},S.map(I=>Yt.default.createElement(Yt.default.Fragment,{key:I.provider},Yt.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Yt.default.createElement("div",{className:"tw-flex tw-items-end tw-gap-2 tw-font-medium"},Yt.default.createElement("div",{className:"tw-truncate"},op(I.provider))),Yt.default.createElement("div",{className:"tw-flex tw-flex-row tw-items-center tw-gap-2"},Yt.default.createElement("div",{className:"tw-flex-1"},Yt.default.createElement(fO,{className:"tw-max-w-full",value:I.apiKey,onChange:R=>O(I.provider,R),disabled:r.has(I.provider)})),Yt.default.createElement("div",{className:"tw-w-[72px]"},I.isVerified?Yt.default.createElement("span",{className:"tw-flex tw-h-9 tw-items-center tw-justify-center tw-text-sm tw-text-success"},"Verified"):Yt.default.createElement(be,{onClick:()=>E(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)?Yt.default.createElement(yc,{className:"tw-mr-2 tw-size-4 tw-animate-spin"}):"Verify")),Yt.default.createElement("div",{className:""},Yt.default.createElement(be,{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&&P(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?Yt.default.createElement(fb,{className:"tw-ml-1 tw-size-4"}):Yt.default.createElement(Xi,{className:"tw-ml-1 tw-size-4"})))),Yt.default.createElement("div",null,V_(I.provider).keyManagementURL&&Yt.default.createElement("a",{href:V_(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 ",op(I.provider)," Key"))),Yt.default.createElement(CT,{open:a===I.provider,className:"tw-mt-2"},Yt.default.createElement(OT,{className:"tw-rounded-md tw-p-3"},Yt.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Yt.default.createElement(Bn,{label:"Model",description:"Add the currently selected model to model List. After adding, please check the Model Tab."},Yt.default.createElement("div",null,Yt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Yt.default.createElement("div",{className:"tw-flex-1"},Yt.default.createElement(cge,{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.
[Timestamp: ${n}]`}).join(`
`)}parseChatContent(e){let r=[],n=e.match(/^---\n([\s\S]*?)\n---/),o=e;n&&(o=e.slice(n[0].length).trim());let i=/\*\*(user|ai)\*\*: ([\s\S]*?)(?=(?:\n\*\*(?:user|ai)\*\*: )|$)/g,a;for(;(a=i.exec(o))!==null;){let s=a[1]==="user"?Ei:mg,u=a[2].trim(),l=u.split(`
`),c=u,d="Unknown time",f=l.length-1;if(f>0&&l[f].startsWith("[Timestamp: ")){let m=l[f].match(/\[Timestamp: (.*?)\]/);m&&(d=m[1],c=l.slice(0,f).join(`
`).trim())}let p;if(d!=="Unknown time"){let m=new Date(d);isNaN(m.getTime())||(p=m.getTime())}r.push({message:c,sender:s,isVisible:!0,timestamp:p?{epoch:p,display:d,fileName:""}:null})}return r}generateFileName(e,r){let n=ae(),i=Bs(new Date(r)).fileName,a=e.find(f=>f.sender===Ei),s=a?a.message.split(/\s+/).slice(0,10).join(" ").replace(/[\\/:*?"<>|]/g,"").trim():"Untitled Chat",u=n.defaultConversationNoteName||"{$date}_{$time}__{$topic}";u=u.replace("{$topic}",s.slice(0,100).replace(/\s+/g,"_")).replace("{$date}",i.split("_")[0]).replace("{$time}",i.split("_")[1]);let l=u.replace(/[\\/:*?"<>|]/g,"_"),c=iu(),d=c?`${c.id}__`:"";return`${n.defaultSaveFolder}/${d}${l}.md`}generateNoteContent(e,r,n){let o=ae(),i=iu();return`---
epoch: ${r}
modelKey: ${n}
${i?`projectId: ${i.id}`:""}
${i?`projectName: ${i.name}`:""}
tags:
- ${o.defaultConversationTag}
---
${e}`}};Ur();var oye=class{constructor(e,r,n,o){this.messageRepo=e;this.chainManager=r;this.fileParserManager=n;this.plugin=o;this.projectMessageRepos=new Map;this.defaultProjectKey="defaultProjectKey";this.lastKnownProjectId=null;this.contextManager=nye.getInstance(),this.projectMessageRepos.set(this.defaultProjectKey,e),this.persistenceManager=new T7(o.app,e)}getCurrentMessageRepo(){let e=this.plugin.projectManager.getCurrentProjectId(),r=e??this.defaultProjectKey;if(this.lastKnownProjectId!==e&&(J(`[ChatManager] Project changed from ${this.lastKnownProjectId} to ${e}`),this.lastKnownProjectId=e),!this.projectMessageRepos.has(r)){J(`[ChatManager] Creating new message repository for project: ${r}`);let o=new K3;this.projectMessageRepos.set(r,o)}let n=this.projectMessageRepos.get(r);return this.persistenceManager=new T7(this.plugin.app,n),n}async sendMessage(e,r,n,o=!1){try{J(`[ChatManager] Sending message: "${e}"`);let i=this.plugin.app.workspace.getActiveFile(),a={...r};if(o&&i){let d=r.notes||[],f=d.some(p=>p.path===i.path);a.notes=f?d:[...d,i]}let s=this.getCurrentMessageRepo(),u=s.addMessage(e,e,Ei,a),l=s.getMessage(u);if(!l)throw new Error(`Failed to retrieve message ${u}`);let c=await this.contextManager.processMessageContext(l,this.fileParserManager,this.plugin.app.vault,n,o,i);return s.updateProcessedText(u,c),J(`[ChatManager] Successfully sent message ${u}`),u}catch(i){throw J("[ChatManager] Error sending message:",i),i}}async editMessage(e,r,n,o=!1){try{J(`[ChatManager] Editing message ${e}: "${r}"`);let i=this.getCurrentMessageRepo();if(!i.editMessage(e,r))return!1;let s=this.plugin.app.workspace.getActiveFile();return await this.contextManager.reprocessMessageContext(e,i,this.fileParserManager,this.plugin.app.vault,n,o,s),await this.updateChainMemory(),J(`[ChatManager] Successfully edited message ${e}`),!0}catch(i){return J(`[ChatManager] Error editing message ${e}:`,i),!1}}async regenerateMessage(e,r,n){try{J(`[ChatManager] Regenerating message ${e}`);let o=this.getCurrentMessageRepo();if(!o.getMessage(e))return J(`[ChatManager] Message not found: ${e}`),!1;let a=o.getDisplayMessages(),s=a.findIndex(d=>d.id===e);if(s<=0)return J("[ChatManager] Cannot regenerate first message or no user message found"),!1;let u=a[s-1];if(u.sender!==Ei)return J("[ChatManager] Previous message is not from user"),!1;if(o.truncateAfter(s-1),await this.updateChainMemory(),!u.id)return J("[ChatManager] User message has no ID for regeneration"),!1;let l=o.getLLMMessage(u.id);if(!l)return J("[ChatManager] LLM message not found for regeneration"),!1;let c=new AbortController;return await this.chainManager.runChain(l,c,r,n,{debug:ae().debug}),J(`[ChatManager] Successfully regenerated message ${e}`),!0}catch(o){return J(`[ChatManager] Error regenerating message ${e}:`,o),!1}}async deleteMessage(e){try{return J(`[ChatManager] Deleting message ${e}`),this.getCurrentMessageRepo().deleteMessage(e)?(await this.updateChainMemory(),J(`[ChatManager] Successfully deleted message ${e}`),!0):!1}catch(r){return J(`[ChatManager] Error deleting message ${e}:`,r),!1}}addDisplayMessage(e,r,n){return this.getCurrentMessageRepo().addDisplayOnlyMessage(e,r,n)}addFullMessage(e){return this.getCurrentMessageRepo().addFullMessage(e)}clearMessages(){this.getCurrentMessageRepo().clear(),this.chainManager.memoryManager.clearChatMemory(),J("[ChatManager] Cleared all messages")}async truncateAfterMessageId(e){this.getCurrentMessageRepo().truncateAfterMessageId(e),await this.updateChainMemory(),J(`[ChatManager] Truncated messages after ${e}`)}getDisplayMessages(){return this.getCurrentMessageRepo().getDisplayMessages()}getLLMMessages(){return this.getCurrentMessageRepo().getLLMMessages()}getMessage(e){return this.getCurrentMessageRepo().getMessage(e)}getLLMMessage(e){return this.getCurrentMessageRepo().getLLMMessage(e)}async updateChainMemory(){try{let r=this.getCurrentMessageRepo().getLLMMessages();await OGt(r,this.chainManager.memoryManager),J(`[ChatManager] Updated chain memory with ${r.length} messages`)}catch(e){J("[ChatManager] Error updating chain memory:
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
*)
2025-08-12 16:40:13 +08:00
@langchain/core/dist/utils/js-sha256/hash.js:
(**
* [js-sha256]{@link https://github.com/emn178/js-sha256}
*
* @version 0.11.1
* @author Chen, Yi-Cyuan [emn178@gmail.com]
* @copyright Chen, Yi-Cyuan 2014-2025
* @license MIT
*)
2025-07-05 20:48:33 +08:00
@google/generative-ai/dist/index.mjs:
(**
* @license
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*)
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 */